diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d89fea47f2..a8ed775e7e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,15 +2,19 @@ # RxDB Changelog -- ADD helpers for the new server plugin -- ADD `RxJsonSchema.internalIndexes` -- ADD(opfs-storage) allow to set `jsonPositionSize` to increase the maxium database size to be bigger than 100 MegaByte. + +### 15.4.0 (22 January 2024) + +- ADD helpers for the new server plugin +- ADD `RxJsonSchema.internalIndexes` +- ADD(opfs-storage) allow to set `jsonPositionSize` to increase the maxium database size to be bigger than 100 MegaByte. + ### 15.3.0 (15 January 2024) - ADD tutorial on [how to start a HTTP replication with a custom server](https://rxdb.info/replication-http.html) diff --git a/dist/cjs/custom-index.js b/dist/cjs/custom-index.js index cf4de162666..c20fd19c381 100644 --- a/dist/cjs/custom-index.js +++ b/dist/cjs/custom-index.js @@ -186,7 +186,7 @@ function getStartIndexStringFromLowerBound(schema, index, lowerBound) { var type = schemaPart.type; switch (type) { case 'string': - var maxLength = (0, _index.ensureNotFalsy)(schemaPart.maxLength); + var maxLength = (0, _index.ensureNotFalsy)(schemaPart.maxLength, 'maxLength not set'); if (typeof bound === 'string') { str += bound.padEnd(maxLength, ' '); } else { @@ -233,7 +233,7 @@ function getStartIndexStringFromUpperBound(schema, index, upperBound) { var type = schemaPart.type; switch (type) { case 'string': - var maxLength = (0, _index.ensureNotFalsy)(schemaPart.maxLength); + var maxLength = (0, _index.ensureNotFalsy)(schemaPart.maxLength, 'maxLength not set'); if (typeof bound === 'string' && bound !== _queryPlanner.INDEX_MAX) { str += bound.padEnd(maxLength, ' '); } else if (bound === _queryPlanner.INDEX_MIN) { diff --git a/dist/cjs/custom-index.js.map b/dist/cjs/custom-index.js.map index 96dd0251baf..0dc2f0b0238 100644 --- a/dist/cjs/custom-index.js.map +++ b/dist/cjs/custom-index.js.map @@ -1 +1 @@ -{"version":3,"file":"custom-index.js","names":["_rxSchemaHelper","require","_index","_queryPlanner","getIndexMeta","schema","index","fieldNameProperties","map","fieldName","schemaPart","getSchemaByObjectPath","Error","type","parsedLengths","getStringLengthOfIndexNumber","getValue","objectPathMonad","maxLength","getIndexStringPart","docData","fieldValue","padEnd","getNumberIndexString","ret","getIndexableStringMonad","fieldNamePropertiesAmount","length","indexPartsFunctions","r","str","i","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","multipleOfParts","split","decimals","roundedMinimum","getIndexStringLength","forEach","props","getPrimaryKeyFromIndexableString","indexableString","primaryKeyLength","paddedPrimaryKey","slice","primaryKey","trim","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","idx","bound","ensureNotFalsy","INDEX_MIN","INDEX_MAX","boolToStr","fillChar","repeat","add","getStartIndexStringFromUpperBound","upperBound","changeIndexableStringByOneQuantum","direction","lastChar","charCode","charCodeAt","withoutLastChar","String","fromCharCode"],"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 * We really often have to craft an index string for a given document.\n * Performance of everything in this file is very important\n * which is why the code sometimes looks strange.\n * Run performance tests before and after you touch anything here!\n */\n\nimport {\n getSchemaByObjectPath\n} from './rx-schema-helper.ts';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types/index.ts';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './plugins/utils/index.ts';\nimport {\n INDEX_MAX,\n INDEX_MIN\n} from './query-planner.ts';\n\n\n/**\n * Prepare all relevant information\n * outside of the returned function\n * from getIndexableStringMonad()\n * to save performance when the returned\n * function is called many times.\n */\ntype IndexMetaField = {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValue: ObjectPathMonadFunction;\n getIndexStringPart: (docData: RxDocumentData) => string;\n};\n\nexport function getIndexMeta(\n schema: RxJsonSchema>,\n index: string[]\n): IndexMetaField[] {\n const fieldNameProperties: IndexMetaField[] = 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 const getValue = objectPathMonad(fieldName);\n const maxLength = schemaPart.maxLength ? schemaPart.maxLength : 0;\n\n let getIndexStringPart: (docData: RxDocumentData) => string;\n if (type === 'string') {\n getIndexStringPart = docData => {\n let fieldValue = getValue(docData);\n if (!fieldValue) {\n fieldValue = '';\n }\n return fieldValue.padEnd(maxLength, ' ');\n };\n } else if (type === 'boolean') {\n getIndexStringPart = docData => {\n const fieldValue = getValue(docData);\n return fieldValue ? '1' : '0';\n };\n } else { // number\n getIndexStringPart = docData => {\n const fieldValue = getValue(docData);\n return getNumberIndexString(\n parsedLengths as any,\n fieldValue\n );\n };\n }\n\n const ret: IndexMetaField = {\n fieldName,\n schemaPart,\n parsedLengths,\n getValue,\n getIndexStringPart\n };\n return ret;\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 const fieldNamePropertiesAmount = fieldNameProperties.length;\n const indexPartsFunctions = fieldNameProperties.map(r => r.getIndexStringPart);\n\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 < fieldNamePropertiesAmount; ++i) {\n str += indexPartsFunctions[i](docData);\n }\n return str;\n };\n return ret;\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 // we can safely trim here because the primary key is not allowed to start or end with a space char.\n const primaryKey = paddedPrimaryKey.trim();\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 const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n let str = nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n if (parsedLengths.decimals > 0) {\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '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): 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 += '0';\n } else if (bound === INDEX_MIN) {\n str += '0';\n } else if (bound === INDEX_MAX) {\n str += '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_MIN) {\n const fillChar = '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else if (bound === INDEX_MAX) {\n str += getNumberIndexString(\n parsedLengths,\n parsedLengths.maximum\n );\n } else {\n const add = getNumberIndexString(\n parsedLengths,\n bound as number\n );\n str += add;\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): 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' && bound !== INDEX_MAX) {\n str += (bound as string).padEnd(maxLength, ' ');\n } else if (bound === INDEX_MIN) {\n str += ''.padEnd(maxLength, ' ');\n } else {\n str += ''.padEnd(maxLength, INDEX_MAX);\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += '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 = '9';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else if (bound === INDEX_MIN) {\n const fillChar = '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\n/**\n * Used in storages where it is not possible\n * to define inclusiveEnd/inclusiveStart\n */\nexport function changeIndexableStringByOneQuantum(str: string, direction: 1 | -1): string {\n const lastChar = str.slice(-1);\n let charCode = lastChar.charCodeAt(0);\n charCode = charCode + direction;\n const withoutLastChar = str.slice(0, -1);\n return withoutLastChar + String.fromCharCode(charCode);\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,IAAAA,eAAA,GAAAC,OAAA;AAQA,IAAAC,MAAA,GAAAD,OAAA;AAKA,IAAAE,aAAA,GAAAF,OAAA;AAxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAqBA;AACA;AACA;AACA;AACA;AACA;AACA;;AAYO,SAASG,YAAYA,CACxBC,MAA+C,EAC/CC,KAAe,EACY;EAC3B,IAAMC,mBAAgD,GAAGD,KAAK,CAACE,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AAKG,uBAAS,EAAE;UACvC,IAAME,QAAQ,GAAG,GAAG;UACpBrC,GAAG,IAAIqC,QAAQ,CAACC,MAAM,CAACtD,aAAa,CAACyB,WAAW,GAAGzB,aAAa,CAAC6B,QAAQ,CAAC;QAC9E,CAAC,MAAM,IAAImB,KAAK,KAAKE,uBAAS,EAAE;UAC5B,IAAMG,SAAQ,GAAG,GAAG;UACpBrC,GAAG,IAAIqC,SAAQ,CAACC,MAAM,CAACtD,aAAa,CAACyB,WAAW,GAAGzB,aAAa,CAAC6B,QAAQ,CAAC;QAC9E,CAAC,MAAM;UACHb,GAAG,IAAIP,oBAAoB,CACvBT,aAAa,EACbgD,KACJ,CAAC;QACL;QACA;MACJ;QACI,MAAM,IAAIlD,KAAK,CAAC,qBAAqB,GAAGC,IAAI,CAAC;IACrD;EACJ,CAAC,CAAC;EACF,OAAOiB,GAAG;AACd;;AAEA;AACA;AACA;AACA;AACO,SAAS0C,iCAAiCA,CAAC1C,GAAW,EAAE2C,SAAiB,EAAU;EACtF,IAAMC,QAAQ,GAAG5C,GAAG,CAACsB,KAAK,CAAC,CAAC,CAAC,CAAC;EAC9B,IAAIuB,QAAQ,GAAGD,QAAQ,CAACE,UAAU,CAAC,CAAC,CAAC;EACrCD,QAAQ,GAAGA,QAAQ,GAAGF,SAAS;EAC/B,IAAMI,eAAe,GAAG/C,GAAG,CAACsB,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;EACxC,OAAOyB,eAAe,GAAGC,MAAM,CAACC,YAAY,CAACJ,QAAQ,CAAC;AAC1D"} \ No newline at end of file +{"version":3,"file":"custom-index.js","names":["_rxSchemaHelper","require","_index","_queryPlanner","getIndexMeta","schema","index","fieldNameProperties","map","fieldName","schemaPart","getSchemaByObjectPath","Error","type","parsedLengths","getStringLengthOfIndexNumber","getValue","objectPathMonad","maxLength","getIndexStringPart","docData","fieldValue","padEnd","getNumberIndexString","ret","getIndexableStringMonad","fieldNamePropertiesAmount","length","indexPartsFunctions","r","str","i","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","multipleOfParts","split","decimals","roundedMinimum","getIndexStringLength","forEach","props","getPrimaryKeyFromIndexableString","indexableString","primaryKeyLength","paddedPrimaryKey","slice","primaryKey","trim","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","idx","bound","ensureNotFalsy","INDEX_MIN","INDEX_MAX","boolToStr","fillChar","repeat","add","getStartIndexStringFromUpperBound","upperBound","changeIndexableStringByOneQuantum","direction","lastChar","charCode","charCodeAt","withoutLastChar","String","fromCharCode"],"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 * We really often have to craft an index string for a given document.\n * Performance of everything in this file is very important\n * which is why the code sometimes looks strange.\n * Run performance tests before and after you touch anything here!\n */\n\nimport {\n getSchemaByObjectPath\n} from './rx-schema-helper.ts';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types/index.ts';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './plugins/utils/index.ts';\nimport {\n INDEX_MAX,\n INDEX_MIN\n} from './query-planner.ts';\n\n\n/**\n * Prepare all relevant information\n * outside of the returned function\n * from getIndexableStringMonad()\n * to save performance when the returned\n * function is called many times.\n */\ntype IndexMetaField = {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValue: ObjectPathMonadFunction;\n getIndexStringPart: (docData: RxDocumentData) => string;\n};\n\nexport function getIndexMeta(\n schema: RxJsonSchema>,\n index: string[]\n): IndexMetaField[] {\n const fieldNameProperties: IndexMetaField[] = 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 const getValue = objectPathMonad(fieldName);\n const maxLength = schemaPart.maxLength ? schemaPart.maxLength : 0;\n\n let getIndexStringPart: (docData: RxDocumentData) => string;\n if (type === 'string') {\n getIndexStringPart = docData => {\n let fieldValue = getValue(docData);\n if (!fieldValue) {\n fieldValue = '';\n }\n return fieldValue.padEnd(maxLength, ' ');\n };\n } else if (type === 'boolean') {\n getIndexStringPart = docData => {\n const fieldValue = getValue(docData);\n return fieldValue ? '1' : '0';\n };\n } else { // number\n getIndexStringPart = docData => {\n const fieldValue = getValue(docData);\n return getNumberIndexString(\n parsedLengths as any,\n fieldValue\n );\n };\n }\n\n const ret: IndexMetaField = {\n fieldName,\n schemaPart,\n parsedLengths,\n getValue,\n getIndexStringPart\n };\n return ret;\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 const fieldNamePropertiesAmount = fieldNameProperties.length;\n const indexPartsFunctions = fieldNameProperties.map(r => r.getIndexStringPart);\n\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 < fieldNamePropertiesAmount; ++i) {\n str += indexPartsFunctions[i](docData);\n }\n return str;\n };\n return ret;\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 // we can safely trim here because the primary key is not allowed to start or end with a space char.\n const primaryKey = paddedPrimaryKey.trim();\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 const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n let str = nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n if (parsedLengths.decimals > 0) {\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '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): 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, 'maxLength not set');\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 += '0';\n } else if (bound === INDEX_MIN) {\n str += '0';\n } else if (bound === INDEX_MAX) {\n str += '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_MIN) {\n const fillChar = '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else if (bound === INDEX_MAX) {\n str += getNumberIndexString(\n parsedLengths,\n parsedLengths.maximum\n );\n } else {\n const add = getNumberIndexString(\n parsedLengths,\n bound as number\n );\n str += add;\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): 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, 'maxLength not set');\n if (typeof bound === 'string' && bound !== INDEX_MAX) {\n str += (bound as string).padEnd(maxLength, ' ');\n } else if (bound === INDEX_MIN) {\n str += ''.padEnd(maxLength, ' ');\n } else {\n str += ''.padEnd(maxLength, INDEX_MAX);\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += '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 = '9';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else if (bound === INDEX_MIN) {\n const fillChar = '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\n/**\n * Used in storages where it is not possible\n * to define inclusiveEnd/inclusiveStart\n */\nexport function changeIndexableStringByOneQuantum(str: string, direction: 1 | -1): string {\n const lastChar = str.slice(-1);\n let charCode = lastChar.charCodeAt(0);\n charCode = charCode + direction;\n const withoutLastChar = str.slice(0, -1);\n return withoutLastChar + String.fromCharCode(charCode);\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,IAAAA,eAAA,GAAAC,OAAA;AAQA,IAAAC,MAAA,GAAAD,OAAA;AAKA,IAAAE,aAAA,GAAAF,OAAA;AAxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAqBA;AACA;AACA;AACA;AACA;AACA;AACA;;AAYO,SAASG,YAAYA,CACxBC,MAA+C,EAC/CC,KAAe,EACY;EAC3B,IAAMC,mBAAgD,GAAGD,KAAK,CAACE,GAAG,CAACC,SAAS,IAAI;IAC5E,IAAMC,UAAU,GAAG,IAAAC,qCAAqB,EACpCN,MAAM,EACNI,SACJ,CAAC;IACD,IAAI,CAACC,UAAU,EAAE;MACb,MAAM,IAAIE,KAAK,CAAC,i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,aAAa,CAAC6B,QAAQ,CAAC;QAC9E,CAAC,MAAM,IAAImB,KAAK,KAAKE,uBAAS,EAAE;UAC5B,IAAMG,SAAQ,GAAG,GAAG;UACpBrC,GAAG,IAAIqC,SAAQ,CAACC,MAAM,CAACtD,aAAa,CAACyB,WAAW,GAAGzB,aAAa,CAAC6B,QAAQ,CAAC;QAC9E,CAAC,MAAM;UACHb,GAAG,IAAIP,oBAAoB,CACvBT,aAAa,EACbgD,KACJ,CAAC;QACL;QACA;MACJ;QACI,MAAM,IAAIlD,KAAK,CAAC,qBAAqB,GAAGC,IAAI,CAAC;IACrD;EACJ,CAAC,CAAC;EACF,OAAOiB,GAAG;AACd;;AAEA;AACA;AACA;AACA;AACO,SAAS0C,iCAAiCA,CAAC1C,GAAW,EAAE2C,SAAiB,EAAU;EACtF,IAAMC,QAAQ,GAAG5C,GAAG,CAACsB,KAAK,CAAC,CAAC,CAAC,CAAC;EAC9B,IAAIuB,QAAQ,GAAGD,QAAQ,CAACE,UAAU,CAAC,CAAC,CAAC;EACrCD,QAAQ,GAAGA,QAAQ,GAAGF,SAAS;EAC/B,IAAMI,eAAe,GAAG/C,GAAG,CAACsB,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;EACxC,OAAOyB,eAAe,GAAGC,MAAM,CAACC,YAAY,CAACJ,QAAQ,CAAC;AAC1D"} \ No newline at end of file diff --git a/dist/cjs/plugins/dev-mode/error-messages.js b/dist/cjs/plugins/dev-mode/error-messages.js index 94864931e77..07623439971 100644 --- a/dist/cjs/plugins/dev-mode/error-messages.js +++ b/dist/cjs/plugins/dev-mode/error-messages.js @@ -157,6 +157,9 @@ var ERROR_MESSAGES = exports.ERROR_MESSAGES = { RC_WEBRTC_PEER: 'RxReplication WebRTC Peer has error', RC_COUCHDB_1: 'replicateCouchDB() url must end with a slash like \'https://example.com/mydatabase/\'', RC_COUCHDB_2: 'replicateCouchDB() did not get valid result with rows.', + RC_OUTDATED: 'Outdated client, update required. Replication was canceled', + RC_UNAUTHORIZED: 'Unauthorized client, update the replicationState.headers to set correct auth data', + RC_FORBIDDEN: 'Client behaves wrong so the replication was canceled. Mostly happens if the client tries to write data that it is not allowed to', // plugins/dev-mode/check-schema.js SC1: 'fieldnames do not match the regex', SC2: 'SchemaCheck: name \'item\' reserved for array-fields', diff --git a/dist/cjs/plugins/dev-mode/error-messages.js.map b/dist/cjs/plugins/dev-mode/error-messages.js.map index d8a57947494..7bfdc08a3b3 100644 --- a/dist/cjs/plugins/dev-mode/error-messages.js.map +++ b/dist/cjs/plugins/dev-mode/error-messages.js.map @@ -1 +1 @@ -{"version":3,"file":"error-messages.js","names":["ERROR_MESSAGES","exports","UT1","UT2","UT3","UT4","UT5","UT6","UT7","PL1","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","QU16","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB11","DB12","DB13","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL20","CONFLICT","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DOC20","DOC21","DOC22","DOC23","DOC24","DM1","DM2","DM3","DM4","DM5","AT1","EN1","EN2","EN3","EN4","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC4","RC5","RC6","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_WEBRTC_PEER","RC_COUCHDB_1","RC_COUCHDB_2","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC27","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","SC40","VD1","VD2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n UT7: 'attachments.compression is enabled but no attachment-compression plugin is used',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin.',\n // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importing a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n QU16: '$regex queries must be defined by a string, not an RegExp instance. ' +\n 'This is because RegExp objects cannot be JSON stringified and also they are mutable which would be dangerous',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional',\n // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n DB12: 'RxDatabase.addCollections(): could not write to internal store',\n DB13: 'createRxDatabase(): Invalid db-name or collection name, name contains the dollar sign',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.incrementalUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n COL20: 'Storage write error',\n CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.destroy() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n DOC20: 'PrimaryKey missing',\n DOC21: 'PrimaryKey must be equal to PrimaryKey.trim(). It cannot start or end with a whitespace',\n DOC22: 'PrimaryKey must not contain a linebreak',\n DOC23: 'PrimaryKey must not contain a double-quote [\"]',\n DOC24: 'Given document data could not be structured cloned. This happens if you pass non-plain-json data into it, like a Date() or a Function. ' +\n 'In vue.js this happens if you use ref() on the document data which transforms it into a Proxy object.',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n DM4: 'Migration errored',\n DM5: 'Cannot open database state with newer RxDB version. You have to migrate your database state first. See see https://rxdb.info/migration-storage.html',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption-crypto-js.js\n EN1: 'password is not valid',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n EN4: 'Password not valid',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'replicateCouchDB() query must be from the same RxCollection',\n // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_WEBRTC_PEER: 'RxReplication WebRTC Peer has error',\n RC_COUCHDB_1: 'replicateCouchDB() url must end with a slash like \\'https://example.com/mydatabase/\\'',\n RC_COUCHDB_2: 'replicateCouchDB() did not get valid result with rows.',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n SC40: '$ref fields in the schema are not allowed. RxDB cannot resolve related schemas because it would have a negative performance impact.' +\n 'It would have to run http requests on runtime. $ref fields should be resolved during build time.',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 instead - DEV1: 'dev-mode added multiple times',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/storage-dexie/\n // removed in 15.0.0, added boolean index support to dexie storage - DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;;AAGO,IAAMA,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG;EAC1B;EACAE,GAAG,EAAE,kCAAkC;EACvCC,GAAG,kTAE8F;EACjGC,GAAG,EAAE,yEAAyE;EAC9EC,GAAG,EAAE,qCAAqC;EAC1CC,GAAG,EAAE,mGAAmG;EACxGC,GAAG,EAAE,mFAAmF;EACxFC,GAAG,EAAE,iFAAiF;EAEtF;EACAC,GAAG,EAAE,kCAAkC;EACvC;EACAC,GAAG,EAAE,+FAA+F;EAEpG;EACA;EACAC,EAAE,EAAE,kDAAkD;EACtD;;EAEA;EACAC,GAAG,EAAE,2CAA2C;EAChD;EACA;EACAC,GAAG,EAAE,+DAA+D;EACpEC,GAAG,EAAE,wEAAwE;EAC7EC,GAAG,EAAE,iDAAiD;EACtD;EACA;EACAC,GAAG,EAAE,oDA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EAAE,4DAA4D;EAClEC,IAAI,EAAE,gDAAgD;EACtDC,IAAI,EAAE,qCAAqC;EAC3CC,IAAI,EAAE,qEAAqE;EAC3EC,IAAI,EAAE,+DAA+D;EACrEC,IAAI,EAAE,sGAAsG;EAC5GC,IAAI,EAAE,+GAA+G;EACrHC,IAAI,EAAE,8CAA8C;EACpDC,IAAI,EAAE,gHAAgH;EACtHC,IAAI,EAAE,kFAAkF;EACxFC,IAAI,EAAE,uDAAuD;EAC7DC,IAAI,EAAE,qIAAqI,GACvI,kGAAkG;EAEtG;EACA;;EAEA;EACAC,GAAG,EAAE,kEAAkE;EACvEC,GAAG,EAAE,8BAA8B;EAEnC;EACA;EACA;;EAEA;EACAC,EAAE,EAAE,iEAAiE;EAErE;EACAC,IAAI,EAAE,oDAAoD;EAC1D;EACAC,IAAI,EAAE,iEAAiE;EACvE;;EAEA;EACAC,KAAK,EAAE,oFAAoF;EAC3FC,KAAK,EAAE,yEAAyE;EAChFC,KAAK,EAAE,wGAAwG;EAE/G;EACA;;EAEA;AACJ;AACA;AACA;AACA;EACIC,GAAG,EAAE;AACT,CAAC"} \ No newline at end of file +{"version":3,"file":"error-messages.js","names":["ERROR_MESSAGES","exports","UT1","UT2","UT3","UT4","UT5","UT6","UT7","PL1","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","QU16","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB11","DB12","DB13","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL20","CONFLICT","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DOC20","DOC21","DOC22","DOC23","DOC24","DM1","DM2","DM3","DM4","DM5","AT1","EN1","EN2","EN3","EN4","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC4","RC5","RC6","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_WEBRTC_PEER","RC_COUCHDB_1","RC_COUCHDB_2","RC_OUTDATED","RC_UNAUTHORIZED","RC_FORBIDDEN","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC27","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","SC40","VD1","VD2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n UT7: 'attachments.compression is enabled but no attachment-compression plugin is used',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin.',\n // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importing a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n QU16: '$regex queries must be defined by a string, not an RegExp instance. ' +\n 'This is because RegExp objects cannot be JSON stringified and also they are mutable which would be dangerous',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional',\n // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n DB12: 'RxDatabase.addCollections(): could not write to internal store',\n DB13: 'createRxDatabase(): Invalid db-name or collection name, name contains the dollar sign',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.incrementalUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n COL20: 'Storage write error',\n CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.destroy() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n DOC20: 'PrimaryKey missing',\n DOC21: 'PrimaryKey must be equal to PrimaryKey.trim(). It cannot start or end with a whitespace',\n DOC22: 'PrimaryKey must not contain a linebreak',\n DOC23: 'PrimaryKey must not contain a double-quote [\"]',\n DOC24: 'Given document data could not be structured cloned. This happens if you pass non-plain-json data into it, like a Date() or a Function. ' +\n 'In vue.js this happens if you use ref() on the document data which transforms it into a Proxy object.',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n DM4: 'Migration errored',\n DM5: 'Cannot open database state with newer RxDB version. You have to migrate your database state first. See see https://rxdb.info/migration-storage.html',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption-crypto-js.js\n EN1: 'password is not valid',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n EN4: 'Password not valid',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'replicateCouchDB() query must be from the same RxCollection',\n // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_WEBRTC_PEER: 'RxReplication WebRTC Peer has error',\n RC_COUCHDB_1: 'replicateCouchDB() url must end with a slash like \\'https://example.com/mydatabase/\\'',\n RC_COUCHDB_2: 'replicateCouchDB() did not get valid result with rows.',\n RC_OUTDATED: 'Outdated client, update required. Replication was canceled',\n RC_UNAUTHORIZED: 'Unauthorized client, update the replicationState.headers to set correct auth data',\n RC_FORBIDDEN: 'Client behaves wrong so the replication was canceled. Mostly happens if the client tries to write data that it is not allowed to',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n SC40: '$ref fields in the schema are not allowed. RxDB cannot resolve related schemas because it would have a negative performance impact.' +\n 'It would have to run http requests on runtime. $ref fields should be resolved during build time.',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 instead - DEV1: 'dev-mode added multiple times',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/storage-dexie/\n // removed in 15.0.0, added boolean index support to dexie storage - DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":";;;;;;AAAA;AACA;AACA;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AAwG;EAE/G;EACA;;EAEA;AACJ;AACA;AACA;AACA;EACIC,GAAG,EAAE;AACT,CAAC"} \ No newline at end of file diff --git a/dist/cjs/plugins/migration-schema/index.js b/dist/cjs/plugins/migration-schema/index.js index f43f4860a28..b69c10beb79 100644 --- a/dist/cjs/plugins/migration-schema/index.js +++ b/dist/cjs/plugins/migration-schema/index.js @@ -50,7 +50,7 @@ Object.keys(_migrationTypes).forEach(function (key) { }); var DATA_MIGRATOR_BY_COLLECTION = exports.DATA_MIGRATOR_BY_COLLECTION = new WeakMap(); var RxDBMigrationPlugin = exports.RxDBMigrationPlugin = { - name: 'migration', + name: 'migration-schema', rxdb: true, init() { (0, _plugin.addRxPlugin)(_index2.RxDBLocalDocumentsPlugin); diff --git a/dist/cjs/plugins/migration-schema/index.js.map b/dist/cjs/plugins/migration-schema/index.js.map index dfea4c7efe6..4cdf07feca5 100644 --- a/dist/cjs/plugins/migration-schema/index.js.map +++ b/dist/cjs/plugins/migration-schema/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_rxjs","require","_index","_rxMigrationState","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_migrationHelpers","_plugin","_index2","_migrationTypes","DATA_MIGRATOR_BY_COLLECTION","WeakMap","RxDBMigrationPlugin","name","rxdb","init","addRxPlugin","RxDBLocalDocumentsPlugin","hooks","preDestroyRxDatabase","after","onDatabaseDestroy","prototypes","RxDatabase","proto","migrationStates","getMigrationStateByDatabase","pipe","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","RxCollection","getMigrationState","getFromMapOrCreate","RxMigrationState","asRxCollection","migrationStrategies","migrationNeeded","schema","version","PROMISE_RESOLVE_FALSE","mustMigrate"],"sources":["../../../../src/plugins/migration-schema/index.ts"],"sourcesContent":["import {\n Observable\n} from 'rxjs';\nimport {\n shareReplay\n} from 'rxjs';\nimport type {\n RxPlugin,\n RxCollection,\n RxDatabase\n} from '../../types/index.ts';\nimport {\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS\n} from '../../plugins/utils/index.ts';\nimport {\n RxMigrationState\n} from './rx-migration-state.ts';\nimport {\n getMigrationStateByDatabase,\n mustMigrate,\n onDatabaseDestroy\n} from './migration-helpers.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { RxDBLocalDocumentsPlugin } from '../local-documents/index.ts';\n\nexport const DATA_MIGRATOR_BY_COLLECTION: WeakMap = new WeakMap();\n\nexport const RxDBMigrationPlugin: RxPlugin = {\n name: 'migration',\n rxdb: true,\n init() {\n addRxPlugin(RxDBLocalDocumentsPlugin);\n },\n hooks: {\n preDestroyRxDatabase: {\n after: onDatabaseDestroy\n }\n },\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.migrationStates = function (this: RxDatabase): Observable {\n return getMigrationStateByDatabase(this).pipe(\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n };\n },\n RxCollection: (proto: any) => {\n proto.getMigrationState = function (this: RxCollection): RxMigrationState {\n return getFromMapOrCreate(\n DATA_MIGRATOR_BY_COLLECTION,\n this,\n () => new RxMigrationState(\n this.asRxCollection,\n this.migrationStrategies\n )\n );\n };\n proto.migrationNeeded = function (this: RxCollection) {\n if (this.schema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return mustMigrate(this.getMigrationState());\n };\n }\n }\n};\n\n\nexport * from './rx-migration-state.ts';\nexport * from './migration-helpers.ts';\nexport * from './migration-types.ts';\n"],"mappings":";;;;;;;;;;AAGA,IAAAA,KAAA,GAAAC,OAAA;AAQA,IAAAC,MAAA,GAAAD,OAAA;AAKA,IAAAE,iBAAA,GAAAF,OAAA;AAsDAG,MAAA,CAAAC,IAAA,CAAAF,iBAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA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,IAAMa,2BAAoE,GAAAR,OAAA,CAAAQ,2BAAA,GAAG,IAAIC,OAAO,CAAC,CAAC;AAE1F,IAAMC,mBAA6B,GAAAV,OAAA,CAAAU,mBAAA,GAAG;EACzCC,IAAI,EAAE,WAAW;EACjBC,IAAI,EAAE,IAAI;EACVC,IAAIA,CAAA,EAAG;IACH,IAAAC,mBAAW,EAACC,gCAAwB,CAAC;EACzC,CAAC;EACDC,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAEC;IACX;EACJ,CAAC;EACDC,UAAU,EAAE;IACRC,UAAU,EAAGC,KAAU,IAAK;MACxBA,KAAK,CAACC,eAAe,GAAG,YAA4D;QAChF,OAAO,IAAAC,6CAA2B,EAAC,IAAI,CAAC,CAACC,IAAI,CACzC,IAAAC,iBAAW,EAACC,iCAA0B,CAC1C,CAAC;MACL,CAAC;IACL,CAAC;IACDC,YAAY,EAAGN,KAAU,IAAK;MAC1BA,KAAK,CAACO,iBAAiB,GAAG,YAAgD;QACtE,OAAO,IAAAC,yBAAkB,EACrBtB,2BAA2B,EAC3B,IAAI,EACJ,MAAM,IAAIuB,kCAAgB,CACtB,IAAI,CAACC,cAAc,EACnB,IAAI,CAACC,mBACT,CACJ,CAAC;MACL,CAAC;MACDX,KAAK,CAACY,eAAe,GAAG,YAA8B;QAClD,IAAI,IAAI,CAACC,MAAM,CAACC,OAAO,KAAK,CAAC,EAAE;UAC3B,OAAOC,4BAAqB;QAChC;QACA,OAAO,IAAAC,6BAAW,EAAC,IAAI,CAACT,iBAAiB,CAAC,CAAC,CAAC;MAChD,CAAC;IACL;EACJ;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["_rxjs","require","_index","_rxMigrationState","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_migrationHelpers","_plugin","_index2","_migrationTypes","DATA_MIGRATOR_BY_COLLECTION","WeakMap","RxDBMigrationPlugin","name","rxdb","init","addRxPlugin","RxDBLocalDocumentsPlugin","hooks","preDestroyRxDatabase","after","onDatabaseDestroy","prototypes","RxDatabase","proto","migrationStates","getMigrationStateByDatabase","pipe","shareReplay","RXJS_SHARE_REPLAY_DEFAULTS","RxCollection","getMigrationState","getFromMapOrCreate","RxMigrationState","asRxCollection","migrationStrategies","migrationNeeded","schema","version","PROMISE_RESOLVE_FALSE","mustMigrate"],"sources":["../../../../src/plugins/migration-schema/index.ts"],"sourcesContent":["import {\n Observable\n} from 'rxjs';\nimport {\n shareReplay\n} from 'rxjs';\nimport type {\n RxPlugin,\n RxCollection,\n RxDatabase\n} from '../../types/index.ts';\nimport {\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS\n} from '../../plugins/utils/index.ts';\nimport {\n RxMigrationState\n} from './rx-migration-state.ts';\nimport {\n getMigrationStateByDatabase,\n mustMigrate,\n onDatabaseDestroy\n} from './migration-helpers.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { RxDBLocalDocumentsPlugin } from '../local-documents/index.ts';\n\nexport const DATA_MIGRATOR_BY_COLLECTION: WeakMap = new WeakMap();\n\nexport const RxDBMigrationPlugin: RxPlugin = {\n name: 'migration-schema',\n rxdb: true,\n init() {\n addRxPlugin(RxDBLocalDocumentsPlugin);\n },\n hooks: {\n preDestroyRxDatabase: {\n after: onDatabaseDestroy\n }\n },\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.migrationStates = function (this: RxDatabase): Observable {\n return getMigrationStateByDatabase(this).pipe(\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n };\n },\n RxCollection: (proto: any) => {\n proto.getMigrationState = function (this: RxCollection): RxMigrationState {\n return getFromMapOrCreate(\n DATA_MIGRATOR_BY_COLLECTION,\n this,\n () => new RxMigrationState(\n this.asRxCollection,\n this.migrationStrategies\n )\n );\n };\n proto.migrationNeeded = function (this: RxCollection) {\n if (this.schema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return mustMigrate(this.getMigrationState());\n };\n }\n }\n};\n\n\nexport * from './rx-migration-state.ts';\nexport * from './migration-helpers.ts';\nexport * from './migration-types.ts';\n"],"mappings":";;;;;;;;;;AAGA,IAAAA,KAAA,GAAAC,OAAA;AAQA,IAAAC,MAAA,GAAAD,OAAA;AAKA,IAAAE,iBAAA,GAAAF,OAAA;AAsDAG,MAAA,CAAAC,IAAA,CAAAF,iBAAA,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,iBAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,iBAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAnDA,IAAAS,iBAAA,GAAAf,OAAA;AAoDAG,MAAA,CAAAC,IAAA,CAAAW,iBAAA,EAAAV,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAS,iBAAA,CAAAT,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAC,iBAAA,CAAAT,GAAA;IAAA;EAAA;AAAA;AA/CA,IAAAU,OAAA,GAAAhB,OAAA;AACA,IAAAiB,OAAA,GAAAjB,OAAA;AA+CA,IAAAkB,eAAA,GAAAlB,OAAA;AAAAG,MAAA,CAAAC,IAA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I,IAAI,CAACC,MAAM,CAACC,OAAO,KAAK,CAAC,EAAE;UAC3B,OAAOC,4BAAqB;QAChC;QACA,OAAO,IAAAC,6BAAW,EAAC,IAAI,CAACT,iBAAiB,CAAC,CAAC,CAAC;MAChD,CAAC;IACL;EACJ;AACJ,CAAC"} \ No newline at end of file diff --git a/dist/cjs/plugins/replication-graphql/index.js b/dist/cjs/plugins/replication-graphql/index.js index 22f42af5304..b4ed9b035d2 100644 --- a/dist/cjs/plugins/replication-graphql/index.js +++ b/dist/cjs/plugins/replication-graphql/index.js @@ -88,7 +88,7 @@ var RxGraphQLReplicationState = exports.RxGraphQLReplicationState = /*#__PURE__* } var _proto = RxGraphQLReplicationState.prototype; _proto.setHeaders = function setHeaders(headers) { - this.clientState.headers = headers; + this.clientState.headers = (0, _index.flatClone)(headers); }; _proto.setCredentials = function setCredentials(credentials) { this.clientState.credentials = credentials; diff --git a/dist/cjs/plugins/replication-graphql/index.js.map b/dist/cjs/plugins/replication-graphql/index.js.map index 2d9984a1820..839d61f8ee0 100644 --- a/dist/cjs/plugins/replication-graphql/index.js.map +++ b/dist/cjs/plugins/replication-graphql/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_index","require","_helper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_index2","_index3","_index4","_graphqlWebsocket","_rxjs","_graphqlSchemaFromRxSchema","_queryBuilderFromRxSchema","RxGraphQLReplicationState","_RxReplicationState","_inheritsLoose2","default","url","clientState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","customFetch","_this","_proto","setHeaders","headers","setCredentials","credentials","graphQLRequest","queryParams","fetch","ensureNotFalsy","http","RxReplicationState","replicateGraphQL","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","mutateableClientState","pullStream$","Subject","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","pullGraphQL","queryBuilder","result","graphqlReplicationState","errors","dataPath","data","getProperty","responseModifier","docsData","documents","newCheckpoint","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","mustUseSocket","ws","streamQueryBuilder","startBefore","start","bind","httpHeaders","includeWsHeaders","undefined","wsClient","getGraphQLWebSocket","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","isStopped","removeGraphQLWebSocketRef","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport {\n ensureNotFalsy,\n getProperty\n} from '../../plugins/utils/index.ts';\n\nimport {\n graphQLRequest\n} from './helper.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index.ts';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket.ts';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n public readonly customFetch?: WindowOrWorkerGlobalScope['fetch']\n ) {\n super(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: { [k: string]: string; }): void {\n this.clientState.headers = headers;\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n this.customFetch ?? fetch,\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\nexport function replicateGraphQL(\n {\n collection,\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n fetch: customFetch,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n replicationIdentifier\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType | undefined\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = getProperty(result, dataPath);\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = push.dataPath || Object.keys(result.data)[0];\n let data: any = getProperty(result.data, dataPath);\n\n if (push.responseModifier) {\n data = await push.responseModifier(\n data,\n );\n }\n\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n replicationIdentifier,\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart,\n customFetch\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const httpHeaders = pull.includeWsHeaders ? mutateableClientState.headers : undefined;\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws), httpHeaders);\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n if (!graphqlReplicationState.isStopped()) {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper.ts';\nexport * from './graphql-schema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,CAAC;QACD8B,KAAK,EAAGA,KAAU,IAAK;UACnB3C,WAAW,CAAC2C,KAAK,CAACA,KAAK,CAAC;QAC5B,CAAC;QACDC,QAAQ,EAAEA,CAAA,KAAM;UACZ5C,WAAW,CAAC4C,QAAQ,CAAC,CAAC;QAC1B;MACJ,CAAC,CAAC;IACV;IACA,OAAOf,WAAW,CAAC,CAAC;EACxB,CAAC;EAED,IAAMgB,YAAY,GAAGnC,uBAAuB,CAACoC,MAAM,CAACf,IAAI,CAACrB,uBAAuB,CAAC;EACjFA,uBAAuB,CAACoC,MAAM,GAAG,MAAM;IACnC,IAAI,CAACpC,uBAAuB,CAACqC,SAAS,CAAC,CAAC,EAAE;MACtC/C,WAAW,CAAC4C,QAAQ,CAAC,CAAC;MACtB,IAAIlB,aAAa,EAAE;QACf,IAAAsB,2CAAyB,EAAC,IAAAxD,qBAAc,EAACpB,GAAG,CAACuD,EAAE,CAAC,CAAC;MACrD;IACJ;IACA,OAAOkB,YAAY,CAAC,CAAC;EACzB,CAAC;EAED,IAAAI,oCAA4B,EAACrD,iBAAiB,EAAEc,uBAAuB,CAAC;EACxE,OAAOA,uBAAuB;AAClC"} \ No newline at end of file +{"version":3,"file":"index.js","names":["_index","require","_helper","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_index2","_index3","_index4","_graphqlWebsocket","_rxjs","_graphqlSchemaFromRxSchema","_queryBuilderFromRxSchema","RxGraphQLReplicationState","_RxReplicationState","_inheritsLoose2","default","url","clientState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","customFetch","_this","_proto","setHeaders","headers","flatClone","setCredentials","credentials","graphQLRequest","queryParams","fetch","ensureNotFalsy","http","RxReplicationState","replicateGraphQL","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","mutateableClientState","pullStream$","Subject","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","pullGraphQL","queryBuilder","result","graphqlReplicationState","errors","dataPath","data","getProperty","responseModifier","docsData","documents","newCheckpoint","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","mustUseSocket","ws","streamQueryBuilder","startBefore","start","bind","httpHeaders","includeWsHeaders","undefined","wsClient","getGraphQLWebSocket","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","isStopped","removeGraphQLWebSocketRef","startReplicationOnLeaderShip"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport {\n ensureNotFalsy,\n flatClone,\n getProperty\n} from '../../plugins/utils/index.ts';\n\nimport {\n graphQLRequest\n} from './helper.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState,\n ById\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index.ts';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket.ts';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n public readonly customFetch?: WindowOrWorkerGlobalScope['fetch']\n ) {\n super(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: ById): void {\n this.clientState.headers = flatClone(headers);\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n this.customFetch ?? fetch,\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\nexport function replicateGraphQL(\n {\n collection,\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n fetch: customFetch,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n replicationIdentifier\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType | undefined\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = getProperty(result, dataPath);\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = push.dataPath || Object.keys(result.data)[0];\n let data: any = getProperty(result.data, dataPath);\n\n if (push.responseModifier) {\n data = await push.responseModifier(\n data,\n );\n }\n\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n replicationIdentifier,\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart,\n customFetch\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const httpHeaders = pull.includeWsHeaders ? mutateableClientState.headers : undefined;\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws), httpHeaders);\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n if (!graphqlReplicationState.isStopped()) {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './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ACAb,WAAW,CAACsC,IAAI,CAACzB,IAAI,CAAC;QAC1B,CAAC;QACD8B,KAAK,EAAGA,KAAU,IAAK;UACnB3C,WAAW,CAAC2C,KAAK,CAACA,KAAK,CAAC;QAC5B,CAAC;QACDC,QAAQ,EAAEA,CAAA,KAAM;UACZ5C,WAAW,CAAC4C,QAAQ,CAAC,CAAC;QAC1B;MACJ,CAAC,CAAC;IACV;IACA,OAAOf,WAAW,CAAC,CAAC;EACxB,CAAC;EAED,IAAMgB,YAAY,GAAGnC,uBAAuB,CAACoC,MAAM,CAACf,IAAI,CAACrB,uBAAuB,CAAC;EACjFA,uBAAuB,CAACoC,MAAM,GAAG,MAAM;IACnC,IAAI,CAACpC,uBAAuB,CAACqC,SAAS,CAAC,CAAC,EAAE;MACtC/C,WAAW,CAAC4C,QAAQ,CAAC,CAAC;MACtB,IAAIlB,aAAa,EAAE;QACf,IAAAsB,2CAAyB,EAAC,IAAAxD,qBAAc,EAACrB,GAAG,CAACwD,EAAE,CAAC,CAAC;MACrD;IACJ;IACA,OAAOkB,YAAY,CAAC,CAAC;EACzB,CAAC;EAED,IAAAI,oCAA4B,EAACrD,iBAAiB,EAAEc,uBAAuB,CAAC;EACxE,OAAOA,uBAAuB;AAClC"} \ No newline at end of file diff --git a/dist/cjs/plugins/replication-websocket/websocket-client.js b/dist/cjs/plugins/replication-websocket/websocket-client.js index 1dc97c75a21..325996754ab 100644 --- a/dist/cjs/plugins/replication-websocket/websocket-client.js +++ b/dist/cjs/plugins/replication-websocket/websocket-client.js @@ -14,7 +14,7 @@ var _index2 = require("../../plugins/utils/index.js"); var _rxjs = require("rxjs"); var _rxError = require("../../rx-error.js"); /** - * Copied and adapter from the 'reconnecting-websocket' npm module. + * Copied and adapted from the 'reconnecting-websocket' npm module. * Some bundlers have problems with bundling the isomorphic-ws plugin * so we directly check the correctness in RxDB to ensure that we can * throw a helpful error. @@ -26,14 +26,34 @@ function ensureIsWebsocket(w) { throw new Error('websocket not valid'); } } -async function createWebSocketClient(url) { +async function createWebSocketClient(options) { ensureIsWebsocket(_isomorphicWs.default); - var wsClient = new _reconnectingWebsocket.default(url, [], { + var wsClient = new _reconnectingWebsocket.default(options.url, [], { WebSocket: _isomorphicWs.default }); var connected$ = new _rxjs.BehaviorSubject(false); + var message$ = new _rxjs.Subject(); + var error$ = new _rxjs.Subject(); + wsClient.onerror = err => { + console.log('--- WAS CLIENT GOT ERROR:'); + console.log(err.error.message); + var emitError = (0, _rxError.newRxError)('RC_STREAM', { + errors: (0, _index2.toArray)(err).map(er => (0, _index2.errorToPlainJson)(er)), + direction: 'pull' + }); + error$.next(emitError); + }; await new Promise(res => { wsClient.onopen = () => { + if (options.headers) { + var authMessage = { + collection: options.collection.name, + id: (0, _index2.randomCouchString)(10), + params: [options.headers], + method: 'auth' + }; + wsClient.send(JSON.stringify(authMessage)); + } connected$.next(true); res(); }; @@ -41,21 +61,12 @@ async function createWebSocketClient(url) { wsClient.onclose = () => { connected$.next(false); }; - var message$ = new _rxjs.Subject(); wsClient.onmessage = messageObj => { var message = JSON.parse(messageObj.data); message$.next(message); }; - var error$ = new _rxjs.Subject(); - wsClient.onerror = err => { - var emitError = (0, _rxError.newRxError)('RC_STREAM', { - errors: (0, _index2.toArray)(err).map(er => (0, _index2.errorToPlainJson)(er)), - direction: 'pull' - }); - error$.next(emitError); - }; return { - url, + url: options.url, socket: wsClient, connected$, message$, @@ -63,7 +74,7 @@ async function createWebSocketClient(url) { }; } async function replicateWithWebsocketServer(options) { - var websocketClient = await createWebSocketClient(options.url); + var websocketClient = await createWebSocketClient(options); var wsClient = websocketClient.socket; var messages$ = websocketClient.message$; var requestCounter = 0; diff --git a/dist/cjs/plugins/replication-websocket/websocket-client.js.map b/dist/cjs/plugins/replication-websocket/websocket-client.js.map index 27ff7e31606..3321948b1ba 100644 --- a/dist/cjs/plugins/replication-websocket/websocket-client.js.map +++ b/dist/cjs/plugins/replication-websocket/websocket-client.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-client.js","names":["_index","require","_reconnectingWebsocket","_interopRequireDefault","_isomorphicWs","_index2","_rxjs","_rxError","ensureIsWebsocket","w","is","CLOSING","console","dir","Error","createWebSocketClient","url","IsomorphicWebSocket","wsClient","ReconnectingWebSocket","WebSocket","connected$","BehaviorSubject","Promise","res","onopen","next","onclose","message$","Subject","onmessage","messageObj","message","JSON","parse","data","error$","onerror","err","emitError","newRxError","errors","toArray","map","er","errorToPlainJson","direction","socket","replicateWithWebsocketServer","options","websocketClient","messages$","requestCounter","requestFlag","randomCouchString","getRequestId","count","collection","database","token","replicationState","replicateRxCollection","replicationIdentifier","live","pull","batchSize","stream$","pipe","filter","msg","id","name","result","handler","lastPulledCheckpoint","requestId","request","method","params","send","stringify","firstValueFrom","push","docs","subscribe","subjects","error","isConnected","reSync","streamRequest","onDestroy","close"],"sources":["../../../../src/plugins/replication-websocket/websocket-client.ts"],"sourcesContent":["import {\n replicateRxCollection,\n RxReplicationState\n} from '../replication/index.ts';\nimport {\n WebsocketClientOptions,\n WebsocketMessageType\n} from './websocket-types.ts';\n\nimport ReconnectingWebSocket from 'reconnecting-websocket';\n\nimport IsomorphicWebSocket from 'isomorphic-ws';\nimport {\n errorToPlainJson,\n randomCouchString,\n toArray\n} from '../../plugins/utils/index.ts';\nimport {\n filter,\n map,\n Subject,\n firstValueFrom,\n BehaviorSubject\n} from 'rxjs';\nimport type {\n RxError,\n RxReplicationWriteToMasterRow\n} from '../../types/index.d.ts';\nimport { newRxError } from '../../rx-error.ts';\n\nexport type WebsocketClient = {\n url: string;\n socket: any;\n connected$: BehaviorSubject;\n message$: Subject;\n error$: Subject;\n};\n\n\n/**\n * Copied and adapter from the 'reconnecting-websocket' npm module.\n * Some bundlers have problems with bundling the isomorphic-ws plugin\n * so we directly check the correctness in RxDB to ensure that we can\n * throw a helpful error.\n */\nexport function ensureIsWebsocket(w: typeof IsomorphicWebSocket) {\n const is = typeof w !== 'undefined' && !!w && w.CLOSING === 2;\n if (!is) {\n console.dir(w);\n throw new Error('websocket not valid');\n }\n}\n\n\nexport async function createWebSocketClient(url: string): Promise {\n ensureIsWebsocket(IsomorphicWebSocket);\n const wsClient = new ReconnectingWebSocket(\n url,\n [],\n {\n WebSocket: IsomorphicWebSocket\n }\n );\n\n const connected$ = new BehaviorSubject(false);\n await new Promise(res => {\n wsClient.onopen = () => {\n connected$.next(true);\n res();\n };\n });\n wsClient.onclose = () => {\n connected$.next(false);\n };\n\n const message$ = new Subject();\n wsClient.onmessage = (messageObj) => {\n const message = JSON.parse(messageObj.data);\n message$.next(message);\n };\n\n const error$ = new Subject();\n wsClient.onerror = (err) => {\n const emitError = newRxError('RC_STREAM', {\n errors: toArray(err).map((er: any) => errorToPlainJson(er)),\n direction: 'pull'\n });\n error$.next(emitError);\n };\n\n\n return {\n url,\n socket: wsClient,\n connected$,\n message$,\n error$\n };\n\n}\n\nexport async function replicateWithWebsocketServer(\n options: WebsocketClientOptions\n): Promise> {\n const websocketClient = await createWebSocketClient(options.url);\n const wsClient = websocketClient.socket;\n const messages$ = websocketClient.message$;\n\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return options.collection.database.token + '|' + requestFlag + '|' + count;\n }\n const replicationState = replicateRxCollection({\n collection: options.collection,\n replicationIdentifier: options.replicationIdentifier,\n live: options.live,\n pull: {\n batchSize: options.batchSize,\n stream$: messages$.pipe(\n filter(msg => msg.id === 'stream' && msg.collection === options.collection.name),\n map(msg => msg.result)\n ),\n async handler(lastPulledCheckpoint: CheckpointType | undefined, batchSize: number) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterChangesSince',\n params: [lastPulledCheckpoint, batchSize]\n };\n wsClient.send(JSON.stringify(request));\n const result = await firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n return result;\n }\n },\n push: {\n batchSize: options.batchSize,\n handler(docs: RxReplicationWriteToMasterRow[]) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterWrite',\n params: [docs]\n };\n wsClient.send(JSON.stringify(request));\n return firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n }\n }\n });\n\n websocketClient.error$.subscribe(err => replicationState.subjects.error.next(err));\n\n websocketClient.connected$.subscribe(isConnected => {\n if (isConnected) {\n /**\n * When the client goes offline and online again,\n * we have to send a 'RESYNC' signal because the client\n * might have missed out events while being offline.\n */\n replicationState.reSync();\n\n /**\n * Because reconnecting creates a new websocket-instance,\n * we have to start the changestream from the remote again\n * each time.\n */\n const streamRequest: WebsocketMessageType = {\n id: 'stream',\n collection: options.collection.name,\n method: 'masterChangeStream$',\n params: []\n };\n wsClient.send(JSON.stringify(streamRequest));\n }\n });\n\n options.collection.onDestroy.push(() => websocketClient.socket.close());\n return replicationState;\n}\n"],"mappings":";;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AASA,IAAAC,sBAAA,GAAAC,sBAAA,CAAAF,OAAA;AAEA,IAAAG,aAAA,GAAAD,sBAAA,CAAAF,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AAKA,IAAAK,KAAA,GAAAL,OAAA;AAWA,IAAAM,QAAA,GAAAN,OAAA;AAWA;AACA;AACA;AACA;AACA;AACA;AACO,SAASO,iBAAiBA,CAACC,CAA6B,EAAE;EAC7D,IAAMC,EAAE,GAAG,OAAOD,CAAC,KAAK,WAAW,IAAI,CAAC,CAACA,CAAC,IAAIA,CAAC,CAACE,OAAO,KAAK,CAAC;EAC7D,IAAI,CAACD,EAAE,EAAE;IACLE,OAAO,CAACC,GAAG,CAACJ,CAAC,CAAC;IACd,MAAM,IAAIK,KAAK,CAAC,qBAAqB,CAAC;EAC1C;AACJ;AAGO,eAAeC,qBAAqBA,CAACC,GAAW,EAA4B;EAC/ER,iBAAiB,CAACS,qBAAmB,CAAC;EACtC,IAAMC,QAA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AMC,aAAmC,GAAG;QACxCnB,EAAE,EAAE,QAAQ;QACZb,UAAU,EAAER,OAAO,CAACQ,UAAU,CAACc,IAAI;QACnCM,MAAM,EAAE,qBAAqB;QAC7BC,MAAM,EAAE;MACZ,CAAC;MACD5D,QAAQ,CAAC6D,IAAI,CAAC9C,IAAI,CAAC+C,SAAS,CAACS,aAAa,CAAC,CAAC;IAChD;EACJ,CAAC,CAAC;EAEFxC,OAAO,CAACQ,UAAU,CAACiC,SAAS,CAACR,IAAI,CAAC,MAAMhC,eAAe,CAACH,MAAM,CAAC4C,KAAK,CAAC,CAAC,CAAC;EACvE,OAAO/B,gBAAgB;AAC3B"} \ No newline at end of file +{"version":3,"file":"websocket-client.js","names":["_index","require","_reconnectingWebsocket","_interopRequireDefault","_isomorphicWs","_index2","_rxjs","_rxError","ensureIsWebsocket","w","is","CLOSING","console","dir","Error","createWebSocketClient","options","IsomorphicWebSocket","wsClient","ReconnectingWebSocket","url","WebSocket","connected$","BehaviorSubject","message$","Subject","error$","onerror","err","log","error","message","emitError","newRxError","errors","toArray","map","er","errorToPlainJson","direction","next","Promise","res","onopen","headers","authMessage","collection","name","id","randomCouchString","params","method","send","JSON","stringify","onclose","onmessage","messageObj","parse","data","socket","replicateWithWebsocketServer","websocketClient","messages$","requestCounter","requestFlag","getRequestId","count","database","token","replicationState","replicateRxCollection","replicationIdentifier","live","pull","batchSize","stream$","pipe","filter","msg","result","handler","lastPulledCheckpoint","requestId","request","firstValueFrom","push","docs","subscribe","subjects","isConnected","reSync","streamRequest","onDestroy","close"],"sources":["../../../../src/plugins/replication-websocket/websocket-client.ts"],"sourcesContent":["import {\n replicateRxCollection,\n RxReplicationState\n} from '../replication/index.ts';\nimport {\n WebsocketClientOptions,\n WebsocketMessageType\n} from './websocket-types.ts';\n\nimport ReconnectingWebSocket from 'reconnecting-websocket';\n\nimport IsomorphicWebSocket from 'isomorphic-ws';\nimport {\n errorToPlainJson,\n randomCouchString,\n toArray\n} from '../../plugins/utils/index.ts';\nimport {\n filter,\n map,\n Subject,\n firstValueFrom,\n BehaviorSubject\n} from 'rxjs';\nimport type {\n RxError,\n RxReplicationWriteToMasterRow\n} from '../../types/index.d.ts';\nimport { newRxError } from '../../rx-error.ts';\n\nexport type WebsocketClient = {\n url: string;\n socket: any;\n connected$: BehaviorSubject;\n message$: Subject;\n error$: Subject;\n};\n\n\n/**\n * Copied and adapted from the 'reconnecting-websocket' npm module.\n * Some bundlers have problems with bundling the isomorphic-ws plugin\n * so we directly check the correctness in RxDB to ensure that we can\n * throw a helpful error.\n */\nexport function ensureIsWebsocket(w: typeof IsomorphicWebSocket) {\n const is = typeof w !== 'undefined' && !!w && w.CLOSING === 2;\n if (!is) {\n console.dir(w);\n throw new Error('websocket not valid');\n }\n}\n\n\nexport async function createWebSocketClient(options: WebsocketClientOptions): Promise {\n ensureIsWebsocket(IsomorphicWebSocket);\n const wsClient = new ReconnectingWebSocket(\n options.url,\n [],\n {\n WebSocket: IsomorphicWebSocket\n }\n );\n const connected$ = new BehaviorSubject(false);\n const message$ = new Subject();\n const error$ = new Subject();\n wsClient.onerror = (err) => {\n\n console.log('--- WAS CLIENT GOT ERROR:');\n console.log(err.error.message);\n\n const emitError = newRxError('RC_STREAM', {\n errors: toArray(err).map((er: any) => errorToPlainJson(er)),\n direction: 'pull'\n });\n error$.next(emitError);\n };\n await new Promise(res => {\n wsClient.onopen = () => {\n\n if (options.headers) {\n const authMessage: WebsocketMessageType = {\n collection: options.collection.name,\n id: randomCouchString(10),\n params: [options.headers],\n method: 'auth'\n };\n wsClient.send(JSON.stringify(authMessage));\n }\n\n connected$.next(true);\n res();\n };\n });\n wsClient.onclose = () => {\n connected$.next(false);\n };\n\n wsClient.onmessage = (messageObj) => {\n const message = JSON.parse(messageObj.data);\n message$.next(message);\n };\n\n return {\n url: options.url,\n socket: wsClient,\n connected$,\n message$,\n error$\n };\n\n}\n\nexport async function replicateWithWebsocketServer(\n options: WebsocketClientOptions\n): Promise> {\n const websocketClient = await createWebSocketClient(options);\n const wsClient = websocketClient.socket;\n const messages$ = websocketClient.message$;\n\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return options.collection.database.token + '|' + requestFlag + '|' + count;\n }\n const replicationState = replicateRxCollection({\n collection: options.collection,\n replicationIdentifier: options.replicationIdentifier,\n live: options.live,\n pull: {\n batchSize: options.batchSize,\n stream$: messages$.pipe(\n filter(msg => msg.id === 'stream' && msg.collection === options.collection.name),\n map(msg => msg.result)\n ),\n async handler(lastPulledCheckpoint: CheckpointType | undefined, batchSize: number) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterChangesSince',\n params: [lastPulledCheckpoint, batchSize]\n };\n wsClient.send(JSON.stringify(request));\n const result = await firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n return result;\n }\n },\n push: {\n batchSize: options.batchSize,\n handler(docs: RxReplicationWriteToMasterRow[]) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterWrite',\n params: [docs]\n };\n wsClient.send(JSON.stringify(request));\n return firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n }\n }\n });\n\n websocketClient.error$.subscribe(err => replicationState.subjects.error.next(err));\n\n websocketClient.connected$.subscribe(isConnected => {\n if (isConnected) {\n /**\n * When the client goes offline and online again,\n * we have to send a 'RESYNC' signal because the client\n * might have missed out events while being offline.\n */\n replicationState.reSync();\n\n /**\n * Because reconnecting creates a new websocket-instance,\n * we have to start the changestream from the remote again\n * each time.\n */\n const streamRequest: WebsocketMessageType = {\n id: 'stream',\n collection: options.collection.name,\n method: 'masterChangeStream$',\n params: []\n };\n wsClient.send(JSON.stringify(streamRequest));\n }\n });\n\n options.collection.onDestroy.push(() => websocketClient.socket.close());\n return replicationState;\n}\n"],"mappings":";;;;;;;;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AAU,EAAE9B,OAAO,CAAC8B,UAAU,CAACC,IAAI;QACnCI,MAAM,EAAE,qBAAqB;QAC7BD,MAAM,EAAE;MACZ,CAAC;MACDhC,QAAQ,CAACkC,IAAI,CAACC,IAAI,CAACC,SAAS,CAACsC,aAAa,CAAC,CAAC;IAChD;EACJ,CAAC,CAAC;EAEF5E,OAAO,CAAC8B,UAAU,CAAC+C,SAAS,CAACP,IAAI,CAAC,MAAMxB,eAAe,CAACF,MAAM,CAACkC,KAAK,CAAC,CAAC,CAAC;EACvE,OAAOxB,gBAAgB;AAC3B"} \ No newline at end of file diff --git a/dist/cjs/plugins/replication-websocket/websocket-server.js b/dist/cjs/plugins/replication-websocket/websocket-server.js index 877ffb8d793..317971e896e 100644 --- a/dist/cjs/plugins/replication-websocket/websocket-server.js +++ b/dist/cjs/plugins/replication-websocket/websocket-server.js @@ -4,6 +4,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau Object.defineProperty(exports, "__esModule", { value: true }); +exports.getReplicationHandlerByCollection = getReplicationHandlerByCollection; exports.startSocketServer = startSocketServer; exports.startWebsocketServer = startWebsocketServer; var _isomorphicWs = _interopRequireDefault(require("isomorphic-ws")); @@ -48,6 +49,17 @@ function startSocketServer(options) { onConnection$: onConnection$.asObservable() }; } +var REPLICATION_HANDLER_BY_COLLECTION = new Map(); +function getReplicationHandlerByCollection(database, collectionName) { + if (!database.collections[collectionName]) { + throw new Error('collection ' + collectionName + ' does not exist'); + } + var collection = database.collections[collectionName]; + var handler = (0, _index2.getFromMapOrCreate)(REPLICATION_HANDLER_BY_COLLECTION, collection, () => { + return (0, _index.rxStorageInstanceToReplicationHandler)(collection.storageInstance, collection.conflictHandler, database.token); + }); + return handler; +} function startWebsocketServer(options) { var { database, @@ -57,17 +69,6 @@ function startWebsocketServer(options) { // auto close when the database gets destroyed database.onDestroy.push(() => serverState.close()); - var replicationHandlerByCollection = new Map(); - function getReplicationHandler(collectionName) { - if (!database.collections[collectionName]) { - throw new Error('collection ' + collectionName + ' does not exist'); - } - var handler = (0, _index2.getFromMapOrCreate)(replicationHandlerByCollection, collectionName, () => { - var collection = database.collections[collectionName]; - return (0, _index.rxStorageInstanceToReplicationHandler)(collection.storageInstance, collection.conflictHandler, database.token); - }); - return handler; - } serverState.onConnection$.subscribe(ws => { var onCloseHandlers = []; ws.onclose = () => { @@ -75,7 +76,10 @@ function startWebsocketServer(options) { }; ws.on('message', async messageString => { var message = JSON.parse(messageString); - var handler = getReplicationHandler(message.collection); + var handler = getReplicationHandlerByCollection(database, message.collection); + if (message.method === 'auth') { + return; + } var method = handler[message.method]; /** diff --git a/dist/cjs/plugins/replication-websocket/websocket-server.js.map b/dist/cjs/plugins/replication-websocket/websocket-server.js.map index cf89bd8446f..f32f6b260dd 100644 --- a/dist/cjs/plugins/replication-websocket/websocket-server.js.map +++ b/dist/cjs/plugins/replication-websocket/websocket-server.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-server.js","names":["_isomorphicWs","_interopRequireDefault","require","_index","_index2","_rxjs","WebSocketServer","pkg","startSocketServer","options","wss","closed","closeServer","PROMISE_RESOLVE_VOID","onConnection$","complete","Promise","res","rej","ws","clients","close","err","Subject","on","next","server","asObservable","startWebsocketServer","database","wsOptions","serverState","onDestroy","push","replicationHandlerByCollection","Map","getReplicationHandler","collectionName","collections","Error","handler","getFromMapOrCreate","collection","rxStorageInstanceToReplicationHandler","storageInstance","conflictHandler","token","subscribe","onCloseHandlers","onclose","map","fn","messageString","message","JSON","parse","method","changeStreamSub","masterChangeStream$","ev","streamResponse","id","result","send","stringify","unsubscribe","params","response"],"sources":["../../../../src/plugins/replication-websocket/websocket-server.ts"],"sourcesContent":["import type {\n RxReplicationHandler\n} from '../../types/index.d.ts';\n\nimport type {\n WebSocket,\n ServerOptions\n} from 'isomorphic-ws';\nimport pkg from 'isomorphic-ws';\nconst { WebSocketServer } = pkg;\n\nimport type {\n WebsocketMessageResponseType,\n WebsocketMessageType,\n WebsocketServerOptions,\n WebsocketServerState\n} from './websocket-types.ts';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol/index.ts';\nimport {\n PROMISE_RESOLVE_VOID, getFromMapOrCreate\n} from '../../plugins/utils/index.ts';\nimport { Subject } from 'rxjs';\n\nexport function startSocketServer(options: ServerOptions): WebsocketServerState {\n const wss = new WebSocketServer(options);\n let closed = false;\n function closeServer() {\n if (closed) {\n return PROMISE_RESOLVE_VOID;\n }\n closed = true;\n onConnection$.complete();\n return new Promise((res, rej) => {\n /**\n * We have to close all client connections,\n * otherwise wss.close() will never call the callback.\n * @link https://github.com/websockets/ws/issues/1288#issuecomment-360594458\n */\n for (const ws of wss.clients) {\n ws.close();\n }\n wss.close((err: any) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n\n const onConnection$ = new Subject();\n wss.on('connection', (ws: any) => onConnection$.next(ws));\n\n return {\n server: wss,\n close: closeServer,\n onConnection$: onConnection$.asObservable()\n };\n}\n\nexport function startWebsocketServer(options: WebsocketServerOptions): WebsocketServerState {\n const { database, ...wsOptions } = options;\n const serverState = startSocketServer(wsOptions);\n\n // auto close when the database gets destroyed\n database.onDestroy.push(() => serverState.close());\n\n const replicationHandlerByCollection: Map> = new Map();\n function getReplicationHandler(collectionName: string): RxReplicationHandler {\n if (!database.collections[collectionName]) {\n throw new Error('collection ' + collectionName + ' does not exist');\n }\n\n const handler = getFromMapOrCreate(\n replicationHandlerByCollection,\n collectionName,\n () => {\n const collection = database.collections[collectionName];\n return rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n database.token\n );\n }\n );\n return handler;\n }\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', async (messageString: string) => {\n const message: WebsocketMessageType = JSON.parse(messageString);\n const handler = getReplicationHandler(message.collection);\n const method = handler[message.method];\n\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n if (typeof method !== 'function') {\n const changeStreamSub = handler.masterChangeStream$.subscribe(ev => {\n const streamResponse: WebsocketMessageResponseType = {\n id: 'stream',\n collection: message.collection,\n result: ev\n };\n ws.send(JSON.stringify(streamResponse));\n });\n onCloseHandlers.push(() => changeStreamSub.unsubscribe());\n return;\n }\n const result = await (method as any)(...message.params);\n const response: WebsocketMessageResponseType = {\n id: message.id,\n collection: message.collection,\n result\n };\n ws.send(JSON.stringify(response));\n });\n });\n\n\n return serverState;\n}\n"],"mappings":";;;;;;;;AAQA,IAAAA,aAAA,GAAAC,sBAAA,CAAAC,OAAA;AASA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAGA,IAAAG,KAAA,GAAAH,OAAA;AAZA,IAAM;EAAEI;AAAgB,CAAC,GAAGC,qBAAG;AAcxB,SAASC,iBAAiBA,CAACC,OAAsB,EAAwB;EAC5E,IAAMC,GAAG,GAAG,IAAIJ,eAAe,CAACG,OAAO,CAAC;EACxC,IAAIE,MAAM,GAAG,KAAK;EAClB,SAASC,WAAWA,CAAA,EAAG;IACnB,IAAID,MAAM,EAAE;MACR,OAAOE,4BAAoB;IAC/B;IACAF,MAAM,GAAG,IAAI;IACbG,aAAa,CAACC,QAAQ,CAAC,CAAC;IACxB,OAAO,IAAIC,OAAO,CAAO,CAACC,GAAG,EAAEC,GAAG,KAAK;MACnC;AACZ;AACA;AACA;AACA;MACY,KAAK,IAAMC,EAAE,IAAIT,GAAG,CAACU,OAAO,EAAE;QAC1BD,EAAE,CAACE,KAAK,CAAC,CAAC;MACd;MACAX,GAAG,CAACW,KAAK,CAAEC,GAAQ,IAAK;QACpB,IAAIA,GAAG,EAAE;UACLJ,GAAG,CAACI,GAAG,CAAC;QACZ,CAAC,MAAM;UACHL,GAAG,CAAC,CAAC;QACT;MACJ,CAAC,CAAC;IACN,CAAC,CAAC;EACN;EAEA,IAAMH,aAAa,GAAG,IAAIS,aAAO,CAAY,CAAC;EAC9Cb,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ACDhC,EAAE,CAACK,EAAE,CAAC,SAAS,EAAE,MAAO4B,aAAqB,IAAK;MAC9C,IAAMC,OAA6B,GAAGC,IAAI,CAACC,KAAK,CAACH,aAAa,CAAC;MAC/D,IAAMZ,OAAO,GAAGJ,qBAAqB,CAACiB,OAAO,CAACX,UAAU,CAAC;MACzD,IAAMc,MAAM,GAAGhB,OAAO,CAACa,OAAO,CAACG,MAAM,CAAC;;MAEtC;AACZ;AACA;AACA;MACY,IAAI,OAAOA,MAAM,KAAK,UAAU,EAAE;QAC9B,IAAMC,eAAe,GAAGjB,OAAO,CAACkB,mBAAmB,CAACX,SAAS,CAACY,EAAE,IAAI;UAChE,IAAMC,cAA4C,GAAG;YACjDC,EAAE,EAAE,QAAQ;YACZnB,UAAU,EAAEW,OAAO,CAACX,UAAU;YAC9BoB,MAAM,EAAEH;UACZ,CAAC;UACDxC,EAAE,CAAC4C,IAAI,CAACT,IAAI,CAACU,SAAS,CAACJ,cAAc,CAAC,CAAC;QAC3C,CAAC,CAAC;QACFZ,eAAe,CAACf,IAAI,CAAC,MAAMwB,eAAe,CAACQ,WAAW,CAAC,CAAC,CAAC;QACzD;MACJ;MACA,IAAMH,MAAM,GAAG,MAAON,MAAM,CAAS,GAAGH,OAAO,CAACa,MAAM,CAAC;MACvD,IAAMC,QAAsC,GAAG;QAC3CN,EAAE,EAAER,OAAO,CAACQ,EAAE;QACdnB,UAAU,EAAEW,OAAO,CAACX,UAAU;QAC9BoB;MACJ,CAAC;MACD3C,EAAE,CAAC4C,IAAI,CAACT,IAAI,CAACU,SAAS,CAACG,QAAQ,CAAC,CAAC;IACrC,CAAC,CAAC;EACN,CAAC,CAAC;EAGF,OAAOpC,WAAW;AACtB"} \ No newline at end of file +{"version":3,"file":"websocket-server.js","names":["_isomorphicWs","_interopRequireDefault","require","_index","_index2","_rxjs","WebSocketServer","pkg","startSocketServer","options","wss","closed","closeServer","PROMISE_RESOLVE_VOID","onConnection$","complete","Promise","res","rej","ws","clients","close","err","Subject","on","next","server","asObservable","REPLICATION_HANDLER_BY_COLLECTION","Map","getReplicationHandlerByCollection","database","collectionName","collections","Error","collection","handler","getFromMapOrCreate","rxStorageInstanceToReplicationHandler","storageInstance","conflictHandler","token","startWebsocketServer","wsOptions","serverState","onDestroy","push","subscribe","onCloseHandlers","onclose","map","fn","messageString","message","JSON","parse","method","changeStreamSub","masterChangeStream$","ev","streamResponse","id","result","send","stringify","unsubscribe","params","response"],"sources":["../../../../src/plugins/replication-websocket/websocket-server.ts"],"sourcesContent":["import type {\n RxCollection,\n RxDatabase,\n RxReplicationHandler\n} from '../../types/index.d.ts';\n\nimport type {\n WebSocket,\n ServerOptions\n} from 'isomorphic-ws';\nimport pkg from 'isomorphic-ws';\nconst { WebSocketServer } = pkg;\n\nimport type {\n WebsocketMessageResponseType,\n WebsocketMessageType,\n WebsocketServerOptions,\n WebsocketServerState\n} from './websocket-types.ts';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol/index.ts';\nimport {\n PROMISE_RESOLVE_VOID, getFromMapOrCreate\n} from '../../plugins/utils/index.ts';\nimport { Subject } from 'rxjs';\n\nexport function startSocketServer(options: ServerOptions): WebsocketServerState {\n const wss = new WebSocketServer(options);\n let closed = false;\n function closeServer() {\n if (closed) {\n return PROMISE_RESOLVE_VOID;\n }\n closed = true;\n onConnection$.complete();\n return new Promise((res, rej) => {\n /**\n * We have to close all client connections,\n * otherwise wss.close() will never call the callback.\n * @link https://github.com/websockets/ws/issues/1288#issuecomment-360594458\n */\n for (const ws of wss.clients) {\n ws.close();\n }\n wss.close((err: any) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n\n const onConnection$ = new Subject();\n wss.on('connection', (ws: any) => onConnection$.next(ws));\n\n return {\n server: wss,\n close: closeServer,\n onConnection$: onConnection$.asObservable()\n };\n}\n\nconst REPLICATION_HANDLER_BY_COLLECTION: WeakMap> = new Map();\nexport function getReplicationHandlerByCollection(\n database: RxDatabase,\n collectionName: string\n): RxReplicationHandler {\n if (!database.collections[collectionName]) {\n throw new Error('collection ' + collectionName + ' does not exist');\n }\n\n const collection = database.collections[collectionName];\n const handler = getFromMapOrCreate>(\n REPLICATION_HANDLER_BY_COLLECTION,\n collection,\n () => {\n return rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n database.token\n );\n }\n );\n return handler;\n}\n\nexport function startWebsocketServer(options: WebsocketServerOptions): WebsocketServerState {\n const { database, ...wsOptions } = options;\n const serverState = startSocketServer(wsOptions);\n\n // auto close when the database gets destroyed\n database.onDestroy.push(() => serverState.close());\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', async (messageString: string) => {\n const message: WebsocketMessageType = JSON.parse(messageString);\n const handler = getReplicationHandlerByCollection(database, message.collection);\n if (message.method === 'auth') {\n return;\n }\n const method = handler[message.method];\n\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n if (typeof method !== 'function') {\n const changeStreamSub = handler.masterChangeStream$.subscribe(ev => {\n const streamResponse: WebsocketMessageResponseType = {\n id: 'stream',\n collection: message.collection,\n result: ev\n };\n ws.send(JSON.stringify(streamResponse));\n });\n onCloseHandlers.push(() => changeStreamSub.unsubscribe());\n return;\n }\n const result = await (method as any)(...message.params);\n const response: WebsocketMessageResponseType = {\n id: message.id,\n collection: message.collection,\n result\n };\n ws.send(JSON.stringify(response));\n });\n });\n\n\n return serverState;\n}\n"],"mappings":";;;;;;;;;AAUA,IAAAA,aAAA,GAAAC,sBAAA,CAAAC,OAAA;AASA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAGA,IAAAG,KAAA,GAAAH,OAAA;AAZA,IAAM;EAAEI;AAAgB,CAAC,GAAGC,qBAAG;AAcxB,SAASC,iBAAiBA,CAACC,OAAsB,EAAwB;EAC5E,IAAMC,GAAG,GAAG,IAAIJ,eAAe,C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C9B2B,MAAM,EAAEH;UACZ,CAAC;UACDxC,EAAE,CAAC4C,IAAI,CAACT,IAAI,CAACU,SAAS,CAACJ,cAAc,CAAC,CAAC;QAC3C,CAAC,CAAC;QACFZ,eAAe,CAACF,IAAI,CAAC,MAAMW,eAAe,CAACQ,WAAW,CAAC,CAAC,CAAC;QACzD;MACJ;MACA,IAAMH,MAAM,GAAG,MAAON,MAAM,CAAS,GAAGH,OAAO,CAACa,MAAM,CAAC;MACvD,IAAMC,QAAsC,GAAG;QAC3CN,EAAE,EAAER,OAAO,CAACQ,EAAE;QACd1B,UAAU,EAAEkB,OAAO,CAAClB,UAAU;QAC9B2B;MACJ,CAAC;MACD3C,EAAE,CAAC4C,IAAI,CAACT,IAAI,CAACU,SAAS,CAACG,QAAQ,CAAC,CAAC;IACrC,CAAC,CAAC;EACN,CAAC,CAAC;EAGF,OAAOvB,WAAW;AACtB"} \ No newline at end of file diff --git a/dist/cjs/plugins/replication-websocket/websocket-types.js.map b/dist/cjs/plugins/replication-websocket/websocket-types.js.map index b9f2efec8af..5dd2ffab3b1 100644 --- a/dist/cjs/plugins/replication-websocket/websocket-types.js.map +++ b/dist/cjs/plugins/replication-websocket/websocket-types.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-types.js","names":[],"sources":["../../../../src/plugins/replication-websocket/websocket-types.ts"],"sourcesContent":["import type {\n Observable,\n} from 'rxjs';\nimport type {\n ServerOptions,\n ClientOptions,\n WebSocketServer,\n WebSocket\n} from 'ws';\nimport type {\n RxCollection,\n RxDatabase,\n RxReplicationHandler,\n StringKeys\n} from '../../types/index.d.ts';\n\nexport type WebsocketServerOptions = {\n database: RxDatabase;\n} & ServerOptions;\n\nexport type WebsocketServerState = {\n server: WebSocketServer;\n close: () => Promise;\n onConnection$: Observable;\n};\n\nexport type WebsocketClientOptions = {\n replicationIdentifier: string;\n collection: RxCollection;\n url: string;\n batchSize?: number;\n live?: boolean;\n} & ClientOptions;\n\nexport type WebsocketMessageType = {\n id: string;\n collection: string;\n method: StringKeys>;\n params: any[];\n};\n\nexport type WebsocketMessageResponseType = {\n id: string;\n collection: string;\n result: any;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"websocket-types.js","names":[],"sources":["../../../../src/plugins/replication-websocket/websocket-types.ts"],"sourcesContent":["import type {\n Observable,\n} from 'rxjs';\nimport type {\n ServerOptions,\n ClientOptions,\n WebSocketServer,\n WebSocket\n} from 'ws';\nimport type {\n RxCollection,\n RxDatabase,\n RxReplicationHandler,\n StringKeys\n} from '../../types/index.d.ts';\n\nexport type WebsocketServerOptions = {\n database: RxDatabase;\n} & ServerOptions;\n\nexport type WebsocketServerState = {\n server: WebSocketServer;\n close: () => Promise;\n onConnection$: Observable;\n};\n\nexport type WebsocketClientOptions = {\n replicationIdentifier: string;\n collection: RxCollection;\n url: string;\n batchSize?: number;\n live?: boolean;\n headers?: { [k: string]: string; };\n} & ClientOptions;\n\nexport type WebsocketMessageType = {\n id: string;\n collection: string;\n method: StringKeys> | 'auth';\n params: any[];\n};\n\nexport type WebsocketMessageResponseType = {\n id: string;\n collection: string;\n result: any;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/plugins/replication/index.js b/dist/cjs/plugins/replication/index.js index fb28f85a979..3bc73b12444 100644 --- a/dist/cjs/plugins/replication/index.js +++ b/dist/cjs/plugins/replication/index.js @@ -49,6 +49,7 @@ var RxReplicationState = exports.RxReplicationState = /*#__PURE__*/function () { this.error$ = this.subjects.error.asObservable(); this.canceled$ = this.subjects.canceled.asObservable(); this.active$ = this.subjects.active.asObservable(); + this.onCancel = []; this.callOnStart = undefined; this.remoteEvents$ = new _rxjs.Subject(); this.replicationIdentifier = replicationIdentifier; @@ -312,7 +313,7 @@ var RxReplicationState = exports.RxReplicationState = /*#__PURE__*/function () { if (this.isStopped()) { return _index2.PROMISE_RESOLVE_FALSE; } - var promises = []; + var promises = this.onCancel.map(fn => (0, _index2.toPromise)(fn())); if (this.internalReplicationState) { await (0, _index3.cancelRxStorageReplication)(this.internalReplicationState); } diff --git a/dist/cjs/plugins/replication/index.js.map b/dist/cjs/plugins/replication/index.js.map index d8f7ad7bc56..22d69124199 100644 --- a/dist/cjs/plugins/replication/index.js.map +++ b/dist/cjs/plugins/replication/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_rxjs","require","_index","_index2","_index3","_rxError","_replicationHelper","_rxDatabaseInternalStore","_plugin","_rxStorageHelper","_overwritable","_hooks","REPLICATION_STATE_BY_COLLECTION","exports","WeakMap","RxReplicationState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","Subject","sent","error","canceled","BehaviorSubject","active","received$","asObservable","sent$","error$","canceled$","active$","callOnStart","undefined","remoteEvents$","replicationStates","getFromMapOrCreate","onDestroy","cancel","Object","keys","forEach","key","defineProperty","get","startPromise","Promise","res","_proto","prototype","start","isStopped","pullModifier","modifier","DEFAULT_MODIFIER","pushModifier","database","metaInstanceCollectionName","hashFunction","name","join","metaInstanceSchema","getRxReplicationMetaInstanceSchema","schema","jsonSchema","hasEncryption","metaInstance","all","storage","createStorageInstance","databaseName","collectionName","databaseInstanceToken","token","multiInstance","options","password","devMode","overwritable","isDevMode","addConnectedStorageToCollection","internalReplicationState","replicateRxStorageInstance","pushBatchSize","batchSize","pullBatchSize","initialCheckpoint","upstream","downstream","forkInstance","storageInstance","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","filter","_v","mergeMap","ev","useEv","flatClone","documents","handlePulledDocuments","map","d","masterChangesSince","checkpoint","done","result","handler","err","emitError","newRxError","errors","toArray","er","errorToPlainJson","direction","next","awaitRetry","ensureNotFalsy","useResult","masterWrite","rows","runAsyncPluginHooks","useRowsOrNull","row","newDocumentState","assumedMasterState","swapDefaultDeletedTodeletedField","useRows","arrayFilterNotEmpty","length","Array","isArray","pushRows","args","rxdb","conflicts","events","subscribe","processed","down","document","up","writeToMasterRow","combineLatest","isActive","stream$","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","getValue","awaitInitialReplication","awaitInSync","requestIdlePromise","reSync","emitEvent","PROMISE_RESOLVE_FALSE","promises","cancelRxStorageReplication","checkpointQueue","then","close","sub","unsubscribe","complete","replicateRxCollection","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun","PROMISE_RESOLVE_TRUE"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport {\n arrayFilterNotEmpty,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n toArray\n} from '../../plugins/utils/index.ts';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n getRxReplicationMetaInstanceSchema,\n replicateRxStorageInstance\n} from '../../replication-protocol/index.ts';\nimport { newRxError } from '../../rx-error.ts';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n handlePulledDocuments\n} from './replication-helper.ts';\nimport {\n addConnectedStorageToCollection\n} from '../../rx-database-internal-store.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { hasEncryption } from '../../rx-storage-helper.ts';\nimport { overwritable } from '../../overwritable.ts';\nimport {\n runAsyncPluginHooks\n} from '../../hooks.ts';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n sent: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false) // true when something is running, false when not\n };\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly sent$: Observable> = this.subjects.sent.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n public startPromise: Promise;\n constructor(\n /**\n * The identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n const replicationStates = getFromMapOrCreate(\n REPLICATION_STATE_BY_COLLECTION,\n collection,\n () => []\n );\n replicationStates.push(this);\n\n // stop the replication when the collection gets destroyed\n this.collection.onDestroy.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance, any, {}, any>;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n const metaInstanceCollectionName = 'rx-replication-meta-' + await database.hashFunction([\n this.collection.name,\n this.replicationIdentifier\n ].join('-'));\n const metaInstanceSchema = getRxReplicationMetaInstanceSchema(\n this.collection.schema.jsonSchema,\n hasEncryption(this.collection.schema.jsonSchema)\n );\n\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance>({\n databaseName: database.name,\n collectionName: metaInstanceCollectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance, // TODO is this always false?\n options: {},\n schema: metaInstanceSchema,\n password: database.password,\n devMode: overwritable.isDevMode()\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInstanceCollectionName,\n metaInstanceSchema\n )\n ]);\n this.metaInstance = metaInstance;\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n initialCheckpoint: {\n upstream: this.push ? this.push.initialCheckpoint : undefined,\n downstream: this.pull ? this.pull.initialCheckpoint : undefined\n },\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rxdbreplication' + this.replicationIdentifier,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n filter(_v => !!this.pull),\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n useEv.documents = handlePulledDocuments(this.collection, this.deletedField, useEv.documents);\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType | undefined,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n useResult.documents = handlePulledDocuments(this.collection, this.deletedField, useResult.documents);\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n\n await runAsyncPluginHooks('preReplicationMasterWrite', {\n rows,\n collection: this.collection\n });\n\n const useRowsOrNull = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.newDocumentState === null) {\n return null;\n }\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n return row;\n })\n );\n const useRows: RxReplicationWriteToMasterRow[] = useRowsOrNull.filter(arrayFilterNotEmpty);\n\n let result: WithDeleted[] = null as any;\n\n // In case all the rows have been filtered and nothing has to be sent\n if (useRows.length === 0) {\n done = true;\n result = [];\n }\n\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n if (this.isStopped()) {\n return [];\n }\n\n await runAsyncPluginHooks('preReplicationMasterWriteDocumentsHandle', {\n result,\n collection: this.collection\n });\n\n const conflicts = handlePulledDocuments(this.collection, this.deletedField, ensureNotFalsy(result));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.sent.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n async cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = [];\n\n if (this.internalReplicationState) {\n await cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.sent.complete();\n\n return Promise.all(promises);\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n /**\n * It is a common error to forget to add these config\n * objects. So we check here because it makes no sense\n * to start a replication with neither push nor pull.\n */\n if (!pull && !push) {\n throw newRxError('UT3', {\n collection: collection.name,\n args: {\n replicationIdentifier\n }\n });\n }\n\n const replicationState = new RxReplicationState(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":";;;;;;;;AAOA,IAAAA,KAAA,GAAAC,OAAA;AAyBA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAUA,IAAAG,OAAA,GAAAH,OAAA;AAOA,IAAAI,QAAA,GAAAJ,OAAA;AACA,IAAAK,kBAAA,GAAAL,OAAA;AAMA,IAAAM,wBAAA,GAAAN,OAAA;AAGA,IAAAO,OAAA,GAAAP,OAAA;AACA,IAAAQ,gBAAA,GAAAR,OAAA;AACA,IAAAS,aAAA,GAAAT,OAAA;AACA,IAAAU,MAAA,GAAAV,OAAA;AA/DA;AACA;AACA;AACA;AACA;AACA;;AA+DO,IAAMW,+BAAsF,GAAAC,OAAA,CAAAD,+BAAA,GAAG,IAAIE,OAAO,CAAC,CAAC;AAAC,IAEvGC,kBAAkB,GAAAF,OAAA,CAAAE,kBAAA;EAiB3B,SAAAA;EACI;AACR;AACA;AACA;EACwBC,qBAA6B,EAC7BC,UAAmC,EACnCC,YAAoB,EACpBC,IAAwD,EACxDC,IAAwC,EACxCC,IAAc,EACvBC,SAAkB,EAClBC,SAAmB,EAC5B;IAAA,KA7BcC,I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AACA;EACI,IAAME,qBAAqB,GAAGL,iBAAiB,IAAIG,gBAAgB,CAACjK,UAAU,CAAC8C,QAAQ,CAACkB,aAAa;EACrG,IAAMoG,WAAyB,GAAGD,qBAAqB,GAAGF,gBAAgB,CAACjK,UAAU,CAAC8C,QAAQ,CAACgH,iBAAiB,CAAC,CAAC,GAAGO,4BAAoB;EACzI,OAAOD,WAAW,CAACZ,IAAI,CAAC,MAAM;IAC1B,IAAIS,gBAAgB,CAACxH,SAAS,CAAC,CAAC,EAAE;MAC9B;IACJ;IACA,IAAIwH,gBAAgB,CAAC3J,SAAS,EAAE;MAC5B2J,gBAAgB,CAACzH,KAAK,CAAC,CAAC;IAC5B;EACJ,CAAC,CAAC;AACN"} \ No newline at end of file +{"version":3,"file":"index.js","names":["_rxjs","require","_index","_index2","_index3","_rxError","_replicationHelper","_rxDatabaseInternalStore","_plugin","_rxStorageHelper","_overwritable","_hooks","REPLICATION_STATE_BY_COLLECTION","exports","WeakMap","RxReplicationState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","Subject","sent","error","canceled","BehaviorSubject","active","received$","asObservable","sent$","error$","canceled$","active$","onCancel","callOnStart","undefined","remoteEvents$","replicationStates","getFromMapOrCreate","onDestroy","cancel","Object","keys","forEach","key","defineProperty","get","startPromise","Promise","res","_proto","prototype","start","isStopped","pullModifier","modifier","DEFAULT_MODIFIER","pushModifier","database","metaInstanceCollectionName","hashFunction","name","join","metaInstanceSchema","getRxReplicationMetaInstanceSchema","schema","jsonSchema","hasEncryption","metaInstance","all","storage","createStorageInstance","databaseName","collectionName","databaseInstanceToken","token","multiInstance","options","password","devMode","overwritable","isDevMode","addConnectedStorageToCollection","internalReplicationState","replicateRxStorageInstance","pushBatchSize","batchSize","pullBatchSize","initialCheckpoint","upstream","downstream","forkInstance","storageInstance","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","filter","_v","mergeMap","ev","useEv","flatClone","documents","handlePulledDocuments","map","d","masterChangesSince","checkpoint","done","result","handler","err","emitError","newRxError","errors","toArray","er","errorToPlainJson","direction","next","awaitRetry","ensureNotFalsy","useResult","masterWrite","rows","runAsyncPluginHooks","useRowsOrNull","row","newDocumentState","assumedMasterState","swapDefaultDeletedTodeletedField","useRows","arrayFilterNotEmpty","length","Array","isArray","pushRows","args","rxdb","conflicts","events","subscribe","processed","down","document","up","writeToMasterRow","combineLatest","isActive","stream$","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","getValue","awaitInitialReplication","awaitInSync","requestIdlePromise","reSync","emitEvent","PROMISE_RESOLVE_FALSE","promises","fn","toPromise","cancelRxStorageReplication","checkpointQueue","then","close","sub","unsubscribe","complete","replicateRxCollection","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun","PROMISE_RESOLVE_TRUE"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport {\n arrayFilterNotEmpty,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n toArray,\n toPromise\n} from '../../plugins/utils/index.ts';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n getRxReplicationMetaInstanceSchema,\n replicateRxStorageInstance\n} from '../../replication-protocol/index.ts';\nimport { newRxError } from '../../rx-error.ts';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n handlePulledDocuments\n} from './replication-helper.ts';\nimport {\n addConnectedStorageToCollection\n} from '../../rx-database-internal-store.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { hasEncryption } from '../../rx-storage-helper.ts';\nimport { overwritable } from '../../overwritable.ts';\nimport {\n runAsyncPluginHooks\n} from '../../hooks.ts';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n sent: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false) // true when something is running, false when not\n };\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly sent$: Observable> = this.subjects.sent.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n public startPromise: Promise;\n\n public onCancel: (() => void)[] = [];\n\n constructor(\n /**\n * The identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n const replicationStates = getFromMapOrCreate(\n REPLICATION_STATE_BY_COLLECTION,\n collection,\n () => []\n );\n replicationStates.push(this);\n\n // stop the replication when the collection gets destroyed\n this.collection.onDestroy.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance, any, {}, any>;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n const metaInstanceCollectionName = 'rx-replication-meta-' + await database.hashFunction([\n this.collection.name,\n this.replicationIdentifier\n ].join('-'));\n const metaInstanceSchema = getRxReplicationMetaInstanceSchema(\n this.collection.schema.jsonSchema,\n hasEncryption(this.collection.schema.jsonSchema)\n );\n\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance>({\n databaseName: database.name,\n collectionName: metaInstanceCollectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance, // TODO is this always false?\n options: {},\n schema: metaInstanceSchema,\n password: database.password,\n devMode: overwritable.isDevMode()\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInstanceCollectionName,\n metaInstanceSchema\n )\n ]);\n this.metaInstance = metaInstance;\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n initialCheckpoint: {\n upstream: this.push ? this.push.initialCheckpoint : undefined,\n downstream: this.pull ? this.pull.initialCheckpoint : undefined\n },\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rxdbreplication' + this.replicationIdentifier,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n filter(_v => !!this.pull),\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n useEv.documents = handlePulledDocuments(this.collection, this.deletedField, useEv.documents);\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType | undefined,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n useResult.documents = handlePulledDocuments(this.collection, this.deletedField, useResult.documents);\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n\n await runAsyncPluginHooks('preReplicationMasterWrite', {\n rows,\n collection: this.collection\n });\n\n const useRowsOrNull = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.newDocumentState === null) {\n return null;\n }\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n return row;\n })\n );\n const useRows: RxReplicationWriteToMasterRow[] = useRowsOrNull.filter(arrayFilterNotEmpty);\n\n let result: WithDeleted[] = null as any;\n\n // In case all the rows have been filtered and nothing has to be sent\n if (useRows.length === 0) {\n done = true;\n result = [];\n }\n\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n if (this.isStopped()) {\n return [];\n }\n\n await runAsyncPluginHooks('preReplicationMasterWriteDocumentsHandle', {\n result,\n collection: this.collection\n });\n\n const conflicts = handlePulledDocuments(this.collection, this.deletedField, ensureNotFalsy(result));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.sent.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n async cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = this.onCancel.map(fn => toPromise(fn()));\n\n if (this.internalReplicationState) {\n await cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.sent.complete();\n\n return Promise.all(promises);\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n /**\n * It is a common error to forget to add these config\n * objects. So we check here because it makes no sense\n * to start a replication with neither push nor pull.\n */\n if (!pull && !push) {\n throw newRxError('UT3', {\n collection: collection.name,\n args: {\n replicationIdentifier\n }\n });\n }\n\n const replicationState = new RxReplicationState(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":";;;;;;;;AAOA,IAAAA,KAAA,GAAAC,OAAA;AAyBA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAWA,IAAAG,OAAA,GAAAH,OAAA;AAOA,IAAAI,QAAA,GAAAJ,OAAA;AACA,IAAAK,kBAAA,GAAAL,OAAA;AAMA,IAAAM,wBAAA,GAAAN,OAAA;AAGA,IAAAO,OAAA,GAAAP,OAAA;AACA,IAAAQ,gBAAA,GAAAR,OAAA;AACA,IAAAS,aAAA,GAAAT,OAAA;AACA,IAAAU,M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ACjK,IAAI,IAAI,CAACC,IAAI,EAAE;IAChB,MAAM,IAAAqG,mBAAU,EAAC,KAAK,EAAE;MACpBxG,UAAU,EAAEA,UAAU,CAACkD,IAAI;MAC3B8E,IAAI,EAAE;QACFjI;MACJ;IACJ,CAAC,CAAC;EACN;EAEA,IAAMqK,gBAAgB,GAAG,IAAItK,kBAAkB,CAC3CC,qBAAqB,EACrBC,UAAU,EACVC,YAAY,EACZC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SACJ,CAAC;EAGD+J,4BAA4B,CAACJ,iBAAiB,EAAEG,gBAAgB,CAAC;EACjE,OAAOA,gBAAgB;AAC3B;AAGO,SAASC,4BAA4BA,CACxCJ,iBAA0B,EAC1BG,gBAA8C,EAChD;EACE;AACJ;AACA;AACA;EACI,IAAME,qBAAqB,GAAGL,iBAAiB,IAAIG,gBAAgB,CAACpK,UAAU,CAAC+C,QAAQ,CAACkB,aAAa;EACrG,IAAMsG,WAAyB,GAAGD,qBAAqB,GAAGF,gBAAgB,CAACpK,UAAU,CAAC+C,QAAQ,CAACkH,iBAAiB,CAAC,CAAC,GAAGO,4BAAoB;EACzI,OAAOD,WAAW,CAACZ,IAAI,CAAC,MAAM;IAC1B,IAAIS,gBAAgB,CAAC1H,SAAS,CAAC,CAAC,EAAE;MAC9B;IACJ;IACA,IAAI0H,gBAAgB,CAAC9J,SAAS,EAAE;MAC5B8J,gBAAgB,CAAC3H,KAAK,CAAC,CAAC;IAC5B;EACJ,CAAC,CAAC;AACN"} \ No newline at end of file diff --git a/dist/cjs/plugins/storage-memory/memory-types.js.map b/dist/cjs/plugins/storage-memory/memory-types.js.map index d327fec2950..7d699393ddd 100644 --- a/dist/cjs/plugins/storage-memory/memory-types.js.map +++ b/dist/cjs/plugins/storage-memory/memory-types.js.map @@ -1 +1 @@ -{"version":3,"file":"memory-types.js","names":[],"sources":["../../../../src/plugins/storage-memory/memory-types.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageChangeEvent,\n RxStorageDefaultCheckpoint\n} from '../../types/index.d.ts';\n\nexport type RxStorageMemorySettings = {};\nexport type RxStorageMemoryInstanceCreationOptions = {};\nexport type RxStorageMemory = RxStorage, RxStorageMemoryInstanceCreationOptions> & {\n /**\n * State by collectionKey\n */\n collectionStates: Map>;\n};\n\nexport type MemoryStorageInternalsByIndex = {\n index: string[];\n docsWithIndex: DocWithIndexString[];\n getIndexableString: (docData: RxDocumentData) => string;\n};\n\n/**\n * The internals are shared between multiple storage instances\n * that have been created with the same [databaseName+collectionName] combination.\n */\nexport type MemoryStorageInternals = {\n\n /**\n * Schema of the first instance created with the given settings.\n * Used to ensure that the same storage is not re-created with\n * a different schema.\n */\n schema: RxJsonSchema>;\n\n /**\n * We reuse the memory state when multiple instances\n * are created with the same params.\n * If refCount becomes 0, we can delete the state.\n */\n refCount: number;\n /**\n * If this becomes true,\n * it means that an instance has called remove()\n * so all other instances should also not work anymore.\n */\n removed: boolean;\n documents: Map>;\n /**\n * Attachments data, indexed by a combined string\n * consisting of [documentId + '||' + attachmentId]\n */\n attachments: Map;\n byIndex: {\n /**\n * Because RxDB requires a deterministic sorting\n * on all indexes, we can be sure that the composed index key\n * of each document is unique, because it contains the primaryKey\n * as last index part.\n * So we do not have to store the index-position when we want to do fast\n * writes. Instead we can do a binary search over the existing array\n * because RxDB also knows the previous state of the document when we do a bulkWrite().\n */\n [indexName: string]: MemoryStorageInternalsByIndex;\n };\n\n /**\n * We need these to do lazy writes.\n */\n ensurePersistenceTask?: CategorizeBulkWriteRowsOutput;\n ensurePersistenceIdlePromise?: Promise;\n\n /**\n * To easier test the conflict resolution,\n * the memory storage exposes the conflict resolution task subject\n * so that we can inject own tasks during tests.\n */\n conflictResultionTasks$: Subject>;\n changes$: Subject>, RxStorageDefaultCheckpoint>>;\n};\n\nexport type DocWithIndexString = {\n id: string;\n doc: RxDocumentData;\n indexString: string;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"memory-types.js","names":[],"sources":["../../../../src/plugins/storage-memory/memory-types.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageChangeEvent,\n RxStorageDefaultCheckpoint\n} from '../../types/index.d.ts';\n\nexport type RxStorageMemorySettings = {};\nexport type RxStorageMemoryInstanceCreationOptions = {};\nexport type RxStorageMemory = RxStorage, RxStorageMemoryInstanceCreationOptions> & {\n /**\n * State by collectionKey\n */\n collectionStates: Map>;\n};\n\nexport type MemoryStorageInternalsByIndex = {\n index: string[];\n docsWithIndex: DocWithIndexString[];\n getIndexableString: (docData: RxDocumentData) => string;\n};\n\n/**\n * The internals are shared between multiple storage instances\n * that have been created with the same [databaseName+collectionName] combination.\n */\nexport type MemoryStorageInternals = {\n // used to debug stuff and identify instances\n id: string;\n\n /**\n * Schema of the first instance created with the given settings.\n * Used to ensure that the same storage is not re-created with\n * a different schema.\n */\n schema: RxJsonSchema>;\n\n /**\n * We reuse the memory state when multiple instances\n * are created with the same params.\n * If refCount becomes 0, we can delete the state.\n */\n refCount: number;\n /**\n * If this becomes true,\n * it means that an instance has called remove()\n * so all other instances should also not work anymore.\n */\n removed: boolean;\n documents: Map>;\n /**\n * Attachments data, indexed by a combined string\n * consisting of [documentId + '||' + attachmentId]\n */\n attachments: Map;\n byIndex: {\n /**\n * Because RxDB requires a deterministic sorting\n * on all indexes, we can be sure that the composed index key\n * of each document is unique, because it contains the primaryKey\n * as last index part.\n * So we do not have to store the index-position when we want to do fast\n * writes. Instead we can do a binary search over the existing array\n * because RxDB also knows the previous state of the document when we do a bulkWrite().\n */\n [indexName: string]: MemoryStorageInternalsByIndex;\n };\n\n /**\n * We need these to do lazy writes.\n */\n ensurePersistenceTask?: CategorizeBulkWriteRowsOutput;\n ensurePersistenceIdlePromise?: Promise;\n\n /**\n * To easier test the conflict resolution,\n * the memory storage exposes the conflict resolution task subject\n * so that we can inject own tasks during tests.\n */\n conflictResultionTasks$: Subject>;\n changes$: Subject>, RxStorageDefaultCheckpoint>>;\n};\n\nexport type DocWithIndexString = {\n id: string;\n doc: RxDocumentData;\n indexString: string;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/plugins/storage-memory/rx-storage-instance-memory.js b/dist/cjs/plugins/storage-memory/rx-storage-instance-memory.js index 88851a7f134..956707f3f29 100644 --- a/dist/cjs/plugins/storage-memory/rx-storage-instance-memory.js +++ b/dist/cjs/plugins/storage-memory/rx-storage-instance-memory.js @@ -100,7 +100,7 @@ var RxStorageInstanceMemory = exports.RxStorageInstanceMemory = /*#__PURE__*/fun var documentsById = this.internals.documents; var primaryPath = this.primaryPath; var categorized = this.internals.ensurePersistenceTask; - delete this.internals.ensurePersistenceTask; + this.internals.ensurePersistenceTask = undefined; /** * Do inserts/updates @@ -181,17 +181,6 @@ var RxStorageInstanceMemory = exports.RxStorageInstanceMemory = /*#__PURE__*/fun upperBound = upperBound; var upperBoundString = (0, _customIndex.getStartIndexStringFromUpperBound)(this.schema, index, upperBound); var indexName = (0, _memoryIndexes.getMemoryIndexName)(index); - - // console.log('in memory query:'); - // console.dir({ - // queryPlan, - // lowerBound, - // upperBound, - // lowerBoundString, - // upperBoundString, - // indexName - // }); - if (!this.internals.byIndex[indexName]) { throw new Error('index does not exist ' + indexName); } @@ -306,6 +295,7 @@ function createMemoryStorageInstance(storage, params, settings) { var internals = storage.collectionStates.get(collectionKey); if (!internals) { internals = { + id: (0, _index.randomCouchString)(5), schema: params.schema, removed: false, refCount: 1, diff --git a/dist/cjs/plugins/storage-memory/rx-storage-instance-memory.js.map b/dist/cjs/plugins/storage-memory/rx-storage-instance-memory.js.map index a8683b087b3..790a7336a92 100644 --- a/dist/cjs/plugins/storage-memory/rx-storage-instance-memory.js.map +++ b/dist/cjs/plugins/storage-memory/rx-storage-instance-memory.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-instance-memory.js","names":["_rxjs","require","_customIndex","_rxSchemaHelper","_rxStorageHelper","_index","_binarySearchBounds","_memoryHelper","_memoryIndexes","_rxQueryHelper","OPEN_MEMORY_INSTANCES","exports","Set","RxStorageInstanceMemory","storage","databaseName","collectionName","schema","internals","options","settings","closed","add","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","_proto","prototype","bulkWrite","documentWrites","context","ensurePersistence","ensureNotRemoved","documentsById","documents","categorized","categorizeBulkWriteRows","error","errors","success","Array","bulkInsertDocs","length","i","writeRow","doc","document","bulkUpdateDocs","push","ensurePersistenceTask","ensurePersistenceIdlePromise","requestIdlePromiseNoQueue","then","undefined","eventBulk","events","lastState","ensureNotFalsy","newestRow","checkpoint","id","lwt","_meta","endTime","now","PROMISE_RESOLVE_TRUE","changes$","next","ret","Promise","resolve","stateByIndex","Object","values","byIndex","docId","putWriteRowToState","get","attachments","attachmentsMap","attachmentsAdd","forEach","attachment","set","attachmentMapKey","documentId","attachmentId","writeData","attachmentData","digest","attachmentsUpdate","attachmentsRemove","delete","findDocumentsById","docIds","withDeleted","size","docInDb","_deleted","query","preparedQuery","queryPlan","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","getQueryMatcher","queryPlanFields","index","mustManuallyResort","sortSatisfiedByIndex","lowerBound","startKeys","lowerBoundString","getStartIndexStringFromLowerBound","upperBound","endKeys","upperBoundString","getStartIndexStringFromUpperBound","indexName","getMemoryIndexName","Error","docsWithIndex","indexOfLower","inclusiveStart","boundGE","boundGT","indexString","compareDocsWithIndex","indexOfUpper","inclusiveEnd","boundLE","boundLT","rows","done","currentRow","currentDoc","sortComparator","getSortComparator","sort","slice","count","result","mode","cleanup","minimumDeletedTime","maxDeletionTime","removeDocFromState","getAttachmentData","key","data","changeStream","asObservable","remove","removed","collectionStates","getMemoryCollectionKey","version","close","PROMISE_RESOLVE_VOID","refCount","conflictResultionTasks","conflictResultionTasks$","resolveConflictResultionTask","_taskSolution","createMemoryStorageInstance","params","collectionKey","Map","Subject","addIndexesToInternalsState","devMode","deepEqual","instance"],"sources":["../../../../src/plugins/storage-memory/rx-storage-instance-memory.ts"],"sourcesContent":["import {\n Observable,\n Subject\n} from 'rxjs';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index.ts';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper.ts';\nimport {\n categorizeBulkWriteRows\n} from '../../rx-storage-helper.ts';\nimport type {\n BulkWriteRow,\n EventBulk,\n PreparedQuery,\n QueryMatcher,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types/index.d.ts';\nimport {\n deepEqual,\n ensureNotFalsy,\n lastOfArray,\n now,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID,\n requestIdlePromiseNoQueue,\n RX_META_LWT_MINIMUM,\n toArray\n} from '../../plugins/utils/index.ts';\nimport {\n boundGE,\n boundGT,\n boundLE,\n boundLT\n} from './binary-search-bounds.ts';\nimport {\n attachmentMapKey,\n compareDocsWithIndex,\n ensureNotRemoved,\n getMemoryCollectionKey,\n putWriteRowToState,\n removeDocFromState\n} from './memory-helper.ts';\nimport {\n addIndexesToInternalsState,\n getMemoryIndexName\n} from './memory-indexes.ts';\nimport type {\n MemoryStorageInternals,\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types.ts';\nimport { getQueryMatcher, getSortComparator } from '../../rx-query-helper.ts';\n\n/**\n * Used in tests to ensure everything\n * is closed correctly\n */\nexport const OPEN_MEMORY_INSTANCES = new Set>();\n\nexport class RxStorageInstanceMemory implements RxStorageInstance<\n RxDocType,\n MemoryStorageInternals,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n public closed = false;\n\n constructor(\n public readonly storage: RxStorageMemory,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: MemoryStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageMemorySettings\n ) {\n OPEN_MEMORY_INSTANCES.add(this);\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n this.ensurePersistence();\n ensureNotRemoved(this);\n const internals = this.internals;\n const documentsById = this.internals.documents;\n const primaryPath = this.primaryPath;\n\n const categorized = categorizeBulkWriteRows(\n this,\n primaryPath as any,\n documentsById,\n documentWrites,\n context\n );\n const error = categorized.errors;\n const success: RxDocumentData[] = new Array(categorized.bulkInsertDocs.length);\n const bulkInsertDocs = categorized.bulkInsertDocs;\n for (let i = 0; i < bulkInsertDocs.length; ++i) {\n const writeRow = bulkInsertDocs[i];\n const doc = writeRow.document;\n success[i] = doc;\n }\n const bulkUpdateDocs = categorized.bulkUpdateDocs;\n for (let i = 0; i < bulkUpdateDocs.length; ++i) {\n const writeRow = bulkUpdateDocs[i];\n const doc = writeRow.document;\n success.push(doc);\n }\n\n this.internals.ensurePersistenceTask = categorized;\n if (!this.internals.ensurePersistenceIdlePromise) {\n this.internals.ensurePersistenceIdlePromise = requestIdlePromiseNoQueue().then(() => {\n this.internals.ensurePersistenceIdlePromise = undefined;\n this.ensurePersistence();\n });\n }\n\n /**\n * Important: The events must be emitted AFTER the persistence\n * task has been added.\n */\n if (categorized.eventBulk.events.length > 0) {\n const lastState = ensureNotFalsy(categorized.newestRow).document;\n categorized.eventBulk.checkpoint = {\n id: lastState[primaryPath],\n lwt: lastState._meta.lwt\n };\n categorized.eventBulk.endTime = now();\n PROMISE_RESOLVE_TRUE.then(() => {\n internals.changes$.next(categorized.eventBulk);\n });\n }\n\n const ret = Promise.resolve({ success, error });\n return ret;\n }\n\n /**\n * Instead of directly inserting the documents into all indexes,\n * we do it lazy in the background. This gives the application time\n * to directly work with the write-result and to do stuff like rendering DOM\n * notes and processing RxDB queries.\n * Then in some later time, or just before the next read/write,\n * it is ensured that the indexes have been written.\n */\n public ensurePersistence() {\n if (\n !this.internals.ensurePersistenceTask\n ) {\n return;\n }\n const internals = this.internals;\n const documentsById = this.internals.documents;\n const primaryPath = this.primaryPath;\n\n const categorized = this.internals.ensurePersistenceTask;\n delete this.internals.ensurePersistenceTask;\n\n /**\n * Do inserts/updates\n */\n const stateByIndex = Object.values(this.internals.byIndex);\n\n const bulkInsertDocs = categorized.bulkInsertDocs;\n for (let i = 0; i < bulkInsertDocs.length; ++i) {\n const writeRow = bulkInsertDocs[i];\n const doc = writeRow.document;\n const docId = doc[primaryPath];\n putWriteRowToState(\n docId as any,\n internals,\n stateByIndex,\n writeRow,\n undefined\n );\n }\n\n const bulkUpdateDocs = categorized.bulkUpdateDocs;\n for (let i = 0; i < bulkUpdateDocs.length; ++i) {\n const writeRow = bulkUpdateDocs[i];\n const doc = writeRow.document;\n const docId = doc[primaryPath];\n putWriteRowToState(\n docId as any,\n internals,\n stateByIndex,\n writeRow,\n documentsById.get(docId as any)\n );\n }\n\n /**\n * Handle attachments\n */\n if (this.schema.attachments) {\n const attachmentsMap = internals.attachments;\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n {\n writeData: attachment.attachmentData,\n digest: attachment.digest\n }\n );\n });\n if (this.schema.attachments) {\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n {\n writeData: attachment.attachmentData,\n digest: attachment.digest\n }\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentsMap.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n }\n }\n }\n\n findDocumentsById(\n docIds: string[],\n withDeleted: boolean\n ): Promise[]> {\n this.ensurePersistence();\n const documentsById = this.internals.documents;\n const ret: RxDocumentData[] = [];\n if (documentsById.size === 0) {\n return Promise.resolve(ret);\n }\n for (let i = 0; i < docIds.length; ++i) {\n const docId = docIds[i];\n const docInDb = documentsById.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret.push(docInDb);\n }\n }\n return Promise.resolve(ret);\n }\n\n query(\n preparedQuery: PreparedQuery\n ): Promise> {\n this.ensurePersistence();\n\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = getQueryMatcher(\n this.schema,\n preparedQuery.query\n );\n }\n\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortSatisfiedByIndex;\n const index: string[] | undefined = queryPlanFields;\n const lowerBound: any[] = queryPlan.startKeys;\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n lowerBound\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = upperBound;\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n upperBound\n );\n const indexName = getMemoryIndexName(index);\n\n // console.log('in memory query:');\n // console.dir({\n // queryPlan,\n // lowerBound,\n // upperBound,\n // lowerBoundString,\n // upperBoundString,\n // indexName\n // });\n\n if (!this.internals.byIndex[indexName]) {\n throw new Error('index does not exist ' + indexName);\n }\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n\n\n let indexOfLower = (queryPlan.inclusiveStart ? boundGE : boundGT)(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n const indexOfUpper = (queryPlan.inclusiveEnd ? boundLE : boundLT)(\n docsWithIndex,\n {\n indexString: upperBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let rows: RxDocumentData[] = [];\n let done = false;\n while (!done) {\n const currentRow = docsWithIndex[indexOfLower];\n if (\n !currentRow ||\n indexOfLower > indexOfUpper\n ) {\n break;\n }\n const currentDoc = currentRow.doc;\n\n if (!queryMatcher || queryMatcher(currentDoc)) {\n rows.push(currentDoc);\n }\n\n if (\n (rows.length >= skipPlusLimit && !mustManuallyResort)\n ) {\n done = true;\n }\n\n indexOfLower++;\n }\n\n if (mustManuallyResort) {\n const sortComparator = getSortComparator(this.schema, preparedQuery.query);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n return Promise.resolve({\n documents: rows\n });\n }\n\n async count(\n preparedQuery: PreparedQuery\n ): Promise {\n this.ensurePersistence();\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n\n cleanup(minimumDeletedTime: number): Promise {\n this.ensurePersistence();\n const maxDeletionTime = now() - minimumDeletedTime;\n const index = ['_deleted', '_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n 0,\n ''\n ]\n );\n\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n if (!currentDoc || currentDoc.doc._meta.lwt > maxDeletionTime) {\n done = true;\n } else {\n removeDocFromState(\n this.primaryPath as any,\n this.schema,\n this.internals,\n currentDoc.doc\n );\n indexOfLower++;\n }\n }\n return PROMISE_RESOLVE_TRUE;\n }\n\n getAttachmentData(\n documentId: string,\n attachmentId: string,\n digest: string\n ): Promise {\n this.ensurePersistence();\n ensureNotRemoved(this);\n const key = attachmentMapKey(documentId, attachmentId);\n const data = this.internals.attachments.get(key);\n\n if (\n !digest ||\n !data ||\n data.digest !== digest\n ) {\n throw new Error('attachment does not exist: ' + key);\n }\n return Promise.resolve(data.writeData.data);\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotRemoved(this);\n return this.internals.changes$.asObservable();\n }\n\n async remove(): Promise {\n if (this.closed) {\n throw new Error('closed');\n }\n this.ensurePersistence();\n ensureNotRemoved(this);\n\n this.internals.removed = true;\n this.storage.collectionStates.delete(\n getMemoryCollectionKey(\n this.databaseName,\n this.collectionName,\n this.schema.version\n )\n );\n await this.close();\n }\n\n close(): Promise {\n OPEN_MEMORY_INSTANCES.delete(this);\n\n this.ensurePersistence();\n if (this.closed) {\n return PROMISE_RESOLVE_VOID;\n }\n this.closed = true;\n\n this.internals.refCount = this.internals.refCount - 1;\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return this.internals.conflictResultionTasks$.asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n}\n\nexport function createMemoryStorageInstance(\n storage: RxStorageMemory,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageMemorySettings\n): Promise> {\n const collectionKey = getMemoryCollectionKey(\n params.databaseName,\n params.collectionName,\n params.schema.version\n );\n\n let internals = storage.collectionStates.get(collectionKey);\n if (!internals) {\n internals = {\n schema: params.schema,\n removed: false,\n refCount: 1,\n documents: new Map(),\n attachments: params.schema.attachments ? new Map() : undefined as any,\n byIndex: {},\n conflictResultionTasks$: new Subject(),\n changes$: new Subject()\n };\n addIndexesToInternalsState(internals, params.schema);\n storage.collectionStates.set(collectionKey, internals);\n } else {\n /**\n * Ensure that the storage was not already\n * created with a different schema.\n * This is very important because if this check\n * does not exist here, we have hard-to-debug problems\n * downstream.\n */\n if (\n params.devMode &&\n !deepEqual(internals.schema, params.schema)\n ) {\n throw new Error('storage was already created with a different schema');\n }\n internals.refCount = internals.refCount + 1;\n }\n\n const instance = new RxStorageInstanceMemory(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAIA,IAAAC,YAAA,GAAAD,OAAA;AAIA,IAAAE,eAAA,GAAAF,OAAA;AACA,IAAAG,gBAAA,GAAAH,OAAA;AAqBA,IAAAI,MAAA,GAAAJ,OAAA;AAWA,IAAAK,mBAAA,GAAAL,OAAA;AAMA,IAAAM,aAAA,GAAAN,OAAA;AAQA,IAAAO,cAAA,GAAAP,OAAA;AAUA,IAAAQ,cAAA,GAAAR,OAAA;AAEA;AACA;AACA;AACA;AACO,IAAMS,qBAAqB,GAAAC,OAAA,CAAAD,qBAAA,GAAG,IAAIE,GAAG,CAA+B,CAAC;AAAC,IAEhEC,uBAAuB,GAAAF,OAAA,CAAAE,uBAAA;EAUhC,SAAAA,wBACoBC,OAAwB,EACxBC,YAAoB,EACpBC,cAAsB,EACtBC,MAAyD,EACzDC,SAA4C,EAC5CC,OAAyD,EACzDC,QAAiC,EACnD;IAAA,KAVKC,MAAM,GAAG,KAAK;IAAA,KAGDP,OAAwB,GAAxBA,OAAwB;IAAA,KACxBC,YAAoB,GAApBA,YAAoB;IAAA,KACpBC,cAAsB,GAAtBA,cAAsB;IAAA,KACtBC,MAAyD,GAAzDA,MAAyD;IAAA,KACzDC,SAA4C,GAA5CA,SAA4C;IAAA,KAC5CC,OAAyD,GAAzDA,OAAyD;IAAA,KACzDC,QAAiC,GAAjCA,QAAiC;IAEjDV,qBAAqB,CAACY,GAAG,CAAC,IAAI,CAAC;IAC/B,IAAI,CAACC,WAAW,GAAG,IAAAC,2CAA2B,EAAC,IAAI,CAACP,MAAM,CAACQ,UAA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AAuB,CACxCC,OAAO,EACP0J,MAAM,CAACzJ,YAAY,EACnByJ,MAAM,CAACxJ,cAAc,EACrBwJ,MAAM,CAACvJ,MAAM,EACbC,SAAS,EACTsJ,MAAM,CAACrJ,OAAO,EACdC,QACJ,CAAC;EACD,OAAOiD,OAAO,CAACC,OAAO,CAACyG,QAAQ,CAAC;AACpC"} \ No newline at end of file +{"version":3,"file":"rx-storage-instance-memory.js","names":["_rxjs","require","_customIndex","_rxSchemaHelper","_rxStorageHelper","_index","_binarySearchBounds","_memoryHelper","_memoryIndexes","_rxQueryHelper","OPEN_MEMORY_INSTANCES","exports","Set","RxStorageInstanceMemory","storage","databaseName","collectionName","schema","internals","options","settings","closed","add","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","_proto","prototype","bulkWrite","documentWrites","context","ensurePersistence","ensureNotRemoved","documentsById","documents","categorized","categorizeBulkWriteRows","error","errors","success","Array","bulkInsertDocs","length","i","writeRow","doc","document","bulkUpdateDocs","push","ensurePersistenceTask","ensurePersistenceIdlePromise","requestIdlePromiseNoQueue","then","undefined","eventBulk","events","lastState","ensureNotFalsy","newestRow","checkpoint","id","lwt","_meta","endTime","now","PROMISE_RESOLVE_TRUE","changes$","next","ret","Promise","resolve","stateByIndex","Object","values","byIndex","docId","putWriteRowToState","get","attachments","attachmentsMap","attachmentsAdd","forEach","attachment","set","attachmentMapKey","documentId","attachmentId","writeData","attachmentData","digest","attachmentsUpdate","attachmentsRemove","delete","findDocumentsById","docIds","withDeleted","size","docInDb","_deleted","query","preparedQuery","queryPlan","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","getQueryMatcher","queryPlanFields","index","mustManuallyResort","sortSatisfiedByIndex","lowerBound","startKeys","lowerBoundString","getStartIndexStringFromLowerBound","upperBound","endKeys","upperBoundString","getStartIndexStringFromUpperBound","indexName","getMemoryIndexName","Error","docsWithIndex","indexOfLower","inclusiveStart","boundGE","boundGT","indexString","compareDocsWithIndex","indexOfUpper","inclusiveEnd","boundLE","boundLT","rows","done","currentRow","currentDoc","sortComparator","getSortComparator","sort","slice","count","result","mode","cleanup","minimumDeletedTime","maxDeletionTime","removeDocFromState","getAttachmentData","key","data","changeStream","asObservable","remove","removed","collectionStates","getMemoryCollectionKey","version","close","PROMISE_RESOLVE_VOID","refCount","conflictResultionTasks","conflictResultionTasks$","resolveConflictResultionTask","_taskSolution","createMemoryStorageInstance","params","collectionKey","randomCouchString","Map","Subject","addIndexesToInternalsState","devMode","deepEqual","instance"],"sources":["../../../../src/plugins/storage-memory/rx-storage-instance-memory.ts"],"sourcesContent":["import {\n Observable,\n Subject\n} from 'rxjs';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index.ts';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper.ts';\nimport {\n categorizeBulkWriteRows\n} from '../../rx-storage-helper.ts';\nimport type {\n BulkWriteRow,\n EventBulk,\n PreparedQuery,\n QueryMatcher,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types/index.d.ts';\nimport {\n deepEqual,\n ensureNotFalsy,\n now,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID,\n randomCouchString,\n requestIdlePromiseNoQueue\n} from '../../plugins/utils/index.ts';\nimport {\n boundGE,\n boundGT,\n boundLE,\n boundLT\n} from './binary-search-bounds.ts';\nimport {\n attachmentMapKey,\n compareDocsWithIndex,\n ensureNotRemoved,\n getMemoryCollectionKey,\n putWriteRowToState,\n removeDocFromState\n} from './memory-helper.ts';\nimport {\n addIndexesToInternalsState,\n getMemoryIndexName\n} from './memory-indexes.ts';\nimport type {\n MemoryStorageInternals,\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types.ts';\nimport { getQueryMatcher, getSortComparator } from '../../rx-query-helper.ts';\n\n/**\n * Used in tests to ensure everything\n * is closed correctly\n */\nexport const OPEN_MEMORY_INSTANCES = new Set>();\n\nexport class RxStorageInstanceMemory implements RxStorageInstance<\n RxDocType,\n MemoryStorageInternals,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n public closed = false;\n\n constructor(\n public readonly storage: RxStorageMemory,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: MemoryStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageMemorySettings\n ) {\n OPEN_MEMORY_INSTANCES.add(this);\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n this.ensurePersistence();\n ensureNotRemoved(this);\n const internals = this.internals;\n const documentsById = this.internals.documents;\n const primaryPath = this.primaryPath;\n\n const categorized = categorizeBulkWriteRows(\n this,\n primaryPath as any,\n documentsById,\n documentWrites,\n context\n );\n const error = categorized.errors;\n const success: RxDocumentData[] = new Array(categorized.bulkInsertDocs.length);\n const bulkInsertDocs = categorized.bulkInsertDocs;\n for (let i = 0; i < bulkInsertDocs.length; ++i) {\n const writeRow = bulkInsertDocs[i];\n const doc = writeRow.document;\n success[i] = doc;\n }\n const bulkUpdateDocs = categorized.bulkUpdateDocs;\n for (let i = 0; i < bulkUpdateDocs.length; ++i) {\n const writeRow = bulkUpdateDocs[i];\n const doc = writeRow.document;\n success.push(doc);\n }\n\n this.internals.ensurePersistenceTask = categorized;\n if (!this.internals.ensurePersistenceIdlePromise) {\n this.internals.ensurePersistenceIdlePromise = requestIdlePromiseNoQueue().then(() => {\n this.internals.ensurePersistenceIdlePromise = undefined;\n this.ensurePersistence();\n });\n }\n\n /**\n * Important: The events must be emitted AFTER the persistence\n * task has been added.\n */\n if (categorized.eventBulk.events.length > 0) {\n const lastState = ensureNotFalsy(categorized.newestRow).document;\n categorized.eventBulk.checkpoint = {\n id: lastState[primaryPath],\n lwt: lastState._meta.lwt\n };\n categorized.eventBulk.endTime = now();\n PROMISE_RESOLVE_TRUE.then(() => {\n internals.changes$.next(categorized.eventBulk);\n });\n }\n\n const ret = Promise.resolve({ success, error });\n return ret;\n }\n\n /**\n * Instead of directly inserting the documents into all indexes,\n * we do it lazy in the background. This gives the application time\n * to directly work with the write-result and to do stuff like rendering DOM\n * notes and processing RxDB queries.\n * Then in some later time, or just before the next read/write,\n * it is ensured that the indexes have been written.\n */\n public ensurePersistence() {\n if (\n !this.internals.ensurePersistenceTask\n ) {\n return;\n }\n const internals = this.internals;\n const documentsById = this.internals.documents;\n const primaryPath = this.primaryPath;\n\n const categorized = this.internals.ensurePersistenceTask;\n this.internals.ensurePersistenceTask = undefined;\n\n /**\n * Do inserts/updates\n */\n const stateByIndex = Object.values(this.internals.byIndex);\n\n const bulkInsertDocs = categorized.bulkInsertDocs;\n for (let i = 0; i < bulkInsertDocs.length; ++i) {\n const writeRow = bulkInsertDocs[i];\n const doc = writeRow.document;\n const docId = doc[primaryPath];\n putWriteRowToState(\n docId as any,\n internals,\n stateByIndex,\n writeRow,\n undefined\n );\n }\n\n const bulkUpdateDocs = categorized.bulkUpdateDocs;\n for (let i = 0; i < bulkUpdateDocs.length; ++i) {\n const writeRow = bulkUpdateDocs[i];\n const doc = writeRow.document;\n const docId = doc[primaryPath];\n putWriteRowToState(\n docId as any,\n internals,\n stateByIndex,\n writeRow,\n documentsById.get(docId as any)\n );\n }\n\n /**\n * Handle attachments\n */\n if (this.schema.attachments) {\n const attachmentsMap = internals.attachments;\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n {\n writeData: attachment.attachmentData,\n digest: attachment.digest\n }\n );\n });\n if (this.schema.attachments) {\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n {\n writeData: attachment.attachmentData,\n digest: attachment.digest\n }\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentsMap.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n }\n }\n }\n\n findDocumentsById(\n docIds: string[],\n withDeleted: boolean\n ): Promise[]> {\n this.ensurePersistence();\n const documentsById = this.internals.documents;\n const ret: RxDocumentData[] = [];\n if (documentsById.size === 0) {\n return Promise.resolve(ret);\n }\n for (let i = 0; i < docIds.length; ++i) {\n const docId = docIds[i];\n const docInDb = documentsById.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret.push(docInDb);\n }\n }\n return Promise.resolve(ret);\n }\n\n query(\n preparedQuery: PreparedQuery\n ): Promise> {\n this.ensurePersistence();\n\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = getQueryMatcher(\n this.schema,\n preparedQuery.query\n );\n }\n\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortSatisfiedByIndex;\n const index: string[] | undefined = queryPlanFields;\n const lowerBound: any[] = queryPlan.startKeys;\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n lowerBound\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = upperBound;\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n upperBound\n );\n const indexName = getMemoryIndexName(index);\n\n if (!this.internals.byIndex[indexName]) {\n throw new Error('index does not exist ' + indexName);\n }\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n\n\n let indexOfLower = (queryPlan.inclusiveStart ? boundGE : boundGT)(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n const indexOfUpper = (queryPlan.inclusiveEnd ? boundLE : boundLT)(\n docsWithIndex,\n {\n indexString: upperBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let rows: RxDocumentData[] = [];\n let done = false;\n while (!done) {\n const currentRow = docsWithIndex[indexOfLower];\n if (\n !currentRow ||\n indexOfLower > indexOfUpper\n ) {\n break;\n }\n const currentDoc = currentRow.doc;\n\n if (!queryMatcher || queryMatcher(currentDoc)) {\n rows.push(currentDoc);\n }\n\n if (\n (rows.length >= skipPlusLimit && !mustManuallyResort)\n ) {\n done = true;\n }\n\n indexOfLower++;\n }\n\n if (mustManuallyResort) {\n const sortComparator = getSortComparator(this.schema, preparedQuery.query);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n return Promise.resolve({\n documents: rows\n });\n }\n\n async count(\n preparedQuery: PreparedQuery\n ): Promise {\n this.ensurePersistence();\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n\n cleanup(minimumDeletedTime: number): Promise {\n this.ensurePersistence();\n const maxDeletionTime = now() - minimumDeletedTime;\n const index = ['_deleted', '_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n 0,\n ''\n ]\n );\n\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n if (!currentDoc || currentDoc.doc._meta.lwt > maxDeletionTime) {\n done = true;\n } else {\n removeDocFromState(\n this.primaryPath as any,\n this.schema,\n this.internals,\n currentDoc.doc\n );\n indexOfLower++;\n }\n }\n return PROMISE_RESOLVE_TRUE;\n }\n\n getAttachmentData(\n documentId: string,\n attachmentId: string,\n digest: string\n ): Promise {\n this.ensurePersistence();\n ensureNotRemoved(this);\n const key = attachmentMapKey(documentId, attachmentId);\n const data = this.internals.attachments.get(key);\n\n if (\n !digest ||\n !data ||\n data.digest !== digest\n ) {\n throw new Error('attachment does not exist: ' + key);\n }\n return Promise.resolve(data.writeData.data);\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotRemoved(this);\n return this.internals.changes$.asObservable();\n }\n\n async remove(): Promise {\n if (this.closed) {\n throw new Error('closed');\n }\n this.ensurePersistence();\n ensureNotRemoved(this);\n\n this.internals.removed = true;\n this.storage.collectionStates.delete(\n getMemoryCollectionKey(\n this.databaseName,\n this.collectionName,\n this.schema.version\n )\n );\n await this.close();\n }\n\n close(): Promise {\n OPEN_MEMORY_INSTANCES.delete(this);\n\n this.ensurePersistence();\n if (this.closed) {\n return PROMISE_RESOLVE_VOID;\n }\n this.closed = true;\n\n this.internals.refCount = this.internals.refCount - 1;\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return this.internals.conflictResultionTasks$.asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n}\n\nexport function createMemoryStorageInstance(\n storage: RxStorageMemory,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageMemorySettings\n): Promise> {\n const collectionKey = getMemoryCollectionKey(\n params.databaseName,\n params.collectionName,\n params.schema.version\n );\n\n let internals = storage.collectionStates.get(collectionKey);\n if (!internals) {\n internals = {\n id: randomCouchString(5),\n schema: params.schema,\n removed: false,\n refCount: 1,\n documents: new Map(),\n attachments: params.schema.attachments ? new Map() : undefined as any,\n byIndex: {},\n conflictResultionTasks$: new Subject(),\n changes$: new Subject()\n };\n addIndexesToInternalsState(internals, params.schema);\n storage.collectionStates.set(collectionKey, internals);\n } else {\n /**\n * Ensure that the storage was not already\n * created with a different schema.\n * This is very important because if this check\n * does not exist here, we have hard-to-debug problems\n * downstream.\n */\n if (\n params.devMode &&\n !deepEqual(internals.schema, params.schema)\n ) {\n throw new Error('storage was already created with a different schema');\n }\n internals.refCount = internals.refCount + 1;\n }\n\n const instance = new RxStorageInstanceMemory(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAIA,IAAAC,YAAA,GAAAD,OAAA;AAIA,IAAAE,eAAA,GAAAF,OAAA;AACA,IAAAG,gBAAA,GAAAH,OAAA;AAqBA,IAAAI,MAAA,GAAAJ,OAAA;AASA,IAAAK,mBAAA,GAAAL,OAAA;AAMA,IAAAM,aAAA,GAAAN,OAAA;AAQA,IAAAO,cAAA,GAAAP,OAAA;AAUA,IAAAQ,cAAA,GAAAR,OAAA;AAEA;AACA;AACA;AACA;AACO,IAAMS,qBAAqB,GAAAC,OAAA,CAAAD,qBAAA,GAAG,IAAIE,GAAG,CAA+B,CAAC;AAAC,IAEhEC,uBAAuB,GAAAF,OAAA,CAAAE,uBAAA;EAUhC,SAAAA,wBACoBC,OAAwB,EACxBC,YAAoB,EACpBC,cAAsB,EACtBC,MAAyD,EACzDC,SAA4C,EAC5CC,OAAyD,EACzDC,QAAiC,EACnD;IAAA,KAVKC,MAAM,GAAG,KAAK;IAAA,KAGDP,OAAwB,GAAxBA,OAAwB;IAAA,KACxBC,YAAoB,GAApBA,YAAoB;IAAA,KACpBC,cAAsB,GAAtBA,cAAsB;IAAA,KACtBC,MAAyD,GAAzDA,MAAyD;IAAA,KACzDC,SAA4C,GAA5CA,SAA4C;IAAA,KAC5CC,OAAyD,GAAzDA,OAAyD;IAAA,KACzDC,QAAiC,GAAjCA,QAAiC;IAEjDV,qBAAqB,CAACY,GAAG,CAAC,IAAI,CAAC;IAC/B,IAAI,CAACC,WAAW,G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S,CAACgJ,QAAQ,GAAG,CAAC;EAC/C;EAEA,IAAMc,QAAQ,GAAG,IAAInK,uBAAuB,CACxCC,OAAO,EACP0J,MAAM,CAACzJ,YAAY,EACnByJ,MAAM,CAACxJ,cAAc,EACrBwJ,MAAM,CAACvJ,MAAM,EACbC,SAAS,EACTsJ,MAAM,CAACrJ,OAAO,EACdC,QACJ,CAAC;EACD,OAAOiD,OAAO,CAACC,OAAO,CAAC0G,QAAQ,CAAC;AACpC"} \ No newline at end of file diff --git a/dist/cjs/plugins/storage-remote-websocket/index.js b/dist/cjs/plugins/storage-remote-websocket/index.js index 8845d490915..592889b2c44 100644 --- a/dist/cjs/plugins/storage-remote-websocket/index.js +++ b/dist/cjs/plugins/storage-remote-websocket/index.js @@ -76,7 +76,7 @@ function getRxStorageRemoteWebsocket(options) { mode: options.mode, async messageChannelCreator() { var messages$ = new _rxjs.Subject(); - var websocketClient = await (0, _index2.createWebSocketClient)(options.url); + var websocketClient = await (0, _index2.createWebSocketClient)(options); websocketClient.message$.subscribe(msg => messages$.next(msg)); return { messages$, diff --git a/dist/cjs/plugins/storage-remote-websocket/index.js.map b/dist/cjs/plugins/storage-remote-websocket/index.js.map index 4fe49510c88..2a42832bad6 100644 --- a/dist/cjs/plugins/storage-remote-websocket/index.js.map +++ b/dist/cjs/plugins/storage-remote-websocket/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_rxjs","require","_index","_index2","_remote","_rxStorageRemote","_storageRemoteHelpers","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","startRxStorageRemoteWebsocketServer","options","serverState","startSocketServer","websocketByConnectionId","Map","messages$","Subject","exposeSettings","asObservable","storage","database","customRequestHandler","send","msg","ws","getFromMapOrThrow","connectionId","JSON","stringify","exposeState","exposeRxStorageRemote","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","createErrorAnswer","Error","set","next","getRxStorageRemoteWebsocket","identifier","url","join","getRxStorageRemote","mode","messageChannelCreator","websocketClient","createWebSocketClient","message$","socket","close","PROMISE_RESOLVE_VOID"],"sources":["../../../../src/plugins/storage-remote-websocket/index.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport {\n PROMISE_RESOLVE_VOID,\n getFromMapOrThrow\n} from '../../plugins/utils/index.ts';\nimport {\n createWebSocketClient,\n startSocketServer\n} from '../replication-websocket/index.ts';\nimport { exposeRxStorageRemote } from '../storage-remote/remote.ts';\nimport { getRxStorageRemote } from '../storage-remote/rx-storage-remote.ts';\nimport { createErrorAnswer } from '../storage-remote/storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport type {\n RxStorageRemoteWebsocketClient,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './types.ts';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage as any,\n database: options.database as any,\n customRequestHandler: options.customRequestHandler,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n }\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (\n message.method !== 'create' &&\n message.method !== 'custom'\n ) {\n ws.send(\n JSON.stringify(\n createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))\n )\n );\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\nexport function getRxStorageRemoteWebsocket(\n options: RxStorageRemoteWebsocketClientOptions\n): RxStorageRemoteWebsocketClient {\n const identifier = [\n options.url,\n 'rx-remote-storage-websocket'\n ].join('');\n const storage = getRxStorageRemote({\n identifier,\n mode: options.mode,\n async messageChannelCreator() {\n const messages$ = new Subject();\n const websocketClient = await createWebSocketClient(options.url);\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n return {\n messages$,\n send(msg) {\n return websocketClient.socket.send(JSON.stringify(msg));\n },\n close() {\n websocketClient.socket.close();\n return PROMISE_RESOLVE_VOID;\n }\n };\n\n }\n });\n return storage;\n}\n\n\nexport * from './types.ts';\n\n"],"mappings":";;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAIA,IAAAC,MAAA,GAAAD,OAAA;AAIA,IAAAE,OAAA,GAAAF,OAAA;AAIA,IAAAG,OAAA,GAAAH,OAAA;AACA,IAAAI,gBAAA,GAAAJ,OAAA;AACA,IAAAK,qBAAA,GAAAL,OAAA;AAkGA,IAAAM,MAAA,GAAAN,OAAA;AAAAO,MAAA,CAAAC,IAAA,CAAAF,MAAA,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,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;A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,OAAOxC,OAAO;AAClB"} \ No newline at end of file +{"version":3,"file":"index.js","names":["_rxjs","require","_index","_index2","_remote","_rxStorageRemote","_storageRemoteHelpers","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","startRxStorageRemoteWebsocketServer","options","serverState","startSocketServer","websocketByConnectionId","Map","messages$","Subject","exposeSettings","asObservable","storage","database","customRequestHandler","send","msg","ws","getFromMapOrThrow","connectionId","JSON","stringify","exposeState","exposeRxStorageRemote","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","createErrorAnswer","Error","set","next","getRxStorageRemoteWebsocket","identifier","url","join","getRxStorageRemote","mode","messageChannelCreator","websocketClient","createWebSocketClient","message$","socket","close","PROMISE_RESOLVE_VOID"],"sources":["../../../../src/plugins/storage-remote-websocket/index.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport {\n PROMISE_RESOLVE_VOID,\n getFromMapOrThrow\n} from '../../plugins/utils/index.ts';\nimport {\n createWebSocketClient,\n startSocketServer\n} from '../replication-websocket/index.ts';\nimport { exposeRxStorageRemote } from '../storage-remote/remote.ts';\nimport { getRxStorageRemote } from '../storage-remote/rx-storage-remote.ts';\nimport { createErrorAnswer } from '../storage-remote/storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport type {\n RxStorageRemoteWebsocketClient,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './types.ts';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage as any,\n database: options.database as any,\n customRequestHandler: options.customRequestHandler,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n }\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (\n message.method !== 'create' &&\n message.method !== 'custom'\n ) {\n ws.send(\n JSON.stringify(\n createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))\n )\n );\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\nexport function getRxStorageRemoteWebsocket(\n options: RxStorageRemoteWebsocketClientOptions\n): RxStorageRemoteWebsocketClient {\n const identifier = [\n options.url,\n 'rx-remote-storage-websocket'\n ].join('');\n const storage = getRxStorageRemote({\n identifier,\n mode: options.mode,\n async messageChannelCreator() {\n const messages$ = new Subject();\n const websocketClient = await createWebSocketClient(options as any);\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n return {\n messages$,\n send(msg) {\n return websocketClient.socket.send(JSON.stringify(msg));\n },\n close() {\n websocketClient.socket.close();\n return PROMISE_RESOLVE_VOID;\n }\n };\n\n }\n });\n return storage;\n}\n\n\nexport * from './types.ts';\n\n"],"mappings":";;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAIA,IAAAC,MAAA,GAAAD,OAAA;AAIA,IAAAE,OAAA,GAAAF,OAAA;AAIA,IAAAG,OAAA,GAAAH,OAAA;AACA,IAAAI,gBAAA,GAAAJ,OAAA;AACA,IAAAK,qBAAA,GAAAL,OAAA;AAkGA,IAAAM,MAAA,GAAAN,OA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AAe,CAACE,QAAQ,CAACxB,SAAS,CAACT,GAAG,IAAIR,SAAS,CAAC+B,IAAI,CAACvB,GAAG,CAAC,CAAC;MAC9D,OAAO;QACHR,SAAS;QACTO,IAAIA,CAACC,GAAG,EAAE;UACN,OAAO+B,eAAe,CAACG,MAAM,CAACnC,IAAI,CAACK,IAAI,CAACC,SAAS,CAACL,GAAG,CAAC,CAAC;QAC3D,CAAC;QACDmC,KAAKA,CAAA,EAAG;UACJJ,eAAe,CAACG,MAAM,CAACC,KAAK,CAAC,CAAC;UAC9B,OAAOC,2BAAoB;QAC/B;MACJ,CAAC;IAEL;EACJ,CAAC,CAAC;EACF,OAAOxC,OAAO;AAClB"} \ No newline at end of file diff --git a/dist/cjs/plugins/utils/utils-other.js b/dist/cjs/plugins/utils/utils-other.js index 4f2ac297ba0..34977d5d50c 100644 --- a/dist/cjs/plugins/utils/utils-other.js +++ b/dist/cjs/plugins/utils/utils-other.js @@ -10,9 +10,12 @@ exports.runXTimes = runXTimes; function runXTimes(xTimes, fn) { new Array(xTimes).fill(0).forEach((_v, idx) => fn(idx)); } -function ensureNotFalsy(obj) { +function ensureNotFalsy(obj, message) { if (!obj) { - throw new Error('ensureNotFalsy() is falsy'); + if (!message) { + message = ''; + } + throw new Error('ensureNotFalsy() is falsy: ' + message); } return obj; } diff --git a/dist/cjs/plugins/utils/utils-other.js.map b/dist/cjs/plugins/utils/utils-other.js.map index db1e94740f8..30bf54fa0de 100644 --- a/dist/cjs/plugins/utils/utils-other.js.map +++ b/dist/cjs/plugins/utils/utils-other.js.map @@ -1 +1 @@ -{"version":3,"file":"utils-other.js","names":["runXTimes","xTimes","fn","Array","fill","forEach","_v","idx","ensureNotFalsy","obj","Error","ensureInteger","Number","isInteger","RXJS_SHARE_REPLAY_DEFAULTS","exports","bufferSize","refCount"],"sources":["../../../../src/plugins/utils/utils-other.ts"],"sourcesContent":["export function runXTimes(xTimes: number, fn: (idx: number) => void) {\n new Array(xTimes).fill(0).forEach((_v, idx) => fn(idx));\n}\n\nexport function ensureNotFalsy(obj: T | false | undefined | null): T {\n if (!obj) {\n throw new Error('ensureNotFalsy() is falsy');\n }\n return obj;\n}\n\nexport function ensureInteger(obj: unknown): number {\n if (!Number.isInteger(obj)) {\n throw new Error('ensureInteger() is falsy');\n }\n return obj as number;\n}\n\n/**\n * Using shareReplay() without settings will not unsubscribe\n * if there are no more subscribers.\n * So we use these defaults.\n * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95\n */\nexport const RXJS_SHARE_REPLAY_DEFAULTS = {\n bufferSize: 1,\n refCount: true\n};\n"],"mappings":";;;;;;;;;AAAO,SAASA,SAASA,CAACC,MAAc,EAAEC,EAAyB,EAAE;EACjE,IAAIC,KAAK,CAACF,MAAM,CAAC,CAACG,IAAI,CAAC,CAAC,CAAC,CAACC,OAAO,CAAC,CAACC,EAAE,EAAEC,GAAG,KAAKL,EAAE,CAACK,GAAG,CAAC,CAAC;AAC3D;AAEO,SAASC,cAAcA,CAAIC,GAAiC,EAAK;EACpE,IAAI,CAACA,GAAG,EAAE;IACN,MAAM,IAAIC,KAAK,CAAC,2BAA2B,CAAC;EAChD;EACA,OAAOD,GAAG;AACd;AAEO,SAASE,aAAaA,CAACF,GAAY,EAAU;EAChD,IAAI,CAACG,MAAM,CAACC,SAAS,CAACJ,GAAG,CAAC,EAAE;IACxB,MAAM,IAAIC,KAAK,CAAC,0BAA0B,CAAC;EAC/C;EACA,OAAOD,GAAG;AACd;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,IAAMK,0BAA0B,GAAAC,OAAA,CAAAD,0BAAA,GAAG;EACtCE,UAAU,EAAE,CAAC;EACbC,QAAQ,EAAE;AACd,CAAC"} \ No newline at end of file +{"version":3,"file":"utils-other.js","names":["runXTimes","xTimes","fn","Array","fill","forEach","_v","idx","ensureNotFalsy","obj","message","Error","ensureInteger","Number","isInteger","RXJS_SHARE_REPLAY_DEFAULTS","exports","bufferSize","refCount"],"sources":["../../../../src/plugins/utils/utils-other.ts"],"sourcesContent":["export function runXTimes(xTimes: number, fn: (idx: number) => void) {\n new Array(xTimes).fill(0).forEach((_v, idx) => fn(idx));\n}\n\nexport function ensureNotFalsy(obj: T | false | undefined | null, message?: string): T {\n if (!obj) {\n if (!message) {\n message = '';\n }\n throw new Error('ensureNotFalsy() is falsy: ' + message);\n }\n return obj;\n}\n\nexport function ensureInteger(obj: unknown): number {\n if (!Number.isInteger(obj)) {\n throw new Error('ensureInteger() is falsy');\n }\n return obj as number;\n}\n\n/**\n * Using shareReplay() without settings will not unsubscribe\n * if there are no more subscribers.\n * So we use these defaults.\n * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95\n */\nexport const RXJS_SHARE_REPLAY_DEFAULTS = {\n bufferSize: 1,\n refCount: true\n};\n"],"mappings":";;;;;;;;;AAAO,SAASA,SAASA,CAACC,MAAc,EAAEC,EAAyB,EAAE;EACjE,IAAIC,KAAK,CAACF,MAAM,CAAC,CAACG,IAAI,CAAC,CAAC,CAAC,CAACC,OAAO,CAAC,CAACC,EAAE,EAAEC,GAAG,KAAKL,EAAE,CAACK,GAAG,CAAC,CAAC;AAC3D;AAEO,SAASC,cAAcA,CAAIC,GAAiC,EAAEC,OAAgB,EAAK;EACtF,IAAI,CAACD,GAAG,EAAE;IACN,IAAI,CAACC,OAAO,EAAE;MACVA,OAAO,GAAG,EAAE;IAChB;IACA,MAAM,IAAIC,KAAK,CAAC,6BAA6B,GAAGD,OAAO,CAAC;EAC5D;EACA,OAAOD,GAAG;AACd;AAEO,SAASG,aAAaA,CAACH,GAAY,EAAU;EAChD,IAAI,CAACI,MAAM,CAACC,SAAS,CAACL,GAAG,CAAC,EAAE;IACxB,MAAM,IAAIE,KAAK,CAAC,0BAA0B,CAAC;EAC/C;EACA,OAAOF,GAAG;AACd;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,IAAMM,0BAA0B,GAAAC,OAAA,CAAAD,0BAAA,GAAG;EACtCE,UAAU,EAAE,CAAC;EACbC,QAAQ,EAAE;AACd,CAAC"} \ No newline at end of file diff --git a/dist/cjs/plugins/utils/utils-rxdb-version.js b/dist/cjs/plugins/utils/utils-rxdb-version.js index 5f04785223e..f7a59f21cb6 100644 --- a/dist/cjs/plugins/utils/utils-rxdb-version.js +++ b/dist/cjs/plugins/utils/utils-rxdb-version.js @@ -7,5 +7,5 @@ exports.RXDB_VERSION = void 0; /** * This file is replaced in the 'npm run build:version' script. */ -var RXDB_VERSION = exports.RXDB_VERSION = '15.3.0'; +var RXDB_VERSION = exports.RXDB_VERSION = '15.4.0'; //# sourceMappingURL=utils-rxdb-version.js.map \ No newline at end of file diff --git a/dist/cjs/plugins/utils/utils-rxdb-version.js.map b/dist/cjs/plugins/utils/utils-rxdb-version.js.map index 4a15ade25c9..981acc0c7e2 100644 --- a/dist/cjs/plugins/utils/utils-rxdb-version.js.map +++ b/dist/cjs/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 = '15.3.0';\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACO,IAAMA,YAAY,GAAAC,OAAA,CAAAD,YAAA,GAAG,QAAQ"} \ 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 = '15.4.0';\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACO,IAAMA,YAAY,GAAAC,OAAA,CAAAD,YAAA,GAAG,QAAQ"} \ No newline at end of file diff --git a/dist/cjs/replication-protocol/index.js.map b/dist/cjs/replication-protocol/index.js.map index 0db67322f1c..5afe50adccb 100644 --- a/dist/cjs/replication-protocol/index.js.map +++ b/dist/cjs/replication-protocol/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_rxjs","require","_rxSchemaHelper","_index","_checkpoint","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_downstream","_helper","_upstream","_index2","_rxStorageHelper","_metaInstance","_conflicts","replicateRxStorageInstance","input","flatClone","forkInstance","getUnderlyingPersistentStorage","metaInstance","checkpointKeyPromise","getCheckpointKey","state","primaryPath","getPrimaryFieldOfPrimaryKey","schema","primaryKey","hasAttachments","attachments","checkpointKey","downstreamBulkWriteFlag","then","events","canceled","BehaviorSubject","active","down","up","processed","Subject","resolvedConflicts","error","stats","addNewTask","downstreamProcessChanges","downstreamResyncOnce","masterChangeStreamEmit","persistFromMaster","forkChangeStreamEmit","persistToMaster","persistToMasterConflictWrites","persistToMasterHadConflicts","processTasks","upstreamInitialSync","firstSyncDone","streamQueue","PROMISE_RESOLVE_VOID","checkpointQueue","lastCheckpointDoc","startReplicationDownstream","startReplicationUpstream","awaitRxStorageReplicationFirstInSync","firstValueFrom","combineLatest","pipe","filter","v","awaitRxStorageReplicationInSync","replicationState","Promise","all","awaitRxStorageReplicationIdle","rxStorageInstanceToReplicationHandler","instance","conflictHandler","databaseInstanceToken","keepMeta","replicationHandler","masterChangeStream$","changeStream","mergeMap","eventBulk","ret","checkpoint","documents","map","event","docData","writeDocToDocState","documentData","fillWriteDataForAttachmentsChange","clone","undefined","masterChangesSince","batchSize","getChangedDocumentsSince","result","length","plainDocumentData","masterWrite","rows","rowById","row","docId","newDocumentState","ids","masterDocsStateList","findDocumentsById","masterDocsState","Map","doc","set","conflicts","writeRows","entries","id","masterState","push","document","docStateToWriteDoc","assumedMasterState","realMasterState","ensureNotFalsy","isEqual","previous","bulkWrite","err","status","Error","documentInDb","cancelRxStorageReplication","next","complete"],"sources":["../../../src/replication-protocol/index.ts"],"sourcesContent":["/**\n * These files contain the replication protocol.\n * It can be used to replicated RxStorageInstances or RxCollections\n * or even to do a client(s)-server replication.\n */\n\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n firstValueFrom,\n mergeMap,\n Subject\n} from 'rxjs';\nimport {\n getPrimaryFieldOfPrimaryKey\n} from '../rx-schema-helper.ts';\nimport type {\n BulkWriteRow,\n ById,\n DocumentsWithCheckpoint,\n RxConflictHandler,\n RxDocumentData,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n WithDeleted\n} from '../types/index.d.ts';\nimport {\n clone,\n ensureNotFalsy,\n flatClone,\n PROMISE_RESOLVE_VOID\n} from '../plugins/utils/index.ts';\nimport {\n getCheckpointKey\n} from './checkpoint.ts';\nimport { startReplicationDownstream } from './downstream.ts';\nimport { docStateToWriteDoc, getUnderlyingPersistentStorage, writeDocToDocState } from './helper.ts';\nimport { startReplicationUpstream } from './upstream.ts';\nimport { fillWriteDataForAttachmentsChange } from '../plugins/attachments/index.ts';\nimport { getChangedDocumentsSince } from '../rx-storage-helper.ts';\n\n\nexport * from './checkpoint.ts';\nexport * from './downstream.ts';\nexport * from './upstream.ts';\nexport * from './meta-instance.ts';\nexport * from './conflicts.ts';\nexport * from './helper.ts';\n\n\nexport function replicateRxStorageInstance(\n input: RxStorageInstanceReplicationInput\n): RxStorageInstanceReplicationState {\n input = flatClone(input);\n input.forkInstance = getUnderlyingPersistentStorage(input.forkInstance);\n input.metaInstance = getUnderlyingPersistentStorage(input.metaInstance);\n const checkpointKeyPromise = getCheckpointKey(input);\n const state: RxStorageInstanceReplicationState = {\n primaryPath: getPrimaryFieldOfPrimaryKey(input.forkInstance.schema.primaryKey),\n hasAttachments: !!input.forkInstance.schema.attachments,\n input,\n checkpointKey: checkpointKeyPromise,\n downstreamBulkWriteFlag: checkpointKeyPromise.then(checkpointKey => 'replication-downstream-' + checkpointKey),\n events: {\n canceled: new BehaviorSubject(false),\n active: {\n down: new BehaviorSubject(true),\n up: new BehaviorSubject(true)\n },\n processed: {\n down: new Subject(),\n up: new Subject()\n },\n resolvedConflicts: new Subject(),\n error: new Subject()\n },\n stats: {\n down: {\n addNewTask: 0,\n downstreamProcessChanges: 0,\n downstreamResyncOnce: 0,\n masterChangeStreamEmit: 0,\n persistFromMaster: 0\n },\n up: {\n forkChangeStreamEmit: 0,\n persistToMaster: 0,\n persistToMasterConflictWrites: 0,\n persistToMasterHadConflicts: 0,\n processTasks: 0,\n upstreamInitialSync: 0\n }\n },\n firstSyncDone: {\n down: new BehaviorSubject(false),\n up: new BehaviorSubject(false)\n },\n streamQueue: {\n down: PROMISE_RESOLVE_VOID,\n up: PROMISE_RESOLVE_VOID\n },\n checkpointQueue: PROMISE_RESOLVE_VOID,\n lastCheckpointDoc: {}\n };\n\n startReplicationDownstream(state);\n startReplicationUpstream(state);\n return state;\n}\n\nexport function awaitRxStorageReplicationFirstInSync(\n state: RxStorageInstanceReplicationState\n): Promise {\n return firstValueFrom(\n combineLatest([\n state.firstSyncDone.down.pipe(\n filter(v => !!v)\n ),\n state.firstSyncDone.up.pipe(\n filter(v => !!v)\n )\n ])\n ).then(() => { });\n}\n\nexport function awaitRxStorageReplicationInSync(\n replicationState: RxStorageInstanceReplicationState\n) {\n return Promise.all([\n replicationState.streamQueue.up,\n replicationState.streamQueue.down,\n replicationState.checkpointQueue\n ]);\n}\n\n\nexport async function awaitRxStorageReplicationIdle(\n state: RxStorageInstanceReplicationState\n) {\n await awaitRxStorageReplicationFirstInSync(state);\n while (true) {\n const { down, up } = state.streamQueue;\n await Promise.all([\n up,\n down\n ]);\n /**\n * If the Promises have not been reassigned\n * after awaiting them, we know that the replication\n * is in idle state at this point in time.\n */\n if (\n down === state.streamQueue.down &&\n up === state.streamQueue.up\n ) {\n return;\n }\n }\n}\n\n\nexport function rxStorageInstanceToReplicationHandler(\n instance: RxStorageInstance,\n conflictHandler: RxConflictHandler,\n databaseInstanceToken: string,\n /**\n * If set to true,\n * the _meta.lwt from the pushed documents is kept.\n * (Used in the migration to ensure checkpoints are still valid)\n */\n keepMeta: boolean = false\n): RxReplicationHandler {\n instance = getUnderlyingPersistentStorage(instance);\n\n const hasAttachments = !!instance.schema.attachments;\n const primaryPath = getPrimaryFieldOfPrimaryKey(instance.schema.primaryKey);\n const replicationHandler: RxReplicationHandler = {\n masterChangeStream$: instance.changeStream().pipe(\n mergeMap(async (eventBulk) => {\n const ret: DocumentsWithCheckpoint = {\n checkpoint: eventBulk.checkpoint,\n documents: await Promise.all(\n eventBulk.events.map(async (event) => {\n let docData = writeDocToDocState(event.documentData, hasAttachments, keepMeta);\n if (hasAttachments) {\n docData = await fillWriteDataForAttachmentsChange(\n primaryPath,\n instance,\n clone(docData),\n /**\n * Notice that the master never knows\n * the client state of the document.\n * Therefore we always send all attachments data.\n */\n undefined\n );\n }\n\n return docData;\n })\n )\n };\n return ret;\n })\n ),\n masterChangesSince(\n checkpoint,\n batchSize\n ) {\n return getChangedDocumentsSince(\n instance,\n batchSize,\n checkpoint\n ).then(async (result) => {\n return {\n checkpoint: result.documents.length > 0 ? result.checkpoint : checkpoint,\n documents: await Promise.all(\n result.documents.map(async (plainDocumentData) => {\n let docData = writeDocToDocState(plainDocumentData, hasAttachments, keepMeta);\n if (hasAttachments) {\n docData = await fillWriteDataForAttachmentsChange(\n primaryPath,\n instance,\n clone(docData),\n /**\n * Notice the the master never knows\n * the client state of the document.\n * Therefore we always send all attachments data.\n */\n undefined\n );\n }\n return docData;\n })\n )\n };\n });\n },\n async masterWrite(\n rows\n ) {\n const rowById: ById> = {};\n rows.forEach(row => {\n const docId: string = (row.newDocumentState as any)[primaryPath];\n rowById[docId] = row;\n });\n const ids = Object.keys(rowById);\n\n const masterDocsStateList = await instance.findDocumentsById(\n ids,\n true\n );\n const masterDocsState = new Map>();\n masterDocsStateList.forEach(doc => masterDocsState.set((doc as any)[primaryPath], doc));\n const conflicts: WithDeleted[] = [];\n const writeRows: BulkWriteRow[] = [];\n await Promise.all(\n Object.entries(rowById)\n .map(async ([id, row]) => {\n const masterState = masterDocsState.get(id);\n if (!masterState) {\n writeRows.push({\n document: docStateToWriteDoc(databaseInstanceToken, hasAttachments, keepMeta, row.newDocumentState)\n });\n } else if (\n masterState &&\n !row.assumedMasterState\n ) {\n conflicts.push(writeDocToDocState(masterState, hasAttachments, keepMeta));\n } else if (\n (await conflictHandler({\n realMasterState: writeDocToDocState(masterState, hasAttachments, keepMeta),\n newDocumentState: ensureNotFalsy(row.assumedMasterState)\n }, 'rxStorageInstanceToReplicationHandler-masterWrite')).isEqual === true\n ) {\n writeRows.push({\n previous: masterState,\n document: docStateToWriteDoc(databaseInstanceToken, hasAttachments, keepMeta, row.newDocumentState, masterState)\n });\n } else {\n conflicts.push(writeDocToDocState(masterState, hasAttachments, keepMeta));\n }\n })\n );\n\n if (writeRows.length > 0) {\n const result = await instance.bulkWrite(\n writeRows,\n 'replication-master-write'\n );\n result.error.forEach(err => {\n if (err.status !== 409) {\n throw new Error('non conflict error');\n } else {\n conflicts.push(\n writeDocToDocState(ensureNotFalsy(err.documentInDb), hasAttachments, keepMeta)\n );\n }\n });\n }\n return conflicts;\n }\n };\n\n return replicationHandler;\n}\n\n\nexport async function cancelRxStorageReplication(\n replicationState: RxStorageInstanceReplicationState\n) {\n replicationState.events.canceled.next(true);\n replicationState.events.active.up.complete();\n replicationState.events.active.down.complete();\n replicationState.events.processed.up.complete();\n replicationState.events.processed.down.complete();\n replicationState.events.resolvedConflicts.complete();\n replicationState.events.canceled.complete();\n await replicationState.checkpointQueue;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAOA,IAAAA,KAAA,GAAAC,OAAA;AAQA,IAAAC,eAAA,GAAAD,OAAA;AAgBA,IAAAE,MAAA,GAAAF,OAAA;AAMA,IAAAG,WAAA,GAAAH,OAAA;AAUAI,MAAA,CAAAC,IAAA,CAAAF,WAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAA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AAM,CAACC,IAAI,CAACgG,QAAQ,CAAC,CAAC;EAC9ChE,gBAAgB,CAACpC,MAAM,CAACM,SAAS,CAACD,EAAE,CAAC+F,QAAQ,CAAC,CAAC;EAC/ChE,gBAAgB,CAACpC,MAAM,CAACM,SAAS,CAACF,IAAI,CAACgG,QAAQ,CAAC,CAAC;EACjDhE,gBAAgB,CAACpC,MAAM,CAACQ,iBAAiB,CAAC4F,QAAQ,CAAC,CAAC;EACpDhE,gBAAgB,CAACpC,MAAM,CAACC,QAAQ,CAACmG,QAAQ,CAAC,CAAC;EAC3C,MAAMhE,gBAAgB,CAACX,eAAe;AAC1C"} \ No newline at end of file +{"version":3,"file":"index.js","names":["_rxjs","require","_rxSchemaHelper","_index","_checkpoint","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_downstream","_helper","_upstream","_index2","_rxStorageHelper","_metaInstance","_conflicts","replicateRxStorageInstance","input","flatClone","forkInstance","getUnderlyingPersistentStorage","metaInstance","checkpointKeyPromise","getCheckpointKey","state","primaryPath","getPrimaryFieldOfPrimaryKey","schema","primaryKey","hasAttachments","attachments","checkpointKey","downstreamBulkWriteFlag","then","events","canceled","BehaviorSubject","active","down","up","processed","Subject","resolvedConflicts","error","stats","addNewTask","downstreamProcessChanges","downstreamResyncOnce","masterChangeStreamEmit","persistFromMaster","forkChangeStreamEmit","persistToMaster","persistToMasterConflictWrites","persistToMasterHadConflicts","processTasks","upstreamInitialSync","firstSyncDone","streamQueue","PROMISE_RESOLVE_VOID","checkpointQueue","lastCheckpointDoc","startReplicationDownstream","startReplicationUpstream","awaitRxStorageReplicationFirstInSync","firstValueFrom","combineLatest","pipe","filter","v","awaitRxStorageReplicationInSync","replicationState","Promise","all","awaitRxStorageReplicationIdle","rxStorageInstanceToReplicationHandler","instance","conflictHandler","databaseInstanceToken","keepMeta","replicationHandler","masterChangeStream$","changeStream","mergeMap","eventBulk","ret","checkpoint","documents","map","event","docData","writeDocToDocState","documentData","fillWriteDataForAttachmentsChange","clone","undefined","masterChangesSince","batchSize","getChangedDocumentsSince","result","length","plainDocumentData","masterWrite","rows","rowById","row","docId","newDocumentState","ids","masterDocsStateList","findDocumentsById","masterDocsState","Map","doc","set","conflicts","writeRows","entries","id","masterState","push","document","docStateToWriteDoc","assumedMasterState","realMasterState","ensureNotFalsy","isEqual","previous","bulkWrite","err","status","Error","documentInDb","cancelRxStorageReplication","next","complete"],"sources":["../../../src/replication-protocol/index.ts"],"sourcesContent":["/**\n * These files contain the replication protocol.\n * It can be used to replicated RxStorageInstances or RxCollections\n * or even to do a client(s)-server replication.\n */\n\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n firstValueFrom,\n mergeMap,\n Subject\n} from 'rxjs';\nimport {\n getPrimaryFieldOfPrimaryKey\n} from '../rx-schema-helper.ts';\nimport type {\n BulkWriteRow,\n ById,\n DocumentsWithCheckpoint,\n RxConflictHandler,\n RxDocumentData,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n WithDeleted\n} from '../types/index.d.ts';\nimport {\n clone,\n ensureNotFalsy,\n flatClone,\n PROMISE_RESOLVE_VOID\n} from '../plugins/utils/index.ts';\nimport {\n getCheckpointKey\n} from './checkpoint.ts';\nimport { startReplicationDownstream } from './downstream.ts';\nimport { docStateToWriteDoc, getUnderlyingPersistentStorage, writeDocToDocState } from './helper.ts';\nimport { startReplicationUpstream } from './upstream.ts';\nimport { fillWriteDataForAttachmentsChange } from '../plugins/attachments/index.ts';\nimport { getChangedDocumentsSince } from '../rx-storage-helper.ts';\n\n\nexport * from './checkpoint.ts';\nexport * from './downstream.ts';\nexport * from './upstream.ts';\nexport * from './meta-instance.ts';\nexport * from './conflicts.ts';\nexport * from './helper.ts';\n\n\nexport function replicateRxStorageInstance(\n input: RxStorageInstanceReplicationInput\n): RxStorageInstanceReplicationState {\n input = flatClone(input);\n input.forkInstance = getUnderlyingPersistentStorage(input.forkInstance);\n input.metaInstance = getUnderlyingPersistentStorage(input.metaInstance);\n const checkpointKeyPromise = getCheckpointKey(input);\n const state: RxStorageInstanceReplicationState = {\n primaryPath: getPrimaryFieldOfPrimaryKey(input.forkInstance.schema.primaryKey),\n hasAttachments: !!input.forkInstance.schema.attachments,\n input,\n checkpointKey: checkpointKeyPromise,\n downstreamBulkWriteFlag: checkpointKeyPromise.then(checkpointKey => 'replication-downstream-' + checkpointKey),\n events: {\n canceled: new BehaviorSubject(false),\n active: {\n down: new BehaviorSubject(true),\n up: new BehaviorSubject(true)\n },\n processed: {\n down: new Subject(),\n up: new Subject()\n },\n resolvedConflicts: new Subject(),\n error: new Subject()\n },\n stats: {\n down: {\n addNewTask: 0,\n downstreamProcessChanges: 0,\n downstreamResyncOnce: 0,\n masterChangeStreamEmit: 0,\n persistFromMaster: 0\n },\n up: {\n forkChangeStreamEmit: 0,\n persistToMaster: 0,\n persistToMasterConflictWrites: 0,\n persistToMasterHadConflicts: 0,\n processTasks: 0,\n upstreamInitialSync: 0\n }\n },\n firstSyncDone: {\n down: new BehaviorSubject(false),\n up: new BehaviorSubject(false)\n },\n streamQueue: {\n down: PROMISE_RESOLVE_VOID,\n up: PROMISE_RESOLVE_VOID\n },\n checkpointQueue: PROMISE_RESOLVE_VOID,\n lastCheckpointDoc: {}\n };\n\n startReplicationDownstream(state);\n startReplicationUpstream(state);\n return state;\n}\n\nexport function awaitRxStorageReplicationFirstInSync(\n state: RxStorageInstanceReplicationState\n): Promise {\n return firstValueFrom(\n combineLatest([\n state.firstSyncDone.down.pipe(\n filter(v => !!v)\n ),\n state.firstSyncDone.up.pipe(\n filter(v => !!v)\n )\n ])\n ).then(() => { });\n}\n\nexport function awaitRxStorageReplicationInSync(\n replicationState: RxStorageInstanceReplicationState\n) {\n return Promise.all([\n replicationState.streamQueue.up,\n replicationState.streamQueue.down,\n replicationState.checkpointQueue\n ]);\n}\n\n\nexport async function awaitRxStorageReplicationIdle(\n state: RxStorageInstanceReplicationState\n) {\n await awaitRxStorageReplicationFirstInSync(state);\n while (true) {\n const { down, up } = state.streamQueue;\n await Promise.all([\n up,\n down\n ]);\n /**\n * If the Promises have not been reassigned\n * after awaiting them, we know that the replication\n * is in idle state at this point in time.\n */\n if (\n down === state.streamQueue.down &&\n up === state.streamQueue.up\n ) {\n return;\n }\n }\n}\n\n\nexport function rxStorageInstanceToReplicationHandler(\n instance: RxStorageInstance,\n conflictHandler: RxConflictHandler,\n databaseInstanceToken: string,\n /**\n * If set to true,\n * the _meta.lwt from the pushed documents is kept.\n * (Used in the migration to ensure checkpoints are still valid)\n */\n keepMeta: boolean = false\n): RxReplicationHandler {\n instance = getUnderlyingPersistentStorage(instance);\n\n const hasAttachments = !!instance.schema.attachments;\n const primaryPath = getPrimaryFieldOfPrimaryKey(instance.schema.primaryKey);\n const replicationHandler: RxReplicationHandler = {\n masterChangeStream$: instance.changeStream().pipe(\n mergeMap(async (eventBulk) => {\n const ret: DocumentsWithCheckpoint = {\n checkpoint: eventBulk.checkpoint,\n documents: await Promise.all(\n eventBulk.events.map(async (event) => {\n let docData = writeDocToDocState(event.documentData, hasAttachments, keepMeta);\n if (hasAttachments) {\n docData = await fillWriteDataForAttachmentsChange(\n primaryPath,\n instance,\n clone(docData),\n /**\n * Notice that the master never knows\n * the client state of the document.\n * Therefore we always send all attachments data.\n */\n undefined\n );\n }\n\n return docData;\n })\n )\n };\n return ret;\n })\n ),\n masterChangesSince(\n checkpoint,\n batchSize\n ) {\n return getChangedDocumentsSince(\n instance,\n batchSize,\n checkpoint\n ).then(async (result) => {\n return {\n checkpoint: result.documents.length > 0 ? result.checkpoint : checkpoint,\n documents: await Promise.all(\n result.documents.map(async (plainDocumentData) => {\n let docData = writeDocToDocState(plainDocumentData, hasAttachments, keepMeta);\n if (hasAttachments) {\n docData = await fillWriteDataForAttachmentsChange(\n primaryPath,\n instance,\n clone(docData),\n /**\n * Notice the the master never knows\n * the client state of the document.\n * Therefore we always send all attachments data.\n */\n undefined\n );\n }\n return docData;\n })\n )\n };\n });\n },\n async masterWrite(\n rows\n ) {\n const rowById: ById> = {};\n rows.forEach(row => {\n const docId: string = (row.newDocumentState as any)[primaryPath];\n rowById[docId] = row;\n });\n const ids = Object.keys(rowById);\n\n const masterDocsStateList = await instance.findDocumentsById(\n ids,\n true\n );\n const masterDocsState = new Map>();\n masterDocsStateList.forEach(doc => masterDocsState.set((doc as any)[primaryPath], doc));\n const conflicts: WithDeleted[] = [];\n const writeRows: BulkWriteRow[] = [];\n await Promise.all(\n Object.entries(rowById)\n .map(async ([id, row]) => {\n const masterState = masterDocsState.get(id);\n if (!masterState) {\n writeRows.push({\n document: docStateToWriteDoc(databaseInstanceToken, hasAttachments, keepMeta, row.newDocumentState)\n });\n } else if (\n masterState &&\n !row.assumedMasterState\n ) {\n conflicts.push(writeDocToDocState(masterState, hasAttachments, keepMeta));\n } else if (\n (await conflictHandler({\n realMasterState: writeDocToDocState(masterState, hasAttachments, keepMeta),\n newDocumentState: ensureNotFalsy(row.assumedMasterState)\n }, 'rxStorageInstanceToReplicationHandler-masterWrite')).isEqual === true\n ) {\n writeRows.push({\n previous: masterState,\n document: docStateToWriteDoc(databaseInstanceToken, hasAttachments, keepMeta, row.newDocumentState, masterState)\n });\n } else {\n conflicts.push(writeDocToDocState(masterState, hasAttachments, keepMeta));\n }\n })\n );\n\n if (writeRows.length > 0) {\n const result = await instance.bulkWrite(\n writeRows,\n 'replication-master-write'\n );\n\n result.error.forEach(err => {\n if (err.status !== 409) {\n throw new Error('non conflict error');\n } else {\n conflicts.push(\n writeDocToDocState(ensureNotFalsy(err.documentInDb), hasAttachments, keepMeta)\n );\n }\n });\n }\n return conflicts;\n }\n };\n\n return replicationHandler;\n}\n\n\nexport async function cancelRxStorageReplication(\n replicationState: RxStorageInstanceReplicationState\n) {\n replicationState.events.canceled.next(true);\n replicationState.events.active.up.complete();\n replicationState.events.active.down.complete();\n replicationState.events.processed.up.complete();\n replicationState.events.processed.down.complete();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AEtG,cAAc,EAAEiD,QAAQ,CACjF,CAAC;UACL;QACJ,CAAC,CAAC;MACN;MACA,OAAOoC,SAAS;IACpB;EACJ,CAAC;EAED,OAAOnC,kBAAkB;AAC7B;AAGO,eAAeqD,0BAA0BA,CAC5C9D,gBAAwD,EAC1D;EACEA,gBAAgB,CAACpC,MAAM,CAACC,QAAQ,CAACkG,IAAI,CAAC,IAAI,CAAC;EAC3C/D,gBAAgB,CAACpC,MAAM,CAACG,MAAM,CAACE,EAAE,CAAC+F,QAAQ,CAAC,CAAC;EAC5ChE,gBAAgB,CAACpC,MAAM,CAACG,MAAM,CAACC,IAAI,CAACgG,QAAQ,CAAC,CAAC;EAC9ChE,gBAAgB,CAACpC,MAAM,CAACM,SAAS,CAACD,EAAE,CAAC+F,QAAQ,CAAC,CAAC;EAC/ChE,gBAAgB,CAACpC,MAAM,CAACM,SAAS,CAACF,IAAI,CAACgG,QAAQ,CAAC,CAAC;EACjDhE,gBAAgB,CAACpC,MAAM,CAACQ,iBAAiB,CAAC4F,QAAQ,CAAC,CAAC;EACpDhE,gBAAgB,CAACpC,MAAM,CAACC,QAAQ,CAACmG,QAAQ,CAAC,CAAC;EAC3C,MAAMhE,gBAAgB,CAACX,eAAe;AAC1C"} \ No newline at end of file diff --git a/dist/cjs/rx-collection.js b/dist/cjs/rx-collection.js index 0cc2d994fb8..2bbe1f50ca1 100644 --- a/dist/cjs/rx-collection.js +++ b/dist/cjs/rx-collection.js @@ -119,10 +119,10 @@ var RxCollectionBase = exports.RxCollectionBase = /*#__PURE__*/function () { // overwritten by migration-plugin ; _proto.migrationNeeded = function migrationNeeded() { - throw (0, _index.pluginMissing)('migration'); + throw (0, _index.pluginMissing)('migration-schema'); }; _proto.getMigrationState = function getMigrationState() { - throw (0, _index.pluginMissing)('migration'); + throw (0, _index.pluginMissing)('migration-schema'); }; _proto.startMigration = function startMigration(batchSize = 10) { return this.getMigrationState().startMigration(batchSize); diff --git a/dist/cjs/rx-collection.js.map b/dist/cjs/rx-collection.js.map index d8457322c4a..e482ccfd2b0 100644 --- a/dist/cjs/rx-collection.js.map +++ b/dist/cjs/rx-collection.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-collection.js","names":["_rxjs","require","_index","_rxCollectionHelper","_rxQuery","_rxError","_docCache","_queryCache","_changeEventBuffer","_hooks","_rxDocumentPrototypeMerge","_rxStorageHelper","_index2","_incrementalWrite","_rxDocument","_overwritable","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","exports","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","defaultCacheReplacementPolicy","statics","conflictHandler","defaultConflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","_incrementalUpsertQueues","Map","synced","hooks","_subs","createQueryCache","$","checkpoint$","onDestroy","destroyed","_applyHookFunctions","asRxCollection","_proto","prototype","prepare","getWrappedStorageInstance","jsonSchema","IncrementalWriteQueue","primaryPath","newData","oldData","beforeDocumentUpdateWrite","result","_runHooks","collectionEventBulks$","eventBulks$","pipe","filter","changeEventBulk","collectionName","mergeMap","events","map","checkpoint","createChangeEventBuffer","DocumentCache","cE","isLocal","docData","createNewRxDocument","databaseStorageToken","storageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","ev","storageChangeEventToRxChangeEvent","databaseToken","token","context","endTime","startTime","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","PROMISE_RESOLVE_VOID","cleanup","_minimumDeletedTime","pluginMissing","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","throwIfIsStorageWriteError","insertResult","ensureNotFalsy","success","docsData","length","useDocs","useDocData","fillObjectDataBeforeInsert","docs","hasHooks","Promise","all","doc","insertRows","row","document","results","bulkWrite","rxDocuments","mapDocumentsDataToCacheDocs","docsMap","forEach","set","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","flatClone","_deleted","previous","successIds","d","getFromMapOrThrow","bulkUpsert","insertData","useJsonByDocId","useJson","newRxError","slice","err","status","documentId","writeData","docDataInDb","documentInDb","getCachedRxDocument","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","_getDefaultQuery","query","createRxQuery","findOne","isArray","newRxTypeError","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addHook","when","key","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","promiseSeries","_runHooksSync","promiseWait","time","ret","res","timeout","setTimeout","delete","add","destroy","PROMISE_RESOLVE_FALSE","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","runAsyncPluginHooks","remove","removeCollectionStorages","storage","internalStore","password","hashFunction","_createClass2","default","operation","collection","colProto","Object","getPrototypeOf","fnName","ucfirst","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","overwritable","isDevMode","runPluginHooks","createRxCollectionStorageInstance","entries","funName","defineProperty","version","creator","catch","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from './plugins/utils/index.ts';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper.ts';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query.ts';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error.ts';\nimport type {\n RxMigrationState\n} from './plugins/migration-schema/index.ts';\nimport {\n DocumentCache, mapDocumentsDataToCacheDocs\n} from './doc-cache.ts';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache.ts';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer.ts';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks.ts';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageWriteError,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex,\n MigrationStrategies\n} from './types/index.d.ts';\n\nimport {\n RxSchema\n} from './rx-schema.ts';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { defaultConflictHandler } from './replication-protocol/index.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; }\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: MigrationStrategies = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _incrementalUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocumentCache = {} as any;\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public checkpoint$: Observable = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n this.incrementalWriteQueue = new IncrementalWriteQueue(\n this.storageInstance,\n this.schema.primaryPath,\n (newData, oldData) => beforeDocumentUpdateWrite(this as any, newData, oldData),\n result => this._runHooks('post', 'save', result)\n );\n\n const collectionEventBulks$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n );\n this.$ = collectionEventBulks$.pipe(\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this.checkpoint$ = collectionEventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.$.pipe(filter(cE => !cE.isLocal)),\n docData => createNewRxDocument(this.asRxCollection, docData)\n );\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context,\n endTime: eventBulk.endTime,\n startTime: eventBulk.startTime\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n /**\n * Manually call the cleanup function of the storage.\n * @link https://rxdb.info/cleanup.html\n */\n cleanup(_minimumDeletedTime?: number): Promise {\n throw pluginMissing('cleanup');\n }\n\n // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration');\n }\n getMigrationState(): RxMigrationState {\n throw pluginMissing('migration');\n }\n startMigration(batchSize: number = 10): Promise {\n return this.getMigrationState().startMigration(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getMigrationState().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n const writeResult = await this.bulkInsert([json as any]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, (json as any)[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const primaryPath = this.schema.primaryPath;\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n const row: BulkWriteRow = { document: doc };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const rxDocuments = mapDocumentsDataToCacheDocs(this._docCache, results.success);\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n docs.forEach(doc => {\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids).exec();\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = rxDocument.toMutableJSON(true) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = results.success.map(d => d[primaryPath] as string);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments = successIds.map(id => getFromMapOrThrow(rxDocumentMap, id));\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n const success = insertResult.success.slice(0);\n const error: RxStorageWriteError[] = [];\n\n // update the ones that existed already\n await Promise.all(\n insertResult.error.map(async (err) => {\n if (err.status !== 409) {\n error.push(err);\n } else {\n const id = err.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(err.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n success.push(newDoc);\n }\n })\n );\n return {\n error,\n success\n };\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n async upsert(json: Partial): Promise> {\n const bulkResult = await this.bulkUpsert([json]);\n throwIfIsStorageWriteError(\n this.asRxCollection,\n (json as any)[this.schema.primaryPath],\n json as any,\n bulkResult.error[0]\n );\n return bulkResult.success[0];\n }\n\n /**\n * upserts to a RxDocument, uses incrementalModify if document already exists\n */\n incrementalUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[]\n > {\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\n // TODO move this check to dev-mode plugin\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n\n // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\n > {\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.password,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _incrementalUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.incrementalModify((_innerDoc) => {\n return json;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _incrementalUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary);\n if (docDataFromCache) {\n return Promise.resolve({\n doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache),\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password,\n devMode: overwritable.isDevMode()\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAMA,IAAAC,MAAA,GAAAD,OAAA;AAUA,IAAAE,mBAAA,GAAAF,OAAA;AAKA,IAAAG,QAAA,GAAAH,OAAA;AAIA,IAAAI,QAAA,GAAAJ,OAAA;AAOA,IAAAK,SAAA,GAAAL,OAAA;AAGA,IAAAM,WAAA,GAAAN,OAAA;AAKA,IAAAO,kBAAA,GAAAP,OAAA;AAIA,IAAAQ,MAAA,GAAAR,OAAA;AA6CA,IAAAS,yBAAA,GAAAT,OAAA;AAGA,IAAAU,gBAAA,GAAAV,OAAA;AAMA,IAAAW,OAAA,GAAAX,OAAA;AACA,IAAAY,iBAAA,GAAAZ,OAAA;AACA,IAAAa,WAAA,GAAAb,OAAA;AACA,IAAAc,aAAA,GAAAd,OAAA;AAEA,IAAMe,UAAU,GAAG,CAAC,KAAK,EAAE,MAAM,CAAU;AAE3C,IAAMC,UAAU,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAU;AAElE,IAAIC,YAAY,GAAG,KAAK;AAAC,IAEZC,gBAAgB,GAAAC,OAAA,CAAAD,gBAAA;EAQzB;AACJ;AACA;;EAKI,SAAAA,iBACWE,QAAyE,EACzEC,IAAY,EACZC,MAAgC,EAChCC,uBAAwF,EACxFC,uBAAgD,GAAG,CAAC,CAAQ,EAC5DC,mBAAwC,GAAG,CAAC,CAAC,EAC7CC,OAAuB,GAAG,CAAC,CAAC,EAC5BC,WAA2B,GAAG,CAAC,CAAC,EAChCC,OAAY,GAAG,CAAC,CAAC,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3G,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEO,SAAS4G,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYlQ,gBAAgB;AAC1C"} \ No newline at end of file +{"version":3,"file":"rx-collection.js","names":["_rxjs","require","_index","_rxCollectionHelper","_rxQuery","_rxError","_docCache","_queryCache","_changeEventBuffer","_hooks","_rxDocumentPrototypeMerge","_rxStorageHelper","_index2","_incrementalWrite","_rxDocument","_overwritable","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","exports","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","defaultCacheReplacementPolicy","statics","conflictHandler","defaultConflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","_incrementalUpsertQueues","Map","synced","hooks","_subs","createQueryCache","$","checkpoint$","onDestroy","destroyed","_applyHookFunctions","asRxCollection","_proto","prototype","prepare","getWrappedStorageInstance","jsonSchema","IncrementalWriteQueue","primaryPath","newData","oldData","beforeDocumentUpdateWrite","result","_runHooks","collectionEventBulks$","eventBulks$","pipe","filter","changeEventBulk","collectionName","mergeMap","events","map","checkpoint","createChangeEventBuffer","DocumentCache","cE","isLocal","docData","createNewRxDocument","databaseStorageToken","storageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","ev","storageChangeEventToRxChangeEvent","databaseToken","token","context","endTime","startTime","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","PROMISE_RESOLVE_VOID","cleanup","_minimumDeletedTime","pluginMissing","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","throwIfIsStorageWriteError","insertResult","ensureNotFalsy","success","docsData","length","useDocs","useDocData","fillObjectDataBeforeInsert","docs","hasHooks","Promise","all","doc","insertRows","row","document","results","bulkWrite","rxDocuments","mapDocumentsDataToCacheDocs","docsMap","forEach","set","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","flatClone","_deleted","previous","successIds","d","getFromMapOrThrow","bulkUpsert","insertData","useJsonByDocId","useJson","newRxError","slice","err","status","documentId","writeData","docDataInDb","documentInDb","getCachedRxDocument","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","_getDefaultQuery","query","createRxQuery","findOne","isArray","newRxTypeError","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addHook","when","key","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","promiseSeries","_runHooksSync","promiseWait","time","ret","res","timeout","setTimeout","delete","add","destroy","PROMISE_RESOLVE_FALSE","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","runAsyncPluginHooks","remove","removeCollectionStorages","storage","internalStore","password","hashFunction","_createClass2","default","operation","collection","colProto","Object","getPrototypeOf","fnName","ucfirst","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","overwritable","isDevMode","runPluginHooks","createRxCollectionStorageInstance","entries","funName","defineProperty","version","creator","catch","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from './plugins/utils/index.ts';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper.ts';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query.ts';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error.ts';\nimport type {\n RxMigrationState\n} from './plugins/migration-schema/index.ts';\nimport {\n DocumentCache, mapDocumentsDataToCacheDocs\n} from './doc-cache.ts';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache.ts';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer.ts';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks.ts';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageWriteError,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex,\n MigrationStrategies\n} from './types/index.d.ts';\n\nimport {\n RxSchema\n} from './rx-schema.ts';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { defaultConflictHandler } from './replication-protocol/index.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; }\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: MigrationStrategies = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _incrementalUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocumentCache = {} as any;\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public checkpoint$: Observable = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n this.incrementalWriteQueue = new IncrementalWriteQueue(\n this.storageInstance,\n this.schema.primaryPath,\n (newData, oldData) => beforeDocumentUpdateWrite(this as any, newData, oldData),\n result => this._runHooks('post', 'save', result)\n );\n\n const collectionEventBulks$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n );\n this.$ = collectionEventBulks$.pipe(\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this.checkpoint$ = collectionEventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.$.pipe(filter(cE => !cE.isLocal)),\n docData => createNewRxDocument(this.asRxCollection, docData)\n );\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context,\n endTime: eventBulk.endTime,\n startTime: eventBulk.startTime\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n /**\n * Manually call the cleanup function of the storage.\n * @link https://rxdb.info/cleanup.html\n */\n cleanup(_minimumDeletedTime?: number): Promise {\n throw pluginMissing('cleanup');\n }\n\n // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration-schema');\n }\n getMigrationState(): RxMigrationState {\n throw pluginMissing('migration-schema');\n }\n startMigration(batchSize: number = 10): Promise {\n return this.getMigrationState().startMigration(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getMigrationState().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n const writeResult = await this.bulkInsert([json as any]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, (json as any)[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const primaryPath = this.schema.primaryPath;\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n const row: BulkWriteRow = { document: doc };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const rxDocuments = mapDocumentsDataToCacheDocs(this._docCache, results.success);\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n docs.forEach(doc => {\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids).exec();\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = rxDocument.toMutableJSON(true) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = results.success.map(d => d[primaryPath] as string);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments = successIds.map(id => getFromMapOrThrow(rxDocumentMap, id));\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n const success = insertResult.success.slice(0);\n const error: RxStorageWriteError[] = [];\n\n // update the ones that existed already\n await Promise.all(\n insertResult.error.map(async (err) => {\n if (err.status !== 409) {\n error.push(err);\n } else {\n const id = err.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(err.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n success.push(newDoc);\n }\n })\n );\n return {\n error,\n success\n };\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n async upsert(json: Partial): Promise> {\n const bulkResult = await this.bulkUpsert([json]);\n throwIfIsStorageWriteError(\n this.asRxCollection,\n (json as any)[this.schema.primaryPath],\n json as any,\n bulkResult.error[0]\n );\n return bulkResult.success[0];\n }\n\n /**\n * upserts to a RxDocument, uses incrementalModify if document already exists\n */\n incrementalUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[]\n > {\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\n // TODO move this check to dev-mode plugin\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n\n // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\n > {\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.password,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _incrementalUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.incrementalModify((_innerDoc) => {\n return json;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _incrementalUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary);\n if (docDataFromCache) {\n return Promise.resolve({\n doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache),\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password,\n devMode: overwritable.isDevMode()\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAMA,IAAAC,MAAA,GAAAD,OAAA;AAUA,IAAAE,mBAAA,GAAAF,OAAA;AAKA,IAAAG,QAAA,GAAAH,OAAA;AAIA,IAAAI,QAAA,GAAAJ,OAAA;AAOA,IAAAK,SAAA,GAAAL,OAAA;AAGA,IAAAM,WAAA,GAAAN,OAAA;AAKA,IAAAO,kBAAA,GAAAP,OAAA;AAIA,IAAAQ,MAAA,GAAAR,OAAA;AA6CA,IAAAS,yBAAA,GAAAT,OAAA;AAGA,IAAAU,gBAAA,GAAAV,OAAA;AAMA,IAAAW,OAAA,GAAAX,OAAA;AACA,IAAAY,iBAAA,GAAAZ,OAAA;AACA,IAAAa,WAAA,GAAAb,OAAA;AACA,IAAAc,aAAA,GAAAd,OAAA;AAEA,IAAMe,UAAU,GAAG,CAAC,KAAK,EAAE,MAAM,CAAU;AAE3C,IAAMC,UAAU,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAU;AAElE,IAAIC,YAAY,GAAG,KAAK;AAAC,IAEZC,gBAAgB,GAAAC,OAAA,CAAAD,gBAAA;EAQzB;AACJ;AACA;;EAKI,SAAAA,iBACWE,QAAyE,EACzEC,IAAY,EACZC,MAAgC,EAChCC,uBAAwF,EACxFC,uBAAgD,GAAG,CAAC,CAAQ,EAC5DC,mBAAwC,GAAG,CAAC,CAAC,EAC7CC,OAAuB,GAAG,CAAC,CAAC,E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AAK,CAAC,CAAC,CACzBrI,IAAI,CAAC,MAAM6B,OAAO,CAACmJ,MAAM,CAAC3G,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEO,SAAS4G,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYlQ,gBAAgB;AAC1C"} \ No newline at end of file diff --git a/dist/cjs/rx-database.js b/dist/cjs/rx-database.js index 20973635d5d..61640d92cc0 100644 --- a/dist/cjs/rx-database.js +++ b/dist/cjs/rx-database.js @@ -284,7 +284,7 @@ var RxDatabaseBase = exports.RxDatabaseBase = /*#__PURE__*/function () { throw (0, _index.pluginMissing)('leader-election'); }; _proto.migrationStates = function migrationStates() { - throw (0, _index.pluginMissing)('migration'); + throw (0, _index.pluginMissing)('migration-schema'); } /** diff --git a/dist/cjs/rx-database.js.map b/dist/cjs/rx-database.js.map index 82dffac52fb..57e4820041b 100644 --- a/dist/cjs/rx-database.js.map +++ b/dist/cjs/rx-database.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database.js","names":["_customIdleQueue","require","_index","_rxError","_rxSchema","_hooks","_rxjs","_operators","_rxCollection","_rxStorageHelper","_obliviousSet","_rxDatabaseInternalStore","_rxCollectionHelper","_overwritable","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","exports","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","idleQueue","IdleQueue","rxdbVersion","RXDB_VERSION","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","Promise","all","Object","entries","map","args","collectionName","rxJsonSchema","createRxSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","useArgs","assign","database","hookData","flatClone","runPluginHooks","conflictHandler","putDocsResult","ensureNoStartupErrors","error","status","writeError","docInDb","ensureNotFalsy","documentInDb","collection","previousSchemaHash","previousSchema","ret","keys","createRxCollection","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","pluginMissing","importJSON","_exportedJSON","backup","_options","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","runAsyncPluginHooks","complete","sub","unsubscribe","col","close","delete","remove","removeRxDatabase","_createClass2","default","throwIfDatabaseNameUsed","link","createRxDatabaseStorageInstance","databaseInstanceToken","databaseName","createStorageInstance","INTERNAL_STORAGE_NAME","devMode","overwritable","isDevMode","createRxDatabase","ignoreDuplicate","localDocuments","defaultHashSha256","randomCouchString","storageInstance","rxDatabase","creator","dbInternalsStorageInstance","collectionDocs","getAllCollectionDocuments","collectionNames","forEach","removedCollectionNames","Array","from","removeCollectionStorages","isRxDatabase","obj","dbCount","isRxDatabaseFirstTimeInstantiated","tokenDoc","instanceToken"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise\n} from './types/index.d.ts';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256,\n RXDB_VERSION\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema.ts';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks.ts';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection.ts';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport type { RxBackupState } from './plugins/backup/index.ts';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store.ts';\nimport { removeCollectionStorages } from './rx-collection-helper.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxMigrationState } from './plugins/migration-schema/index.ts';\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 public readonly rxdbVersion = RXDB_VERSION;\n\n /**\n * Contains all known non-closed storage instances\n * that belong to this database.\n * Used in plugins and unit tests.\n */\n public readonly storageInstances = new Set>();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean\n ) {\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 await Promise.all(\n Object.entries(collectionCreators).map(async ([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema, this.hashFunction);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: await schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n })\n );\n\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n await Promise.all(\n putDocsResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('DB12', {\n database: this.name,\n writeError: error\n });\n }\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== await schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: await schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n })\n );\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\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, this.password));\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 = true,\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 password?: string\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false,\n password\n );\n\n const collectionDocs = await getAllCollectionDocuments(dbInternalsStorageInstance);\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 password\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";;;;;;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,0BAAmB,EAAC,sBAAsB,EAAE;IAC9Ce,YAAY;IACZjJ;EACJ,CAAC,CAAC;EAEF,MAAM+J,0BAA0B,CAACtB,MAAM,CAAC,CAAC;EACzC,OAAO2B,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,CACnD9E,QAAoB,EACJ;EAChB,IAAM+E,QAAQ,GAAG,MAAM/E,QAAQ,CAAChE,oBAAoB;EACpD,OAAO+I,QAAQ,CAACnI,IAAI,CAACoI,aAAa,KAAKhF,QAAQ,CAAC9F,KAAK;AACzD;;AAGA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeoG,qBAAqBA,CACvC0D,UAAyC,EAC3C;EACE,MAAMA,UAAU,CAAClI,YAAY;EAC7B,IAAIkI,UAAU,CAAC7I,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAM6I,UAAU,CAAC7I,aAAa,CAAC,CAAC,CAAC;EACrC;AACJ"} \ No newline at end of file +{"version":3,"file":"rx-database.js","names":["_customIdleQueue","require","_index","_rxError","_rxSchema","_hooks","_rxjs","_operators","_rxCollection","_rxStorageHelper","_obliviousSet","_rxDatabaseInternalStore","_rxCollectionHelper","_overwritable","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","exports","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","idleQueue","IdleQueue","rxdbVersion","RXDB_VERSION","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","Promise","all","Object","entries","map","args","collectionName","rxJsonSchema","createRxSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","getDefaultRxDocumentMeta","_rev","getDefaultRevision","_attachments","useArgs","assign","database","hookData","flatClone","runPluginHooks","conflictHandler","putDocsResult","ensureNoStartupErrors","error","status","writeError","docInDb","ensureNotFalsy","documentInDb","collection","previousSchemaHash","previousSchema","ret","keys","createRxCollection","defineProperty","get","lockedRun","fn","wrapCall","requestIdlePromise","exportJSON","_collections","pluginMissing","importJSON","_exportedJSON","backup","_options","leaderElector","isLeader","waitForLeadership","migrationStates","destroy","runAsyncPluginHooks","complete","sub","unsubscribe","col","close","delete","remove","removeRxDatabase","_createClass2","default","throwIfDatabaseNameUsed","link","createRxDatabaseStorageInstance","databaseInstanceToken","databaseName","createStorageInstance","INTERNAL_STORAGE_NAME","devMode","overwritable","isDevMode","createRxDatabase","ignoreDuplicate","localDocuments","defaultHashSha256","randomCouchString","storageInstance","rxDatabase","creator","dbInternalsStorageInstance","collectionDocs","getAllCollectionDocuments","collectionNames","forEach","removedCollectionNames","Array","from","removeCollectionStorages","isRxDatabase","obj","dbCount","isRxDatabaseFirstTimeInstantiated","tokenDoc","instanceToken"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise\n} from './types/index.d.ts';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256,\n RXDB_VERSION\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema.ts';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks.ts';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection.ts';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport type { RxBackupState } from './plugins/backup/index.ts';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store.ts';\nimport { removeCollectionStorages } from './rx-collection-helper.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxMigrationState } from './plugins/migration-schema/index.ts';\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 public readonly rxdbVersion = RXDB_VERSION;\n\n /**\n * Contains all known non-closed storage instances\n * that belong to this database.\n * Used in plugins and unit tests.\n */\n public readonly storageInstances = new Set>();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean\n ) {\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 await Promise.all(\n Object.entries(collectionCreators).map(async ([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema, this.hashFunction);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: await schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n })\n );\n\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n await Promise.all(\n putDocsResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('DB12', {\n database: this.name,\n writeError: error\n });\n }\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== await schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: await schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n })\n );\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n * @note When an interface is loaded in this collection all base properties of the type are typed as `any`\n * since data could be encrypted.\n */\n importJSON(_exportedJSON: RxDumpDatabaseAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n backup(_options: BackupOptions): RxBackupState {\n throw pluginMissing('backup');\n }\n\n public leaderElector(): LeaderElector {\n throw pluginMissing('leader-election');\n }\n\n public isLeader(): boolean {\n throw pluginMissing('leader-election');\n }\n /**\n * returns a promise which resolves when the instance becomes leader\n */\n public waitForLeadership(): Promise {\n throw pluginMissing('leader-election');\n }\n\n public migrationStates(): Observable {\n throw pluginMissing('migration-schema');\n }\n\n /**\n * destroys the database-instance and all collections\n */\n public async destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n // settings destroyed = true must be the first thing to do.\n this.destroyed = true;\n\n await runAsyncPluginHooks('preDestroyRxDatabase', this);\n /**\n * Complete the event stream\n * to stop all subscribers who forgot to unsubscribe.\n */\n this.eventBulks$.complete();\n\n DB_COUNT--;\n this._subs.map(sub => sub.unsubscribe());\n\n /**\n * Destroying the pseudo instance will throw\n * because stuff is missing\n * TODO we should not need the pseudo instance on runtime.\n * we should generate the property list on build time.\n */\n if (this.name === 'pseudoInstance') {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * First wait until the database is idle\n */\n return this.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n // destroy all collections\n .then(() => Promise.all(\n Object.keys(this.collections as any)\n .map(key => (this.collections as any)[key])\n .map(col => col.destroy())\n ))\n // destroy internal storage instances\n .then(() => this.internalStore.close())\n // remove combination from USED_COMBINATIONS-map\n .then(() => USED_DATABASE_NAMES.delete(this.name))\n .then(() => true);\n }\n\n /**\n * deletes the database and its stored data.\n * Returns the names of all removed collections.\n */\n remove(): Promise {\n return this\n .destroy()\n .then(() => removeRxDatabase(this.name, this.storage, this.password));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions\n > {\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 = true,\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 password?: string\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false,\n password\n );\n\n const collectionDocs = await getAllCollectionDocuments(dbInternalsStorageInstance);\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 password\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupEr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B,EACjEvK,OAAO,EACP+J,0BAA0B,EAC1Bf,qBAAqB,EACrBC,YAAY,EACZvE,cAAc,EACdxE,QACJ,CAAC,CACL,CAAC;EAED,MAAM,IAAAgI,0BAAmB,EAAC,sBAAsB,EAAE;IAC9Ce,YAAY;IACZjJ;EACJ,CAAC,CAAC;EAEF,MAAM+J,0BAA0B,CAACtB,MAAM,CAAC,CAAC;EACzC,OAAO2B,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,CACnD9E,QAAoB,EACJ;EAChB,IAAM+E,QAAQ,GAAG,MAAM/E,QAAQ,CAAChE,oBAAoB;EACpD,OAAO+I,QAAQ,CAACnI,IAAI,CAACoI,aAAa,KAAKhF,QAAQ,CAAC9F,KAAK;AACzD;;AAGA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeoG,qBAAqBA,CACvC0D,UAAyC,EAC3C;EACE,MAAMA,UAAU,CAAClI,YAAY;EAC7B,IAAIkI,UAAU,CAAC7I,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAM6I,UAAU,CAAC7I,aAAa,CAAC,CAAC,CAAC;EACrC;AACJ"} \ No newline at end of file diff --git a/dist/cjs/rx-schema-helper.js b/dist/cjs/rx-schema-helper.js index f25a578fa6b..90a0fb35acd 100644 --- a/dist/cjs/rx-schema-helper.js +++ b/dist/cjs/rx-schema-helper.js @@ -215,6 +215,13 @@ function fillWithDefaultSettings(schemaObj) { // we need this index for the getChangedDocumentsSince() method useIndexes.push(['_meta.lwt', primaryPath]); + // also add the internalIndexes + if (schemaObj.internalIndexes) { + schemaObj.internalIndexes.map(idx => { + useIndexes.push(idx); + }); + } + // make indexes unique var hasIndex = new Set(); useIndexes.filter(index => { diff --git a/dist/cjs/rx-schema-helper.js.map b/dist/cjs/rx-schema-helper.js.map index 6508ce1cf68..2c91af866a4 100644 --- a/dist/cjs/rx-schema-helper.js.map +++ b/dist/cjs/rx-schema-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-schema-helper.js","names":["_rxError","require","_index","getPseudoSchemaForVersion","version","primaryKey","pseudoSchema","fillWithDefaultSettings","type","properties","maxLength","indexes","required","getSchemaByObjectPath","rxJsonSchema","path","usePath","replace","REGEX_ALL_DOTS","trimDots","ret","getProperty","fillPrimaryKey","primaryPath","jsonSchema","documentData","newPrimary","getComposedPrimaryKeyOfDocumentData","existingPrimary","newRxError","args","schema","getPrimaryFieldOfPrimaryKey","key","getLengthOfPrimaryKey","schemaPart","ensureNotFalsy","compositePrimary","fields","map","field","value","join","separator","normalizeRxJsonSchema","normalizedSchema","sortObject","getDefaultIndex","schemaObj","flatClone","additionalProperties","Object","prototype","hasOwnProperty","call","keyCompression","slice","encrypted","_rev","minLength","_attachments","_deleted","_meta","RX_META_SCHEMA","push","finalFields","getFinalFields","appendToArray","filter","includes","elem","pos","arr","indexOf","useIndexes","index","arIndex","isMaybeReadonlyArray","unshift","length","hasIndex","Set","indexStr","has","add","exports","lwt","minimum","RX_META_LWT_MINIMUM","maximum","multipleOf","keys","final","forEach","fillObjectWithDefaults","rxSchema","obj","defaultKeys","defaultValues","i","DEFAULT_CHECKPOINT_SCHEMA","id"],"sources":["../../src/rx-schema-helper.ts"],"sourcesContent":["import { newRxError } from './rx-error.ts';\nimport type {\n CompositePrimaryKey,\n DeepReadonly,\n JsonSchema,\n PrimaryKey,\n RxDocumentData,\n RxJsonSchema,\n RxStorageDefaultCheckpoint,\n StringKeys\n} from './types/index.d.ts';\nimport {\n appendToArray,\n ensureNotFalsy,\n flatClone,\n getProperty,\n isMaybeReadonlyArray,\n REGEX_ALL_DOTS,\n RX_META_LWT_MINIMUM,\n sortObject,\n trimDots\n} from './plugins/utils/index.ts';\nimport type { RxSchema } from './rx-schema.ts';\n\n/**\n * Helper function to create a valid RxJsonSchema\n * with a given version.\n */\nexport function getPseudoSchemaForVersion(\n version: number,\n primaryKey: StringKeys\n): RxJsonSchema> {\n const pseudoSchema: RxJsonSchema> = fillWithDefaultSettings({\n version,\n type: 'object',\n primaryKey: primaryKey as any,\n properties: {\n [primaryKey]: {\n type: 'string',\n maxLength: 100\n }\n } as any,\n indexes: [\n [primaryKey]\n ],\n required: [primaryKey]\n });\n return pseudoSchema;\n}\n\n/**\n * Returns the sub-schema for a given path\n */\nexport function getSchemaByObjectPath(\n rxJsonSchema: RxJsonSchema,\n path: keyof T | string\n): JsonSchema {\n let usePath: string = path as string;\n usePath = usePath.replace(REGEX_ALL_DOTS, '.properties.');\n usePath = 'properties.' + usePath;\n usePath = trimDots(usePath);\n\n const ret = getProperty(rxJsonSchema, usePath);\n return ret;\n}\n\nexport function fillPrimaryKey(\n primaryPath: keyof T,\n jsonSchema: RxJsonSchema,\n documentData: RxDocumentData\n): RxDocumentData {\n // optimization shortcut.\n if (typeof jsonSchema.primaryKey === 'string') {\n return documentData;\n }\n\n const newPrimary = getComposedPrimaryKeyOfDocumentData(\n jsonSchema,\n documentData\n );\n const existingPrimary: string | undefined = documentData[primaryPath] as any;\n if (\n existingPrimary &&\n existingPrimary !== newPrimary\n ) {\n throw newRxError(\n 'DOC19',\n {\n args: {\n documentData,\n existingPrimary,\n newPrimary,\n },\n schema: jsonSchema\n });\n }\n\n (documentData as any)[primaryPath] = newPrimary;\n return documentData;\n}\n\nexport function getPrimaryFieldOfPrimaryKey(\n primaryKey: PrimaryKey\n): StringKeys {\n if (typeof primaryKey === 'string') {\n return primaryKey as any;\n } else {\n return (primaryKey as CompositePrimaryKey).key;\n }\n}\n\nexport function getLengthOfPrimaryKey(\n schema: RxJsonSchema>\n): number {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const schemaPart = getSchemaByObjectPath(schema, primaryPath);\n return ensureNotFalsy(schemaPart.maxLength);\n}\n\n/**\n * Returns the composed primaryKey of a document by its data.\n */\nexport function getComposedPrimaryKeyOfDocumentData(\n jsonSchema: RxJsonSchema | RxJsonSchema>,\n documentData: Partial\n): string {\n if (typeof jsonSchema.primaryKey === 'string') {\n return (documentData as any)[jsonSchema.primaryKey];\n }\n\n const compositePrimary: CompositePrimaryKey = jsonSchema.primaryKey as any;\n return compositePrimary.fields.map(field => {\n const value = getProperty(documentData as any, field as string);\n if (typeof value === 'undefined') {\n throw newRxError('DOC18', { args: { field, documentData } });\n }\n return value;\n }).join(compositePrimary.separator);\n}\n\n\n/**\n * Normalize the RxJsonSchema.\n * We need this to ensure everything is set up properly\n * and we have the same hash on schemas that represent the same value but\n * have different json.\n *\n * - Orders the schemas attributes by alphabetical order\n * - Adds the primaryKey to all indexes that do not contain the primaryKey\n * - We need this for deterministic sort order on all queries, which is required for event-reduce to work.\n *\n * @return RxJsonSchema - ordered and filled\n */\nexport function normalizeRxJsonSchema(jsonSchema: RxJsonSchema): RxJsonSchema {\n const normalizedSchema: RxJsonSchema = sortObject(jsonSchema, true);\n return normalizedSchema;\n}\n\n/**\n * If the schema does not specify any index,\n * we add this index so we at least can run RxQuery()\n * and only select non-deleted fields.\n */\nexport function getDefaultIndex(primaryPath: string) {\n return ['_deleted', primaryPath];\n}\n\n/**\n * fills the schema-json with default-settings\n * @return cloned schemaObj\n */\nexport function fillWithDefaultSettings(\n schemaObj: RxJsonSchema\n): RxJsonSchema> {\n schemaObj = flatClone(schemaObj);\n const primaryPath: string = getPrimaryFieldOfPrimaryKey(schemaObj.primaryKey);\n schemaObj.properties = flatClone(schemaObj.properties);\n\n // additionalProperties is always false\n schemaObj.additionalProperties = false;\n\n // fill with key-compression-state ()\n if (!Object.prototype.hasOwnProperty.call(schemaObj, 'keyCompression')) {\n schemaObj.keyCompression = false;\n }\n\n // indexes must be array\n schemaObj.indexes = schemaObj.indexes ? schemaObj.indexes.slice(0) : [];\n\n // required must be array\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n\n // encrypted must be array\n schemaObj.encrypted = schemaObj.encrypted ? schemaObj.encrypted.slice(0) : [];\n\n // add _rev\n (schemaObj.properties as any)._rev = {\n type: 'string',\n minLength: 1\n };\n\n // add attachments\n (schemaObj.properties as any)._attachments = {\n type: 'object'\n };\n\n // add deleted flag\n (schemaObj.properties as any)._deleted = {\n type: 'boolean'\n };\n\n // add meta property\n (schemaObj.properties as any)._meta = RX_META_SCHEMA;\n\n /**\n * meta fields are all required\n */\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n (schemaObj.required as string[]).push('_deleted');\n (schemaObj.required as string[]).push('_rev');\n (schemaObj.required as string[]).push('_meta');\n (schemaObj.required as string[]).push('_attachments');\n\n // final fields are always required\n const finalFields = getFinalFields(schemaObj);\n appendToArray(schemaObj.required as any, finalFields);\n schemaObj.required = schemaObj.required\n .filter((field: string) => !field.includes('.'))\n .filter((elem: any, pos: any, arr: any) => arr.indexOf(elem) === pos); // unique;\n\n // version is 0 by default\n schemaObj.version = schemaObj.version || 0;\n\n const useIndexes: string[][] = schemaObj.indexes.map(index => {\n const arIndex = isMaybeReadonlyArray(index) ? index.slice(0) : [index];\n /**\n * Append primary key to indexes that do not contain the primaryKey.\n * All indexes must have the primaryKey to ensure a deterministic sort order.\n */\n if (!arIndex.includes(primaryPath)) {\n arIndex.push(primaryPath);\n }\n\n // add _deleted flag to all indexes so we can query only non-deleted fields\n // in RxDB itself\n if (arIndex[0] !== '_deleted') {\n arIndex.unshift('_deleted');\n }\n\n return arIndex;\n });\n\n if (useIndexes.length === 0) {\n useIndexes.push(getDefaultIndex(primaryPath));\n }\n\n // we need this index for the getChangedDocumentsSince() method\n useIndexes.push(['_meta.lwt', primaryPath]);\n\n // make indexes unique\n const hasIndex = new Set();\n useIndexes.filter(index => {\n const indexStr = index.join(',');\n if (hasIndex.has(indexStr)) {\n return false;\n } else {\n hasIndex.add(indexStr);\n return true;\n }\n });\n\n schemaObj.indexes = useIndexes;\n\n return schemaObj as any;\n}\n\n\nexport const RX_META_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n /**\n * The last-write time.\n * Unix time in milliseconds.\n */\n lwt: {\n type: 'number',\n /**\n * We use 1 as minimum so that the value is never falsy.\n */\n minimum: RX_META_LWT_MINIMUM,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n /**\n * Additional properties are allowed\n * and can be used by plugins to set various flags.\n */\n additionalProperties: true as any,\n required: [\n 'lwt'\n ]\n};\n\n\n/**\n * returns the final-fields of the schema\n * @return field-names of the final-fields\n */\nexport function getFinalFields(\n jsonSchema: RxJsonSchema\n): string[] {\n const ret = Object.keys(jsonSchema.properties)\n .filter(key => (jsonSchema as any).properties[key].final);\n\n // primary is also final\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n ret.push(primaryPath);\n\n // fields of composite primary are final\n if (typeof jsonSchema.primaryKey !== 'string') {\n (jsonSchema.primaryKey as CompositePrimaryKey).fields\n .forEach(field => ret.push(field as string));\n }\n\n return ret;\n}\n\n/**\n * fills all unset fields with default-values if set\n * @hotPath\n */\nexport function fillObjectWithDefaults(rxSchema: RxSchema, obj: any): any {\n const defaultKeys = Object.keys(rxSchema.defaultValues);\n for (let i = 0; i < defaultKeys.length; ++i) {\n const key = defaultKeys[i];\n if (!Object.prototype.hasOwnProperty.call(obj, key) || typeof obj[key] === 'undefined') {\n obj[key] = rxSchema.defaultValues[key];\n }\n }\n return obj;\n}\n\nexport const DEFAULT_CHECKPOINT_SCHEMA: DeepReadonly> = {\n type: 'object',\n properties: {\n id: {\n type: 'string'\n },\n lwt: {\n type: 'number'\n }\n },\n required: [\n 'id',\n 'lwt'\n ],\n additionalProperties: false\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,IAAAA,QAAA,GAAAC,OAAA;AAWA,IAAAC,MAAA,GAAAD,OAAA;AAaA;AACA;AACA;AACA;AACO,SAASE,yBAAyBA,CACrCC,OAAe,EACfC,UAAyB,EACM;E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;EAC3F5F,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACR4F,EAAE,EAAE;MACA7F,IAAI,EAAE;IACV,CAAC;IACD8E,GAAG,EAAE;MACD9E,IAAI,EAAE;IACV;EACJ,CAAC;EACDI,QAAQ,EAAE,CACN,IAAI,EACJ,KAAK,CACR;EACDsC,oBAAoB,EAAE;AAC1B,CAAU"} \ No newline at end of file +{"version":3,"file":"rx-schema-helper.js","names":["_rxError","require","_index","getPseudoSchemaForVersion","version","primaryKey","pseudoSchema","fillWithDefaultSettings","type","properties","maxLength","indexes","required","getSchemaByObjectPath","rxJsonSchema","path","usePath","replace","REGEX_ALL_DOTS","trimDots","ret","getProperty","fillPrimaryKey","primaryPath","jsonSchema","documentData","newPrimary","getComposedPrimaryKeyOfDocumentData","existingPrimary","newRxError","args","schema","getPrimaryFieldOfPrimaryKey","key","getLengthOfPrimaryKey","schemaPart","ensureNotFalsy","compositePrimary","fields","map","field","value","join","separator","normalizeRxJsonSchema","normalizedSchema","sortObject","getDefaultIndex","schemaObj","flatClone","additionalProperties","Object","prototype","hasOwnProperty","call","keyCompression","slice","encrypted","_rev","minLength","_attachments","_deleted","_meta","RX_META_SCHEMA","push","finalFields","getFinalFields","appendToArray","filter","includes","elem","pos","arr","indexOf","useIndexes","index","arIndex","isMaybeReadonlyArray","unshift","length","internalIndexes","idx","hasIndex","Set","indexStr","has","add","exports","lwt","minimum","RX_META_LWT_MINIMUM","maximum","multipleOf","keys","final","forEach","fillObjectWithDefaults","rxSchema","obj","defaultKeys","defaultValues","i","DEFAULT_CHECKPOINT_SCHEMA","id"],"sources":["../../src/rx-schema-helper.ts"],"sourcesContent":["import { newRxError } from './rx-error.ts';\nimport type {\n CompositePrimaryKey,\n DeepReadonly,\n JsonSchema,\n PrimaryKey,\n RxDocumentData,\n RxJsonSchema,\n RxStorageDefaultCheckpoint,\n StringKeys\n} from './types/index.d.ts';\nimport {\n appendToArray,\n ensureNotFalsy,\n flatClone,\n getProperty,\n isMaybeReadonlyArray,\n REGEX_ALL_DOTS,\n RX_META_LWT_MINIMUM,\n sortObject,\n trimDots\n} from './plugins/utils/index.ts';\nimport type { RxSchema } from './rx-schema.ts';\n\n/**\n * Helper function to create a valid RxJsonSchema\n * with a given version.\n */\nexport function getPseudoSchemaForVersion(\n version: number,\n primaryKey: StringKeys\n): RxJsonSchema> {\n const pseudoSchema: RxJsonSchema> = fillWithDefaultSettings({\n version,\n type: 'object',\n primaryKey: primaryKey as any,\n properties: {\n [primaryKey]: {\n type: 'string',\n maxLength: 100\n }\n } as any,\n indexes: [\n [primaryKey]\n ],\n required: [primaryKey]\n });\n return pseudoSchema;\n}\n\n/**\n * Returns the sub-schema for a given path\n */\nexport function getSchemaByObjectPath(\n rxJsonSchema: RxJsonSchema,\n path: keyof T | string\n): JsonSchema {\n let usePath: string = path as string;\n usePath = usePath.replace(REGEX_ALL_DOTS, '.properties.');\n usePath = 'properties.' + usePath;\n usePath = trimDots(usePath);\n\n const ret = getProperty(rxJsonSchema, usePath);\n return ret;\n}\n\nexport function fillPrimaryKey(\n primaryPath: keyof T,\n jsonSchema: RxJsonSchema,\n documentData: RxDocumentData\n): RxDocumentData {\n // optimization shortcut.\n if (typeof jsonSchema.primaryKey === 'string') {\n return documentData;\n }\n\n const newPrimary = getComposedPrimaryKeyOfDocumentData(\n jsonSchema,\n documentData\n );\n const existingPrimary: string | undefined = documentData[primaryPath] as any;\n if (\n existingPrimary &&\n existingPrimary !== newPrimary\n ) {\n throw newRxError(\n 'DOC19',\n {\n args: {\n documentData,\n existingPrimary,\n newPrimary,\n },\n schema: jsonSchema\n });\n }\n\n (documentData as any)[primaryPath] = newPrimary;\n return documentData;\n}\n\nexport function getPrimaryFieldOfPrimaryKey(\n primaryKey: PrimaryKey\n): StringKeys {\n if (typeof primaryKey === 'string') {\n return primaryKey as any;\n } else {\n return (primaryKey as CompositePrimaryKey).key;\n }\n}\n\nexport function getLengthOfPrimaryKey(\n schema: RxJsonSchema>\n): number {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const schemaPart = getSchemaByObjectPath(schema, primaryPath);\n return ensureNotFalsy(schemaPart.maxLength);\n}\n\n/**\n * Returns the composed primaryKey of a document by its data.\n */\nexport function getComposedPrimaryKeyOfDocumentData(\n jsonSchema: RxJsonSchema | RxJsonSchema>,\n documentData: Partial\n): string {\n if (typeof jsonSchema.primaryKey === 'string') {\n return (documentData as any)[jsonSchema.primaryKey];\n }\n\n const compositePrimary: CompositePrimaryKey = jsonSchema.primaryKey as any;\n return compositePrimary.fields.map(field => {\n const value = getProperty(documentData as any, field as string);\n if (typeof value === 'undefined') {\n throw newRxError('DOC18', { args: { field, documentData } });\n }\n return value;\n }).join(compositePrimary.separator);\n}\n\n\n/**\n * Normalize the RxJsonSchema.\n * We need this to ensure everything is set up properly\n * and we have the same hash on schemas that represent the same value but\n * have different json.\n *\n * - Orders the schemas attributes by alphabetical order\n * - Adds the primaryKey to all indexes that do not contain the primaryKey\n * - We need this for deterministic sort order on all queries, which is required for event-reduce to work.\n *\n * @return RxJsonSchema - ordered and filled\n */\nexport function normalizeRxJsonSchema(jsonSchema: RxJsonSchema): RxJsonSchema {\n const normalizedSchema: RxJsonSchema = sortObject(jsonSchema, true);\n return normalizedSchema;\n}\n\n/**\n * If the schema does not specify any index,\n * we add this index so we at least can run RxQuery()\n * and only select non-deleted fields.\n */\nexport function getDefaultIndex(primaryPath: string) {\n return ['_deleted', primaryPath];\n}\n\n/**\n * fills the schema-json with default-settings\n * @return cloned schemaObj\n */\nexport function fillWithDefaultSettings(\n schemaObj: RxJsonSchema\n): RxJsonSchema> {\n schemaObj = flatClone(schemaObj);\n const primaryPath: string = getPrimaryFieldOfPrimaryKey(schemaObj.primaryKey);\n schemaObj.properties = flatClone(schemaObj.properties);\n\n // additionalProperties is always false\n schemaObj.additionalProperties = false;\n\n // fill with key-compression-state ()\n if (!Object.prototype.hasOwnProperty.call(schemaObj, 'keyCompression')) {\n schemaObj.keyCompression = false;\n }\n\n // indexes must be array\n schemaObj.indexes = schemaObj.indexes ? schemaObj.indexes.slice(0) : [];\n\n // required must be array\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n\n // encrypted must be array\n schemaObj.encrypted = schemaObj.encrypted ? schemaObj.encrypted.slice(0) : [];\n\n // add _rev\n (schemaObj.properties as any)._rev = {\n type: 'string',\n minLength: 1\n };\n\n // add attachments\n (schemaObj.properties as any)._attachments = {\n type: 'object'\n };\n\n // add deleted flag\n (schemaObj.properties as any)._deleted = {\n type: 'boolean'\n };\n\n // add meta property\n (schemaObj.properties as any)._meta = RX_META_SCHEMA;\n\n /**\n * meta fields are all required\n */\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n (schemaObj.required as string[]).push('_deleted');\n (schemaObj.required as string[]).push('_rev');\n (schemaObj.required as string[]).push('_meta');\n (schemaObj.required as string[]).push('_attachments');\n\n // final fields are always required\n const finalFields = getFinalFields(schemaObj);\n appendToArray(schemaObj.required as any, finalFields);\n schemaObj.required = schemaObj.required\n .filter((field: string) => !field.includes('.'))\n .filter((elem: any, pos: any, arr: any) => arr.indexOf(elem) === pos); // unique;\n\n // version is 0 by default\n schemaObj.version = schemaObj.version || 0;\n\n const useIndexes: string[][] = schemaObj.indexes.map(index => {\n const arIndex = isMaybeReadonlyArray(index) ? index.slice(0) : [index];\n /**\n * Append primary key to indexes that do not contain the primaryKey.\n * All indexes must have the primaryKey to ensure a deterministic sort order.\n */\n if (!arIndex.includes(primaryPath)) {\n arIndex.push(primaryPath);\n }\n\n // add _deleted flag to all indexes so we can query only non-deleted fields\n // in RxDB itself\n if (arIndex[0] !== '_deleted') {\n arIndex.unshift('_deleted');\n }\n\n return arIndex;\n });\n\n if (useIndexes.length === 0) {\n useIndexes.push(getDefaultIndex(primaryPath));\n }\n\n // we need this index for the getChangedDocumentsSince() method\n useIndexes.push(['_meta.lwt', primaryPath]);\n\n // also add the internalIndexes\n if (schemaObj.internalIndexes) {\n schemaObj.internalIndexes.map(idx => {\n useIndexes.push(idx);\n });\n }\n\n // make indexes unique\n const hasIndex = new Set();\n useIndexes.filter(index => {\n const indexStr = index.join(',');\n if (hasIndex.has(indexStr)) {\n return false;\n } else {\n hasIndex.add(indexStr);\n return true;\n }\n });\n\n schemaObj.indexes = useIndexes;\n\n return schemaObj as any;\n}\n\n\nexport const RX_META_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n /**\n * The last-write time.\n * Unix time in milliseconds.\n */\n lwt: {\n type: 'number',\n /**\n * We use 1 as minimum so that the value is never falsy.\n */\n minimum: RX_META_LWT_MINIMUM,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n /**\n * Additional properties are allowed\n * and can be used by plugins to set various flags.\n */\n additionalProperties: true as any,\n required: [\n 'lwt'\n ]\n};\n\n\n/**\n * returns the final-fields of the schema\n * @return field-names of the final-fields\n */\nexport function getFinalFields(\n jsonSchema: RxJsonSchema\n): string[] {\n const ret = Object.keys(jsonSchema.properties)\n .filter(key => (jsonSchema as any).properties[key].final);\n\n // primary is also final\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n ret.push(primaryPath);\n\n // fields of composite primary are final\n if (typeof jsonSchema.primaryKey !== 'string') {\n (jsonSchema.primaryKey as CompositePrimaryKey).fields\n .forEach(field => ret.push(field as string));\n }\n\n return ret;\n}\n\n/**\n * fills all unset fields with default-values if set\n * @hotPath\n */\nexport function fillObjectWithDefaults(rxSchema: RxSchema, obj: any): any {\n const defaultKeys = Object.keys(rxSchema.defaultValues);\n for (let i = 0; i < defaultKeys.length; ++i) {\n const key = defaultKeys[i];\n if (!Object.prototype.hasOwnProperty.call(obj, key) || typeof obj[key] === 'undefined') {\n obj[key] = rxSchema.defaultValues[key];\n }\n }\n return obj;\n}\n\nexport const DEFAULT_CHECKPOINT_SCHEMA: DeepReadonly> = {\n type: 'object',\n properties: {\n id: {\n type: 'string'\n },\n lwt: {\n type: 'number'\n }\n },\n required: [\n 'id',\n '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AAMpE,GAAG,GAAGkE,WAAW,CAACE,CAAC,CAAC;IAC1B,IAAI,CAAClD,MAAM,CAACC,SAAS,CAACC,cAAc,CAACC,IAAI,CAAC4C,GAAG,EAAEjE,GAAG,CAAC,IAAI,OAAOiE,GAAG,CAACjE,GAAG,CAAC,KAAK,WAAW,EAAE;MACpFiE,GAAG,CAACjE,GAAG,CAAC,GAAGgE,QAAQ,CAACG,aAAa,CAACnE,GAAG,CAAC;IAC1C;EACJ;EACA,OAAOiE,GAAG;AACd;AAEO,IAAMI,yBAA+E,GAAAf,OAAA,CAAAe,yBAAA,GAAG;EAC3F9F,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACR8F,EAAE,EAAE;MACA/F,IAAI,EAAE;IACV,CAAC;IACDgF,GAAG,EAAE;MACDhF,IAAI,EAAE;IACV;EACJ,CAAC;EACDI,QAAQ,EAAE,CACN,IAAI,EACJ,KAAK,CACR;EACDsC,oBAAoB,EAAE;AAC1B,CAAU"} \ No newline at end of file diff --git a/dist/cjs/rx-storage-helper.js b/dist/cjs/rx-storage-helper.js index ba1e2ec4228..4a42c4ec2e8 100644 --- a/dist/cjs/rx-storage-helper.js +++ b/dist/cjs/rx-storage-helper.js @@ -10,6 +10,7 @@ exports.ensureRxStorageInstanceParamsAreCorrect = ensureRxStorageInstanceParamsA exports.flatCloneDocWithMeta = flatCloneDocWithMeta; exports.getAttachmentSize = getAttachmentSize; exports.getChangedDocumentsSince = getChangedDocumentsSince; +exports.getChangedDocumentsSinceQuery = getChangedDocumentsSinceQuery; exports.getSingleDocument = getSingleDocument; exports.getWrappedStorageInstance = getWrappedStorageInstance; exports.hasEncryption = hasEncryption; @@ -27,6 +28,7 @@ var _rxSchemaHelper = require("./rx-schema-helper.js"); var _index = require("./plugins/utils/index.js"); var _rxjs = require("rxjs"); var _rxQuery = require("./rx-query.js"); +var _rxQueryHelper = require("./rx-query-helper.js"); /** * Helper functions for accessing the RxStorage instances. */ @@ -657,14 +659,11 @@ function hasEncryption(jsonSchema) { return false; } } -async function getChangedDocumentsSince(storageInstance, limit, checkpoint) { - if (storageInstance.getChangedDocumentsSince) { - return storageInstance.getChangedDocumentsSince(limit, checkpoint); - } +function getChangedDocumentsSinceQuery(storageInstance, limit, checkpoint) { var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(storageInstance.schema.primaryKey); var sinceLwt = checkpoint ? checkpoint.lwt : _index.RX_META_LWT_MINIMUM; var sinceId = checkpoint ? checkpoint.id : ''; - var query = (0, _rxQuery.prepareQuery)(storageInstance.schema, { + return (0, _rxQueryHelper.normalizeMangoQuery)(storageInstance.schema, { selector: { $or: [{ '_meta.lwt': { @@ -689,9 +688,23 @@ async function getChangedDocumentsSince(storageInstance, limit, checkpoint) { [primaryPath]: 'asc' }], skip: 0, - limit, - index: ['_meta.lwt', primaryPath] + limit + /** + * DO NOT SET A SPECIFIC INDEX HERE! + * The query might be modified by some plugin + * before sending it to the storage. + * We can be sure that in the end the query planner + * will find the best index. + */ + // index: ['_meta.lwt', primaryPath] }); +} +async function getChangedDocumentsSince(storageInstance, limit, checkpoint) { + if (storageInstance.getChangedDocumentsSince) { + return storageInstance.getChangedDocumentsSince(limit, checkpoint); + } + var primaryPath = (0, _rxSchemaHelper.getPrimaryFieldOfPrimaryKey)(storageInstance.schema.primaryKey); + var query = (0, _rxQuery.prepareQuery)(storageInstance.schema, getChangedDocumentsSinceQuery(storageInstance, limit, checkpoint)); var result = await storageInstance.query(query); var documents = result.documents; var lastDoc = (0, _index.lastOfArray)(documents); diff --git a/dist/cjs/rx-storage-helper.js.map b/dist/cjs/rx-storage-helper.js.map index ba5c7cf1c78..4138229bacc 100644 --- a/dist/cjs/rx-storage-helper.js.map +++ b/dist/cjs/rx-storage-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-helper.js","names":["_overwritable","require","_rxError","_rxSchemaHelper","_index","_rxjs","_rxQuery","INTERNAL_STORAGE_NAME","exports","RX_DATABASE_LOCAL_DOCS_STORAGE_NAME","getSingleDocument","storageInstance","documentId","results","findDocumentsById","doc","undefined","writeSingle","instance","writeRow","context","writeResult","bulkWrite","error","length","ret","success","observeSingle","firstFindPromise","changeStream","pipe","map","evBulk","events","find","ev","filter","Promise","resolve","ensureNotFalsy","documentData","startWith","switchMap","v","stackCheckpoints","checkpoints","Object","assign","storageChangeEventToRxChangeEvent","isLocal","rxStorageChangeEvent","rxCollection","previousDocumentData","collectionName","name","operation","overwritable","deepFreezeWhenDevMode","throwIfIsStorageWriteError","collection","writeData","status","newRxError","id","writeError","data","categorizeBulkWriteRows","primaryPath","docsInDb","bulkWriteRows","onInsert","onUpdate","hasAttachments","schema","attachments","bulkInsertDocs","bulkUpdateDocs","errors","eventBulkId","randomCouchString","eventBulk","checkpoint","startTime","now","endTime","eventBulkEvents","attachmentsAdd","attachmentsRemove","attachmentsUpdate","hasDocsInDb","size","newestRow","rowAmount","_loop","rowId","document","previous","docId","documentDeleted","_deleted","previousDeleted","documentInDb","get","attachmentError","insertedIsDeleted","entries","_attachments","forEach","attachmentId","attachmentData","isError","push","digest","stripAttachmentsDataFromRow","event","stripAttachmentsDataFromDocument","revInDb","_rev","err","updatedRow","keys","previousAttachmentData","newDigest","eventDocumentData","previousEventDocumentData","args","getAttachmentSize","attachmentBase64String","atob","attachmentWriteDataToNormalData","type","useDoc","flatClone","flatCloneDocWithMeta","_meta","getWrappedStorageInstance","database","rxJsonSchema","getPrimaryFieldOfPrimaryKey","primaryKey","transformDocumentDataFromRxDBToRxStorage","isDevMode","fillPrimaryKey","structuredClone","JSON","parse","stringify","metaFieldName","prototype","hasOwnProperty","call","dataBefore","dataAfter","lwt","createRevision","token","originalStorageInstance","internals","databaseName","options","rows","toStorageWriteRows","row","lockedRun","then","useWriteResult","slice","reInsertErrors","reInserts","subResult","appendToArray","query","preparedQuery","count","ids","deleted","getAttachmentData","getChangedDocumentsSince","limit","cleanup","minDeletedTime","remove","storageInstances","delete","close","conflictResultionTasks","resolveConflictResultionTask","taskSolution","output","isEqual","getDefaultRxDocumentMeta","getDefaultRevision","add","ensureRxStorageInstanceParamsAreCorrect","params","keyCompression","hasEncryption","compression","jsonSchema","encrypted","sinceLwt","RX_META_LWT_MINIMUM","sinceId","prepareQuery","selector","$or","$gt","$eq","$gte","sort","skip","index","result","documents","lastDoc","lastOfArray","randomDelayStorage","input","retStorage","storage","rxdbVersion","RXDB_VERSION","createStorageInstance","promiseWait","delayTimeBefore","delayTimeAfter","writeQueue","PROMISE_RESOLVE_TRUE","a","b","response","c"],"sources":["../../src/rx-storage-helper.ts"],"sourcesContent":["/**\n * Helper functions for accessing the RxStorage instances.\n */\n\nimport { overwritable } from './overwritable.ts';\nimport { newRxError } from './rx-error.ts';\nimport {\n fillPrimaryKey,\n getPrimaryFieldOfPrimaryKey\n} from './rx-schema-helper.ts';\nimport type {\n BulkWriteRow,\n BulkWriteRowProcessed,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorageWriteError,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n StringKeys,\n RxStorageWriteErrorConflict,\n RxStorageWriteErrorAttachment,\n RxStorage,\n RxStorageDefaultCheckpoint\n} from './types/index.d.ts';\nimport {\n PROMISE_RESOLVE_TRUE,\n RXDB_VERSION,\n RX_META_LWT_MINIMUM,\n appendToArray,\n createRevision,\n ensureNotFalsy,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n lastOfArray,\n now,\n promiseWait,\n randomCouchString\n} from './plugins/utils/index.ts';\nimport { Observable, filter, map, startWith, switchMap } from 'rxjs';\nimport { prepareQuery } from './rx-query.ts';\n\nexport const INTERNAL_STORAGE_NAME = '_rxdb_internal';\nexport const RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local';\n\nexport async function getSingleDocument(\n storageInstance: RxStorageInstance,\n documentId: string\n): Promise | undefined> {\n const results = await storageInstance.findDocumentsById([documentId], false);\n const doc = results[0];\n if (doc) {\n return doc;\n } else {\n return undefined;\n }\n}\n\n/**\n * Writes a single document,\n * throws RxStorageBulkWriteError on failure\n */\nexport async function writeSingle(\n instance: RxStorageInstance,\n writeRow: BulkWriteRow,\n context: string\n): Promise> {\n const writeResult = await instance.bulkWrite(\n [writeRow],\n context\n );\n if (writeResult.error.length > 0) {\n const error = writeResult.error[0];\n throw error;\n } else {\n const ret = writeResult.success[0];\n return ret;\n }\n}\n\n/**\n * Observe the plain document data of a single document.\n * Do not forget to unsubscribe.\n */\nexport function observeSingle(\n storageInstance: RxStorageInstance,\n documentId: string\n): Observable> {\n const firstFindPromise = getSingleDocument(storageInstance, documentId);\n const ret = storageInstance\n .changeStream()\n .pipe(\n map(evBulk => evBulk.events.find(ev => ev.documentId === documentId)),\n filter(ev => !!ev),\n map(ev => Promise.resolve(ensureNotFalsy(ev).documentData)),\n startWith(firstFindPromise),\n switchMap(v => v),\n filter(v => !!v)\n ) as any;\n return ret;\n}\n\n\n/**\n * Checkpoints must be stackable over another.\n * This is required form some RxStorage implementations\n * like the sharding plugin, where a checkpoint only represents\n * the document state from some, but not all shards.\n */\nexport function stackCheckpoints(\n checkpoints: CheckpointType[]\n): CheckpointType {\n return Object.assign(\n {},\n ...checkpoints\n );\n}\n\nexport function storageChangeEventToRxChangeEvent(\n isLocal: boolean,\n rxStorageChangeEvent: RxStorageChangeEvent,\n rxCollection?: RxCollection,\n): RxChangeEvent {\n const documentData = rxStorageChangeEvent.documentData;\n const previousDocumentData = rxStorageChangeEvent.previousDocumentData;\n const ret: RxChangeEvent = {\n documentId: rxStorageChangeEvent.documentId,\n collectionName: rxCollection ? rxCollection.name : undefined,\n isLocal,\n operation: rxStorageChangeEvent.operation,\n documentData: overwritable.deepFreezeWhenDevMode(documentData as any),\n previousDocumentData: overwritable.deepFreezeWhenDevMode(previousDocumentData as any)\n };\n return ret;\n}\n\nexport function throwIfIsStorageWriteError(\n collection: RxCollection,\n documentId: string,\n writeData: RxDocumentWriteData | RxDocType,\n error: RxStorageWriteError | undefined\n) {\n if (error) {\n if (error.status === 409) {\n throw newRxError('CONFLICT', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else if (error.status === 422) {\n throw newRxError('VD2', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else {\n throw error;\n }\n }\n}\n\n\n/**\n * Analyzes a list of BulkWriteRows and determines\n * which documents must be inserted, updated or deleted\n * and which events must be emitted and which documents cause a conflict\n * and must not be written.\n * Used as helper inside of some RxStorage implementations.\n * @hotPath The performance of this function is critical\n */\nexport function categorizeBulkWriteRows(\n storageInstance: RxStorageInstance,\n primaryPath: StringKeys,\n /**\n * Current state of the documents\n * inside of the storage. Used to determine\n * which writes cause conflicts.\n * This must be a Map for better performance.\n */\n docsInDb: Map[StringKeys] | string, RxDocumentData>,\n /**\n * The write rows that are passed to\n * RxStorageInstance().bulkWrite().\n */\n bulkWriteRows: BulkWriteRow[],\n context: string,\n /**\n * Used by some storages for better performance.\n * For example when get-by-id and insert/update can run in parallel.\n */\n onInsert?: (docData: RxDocumentData) => void,\n onUpdate?: (docData: RxDocumentData) => void\n): CategorizeBulkWriteRowsOutput {\n const hasAttachments = !!storageInstance.schema.attachments;\n const bulkInsertDocs: BulkWriteRowProcessed[] = [];\n const bulkUpdateDocs: BulkWriteRowProcessed[] = [];\n const errors: RxStorageWriteError[] = [];\n const eventBulkId = randomCouchString(10);\n const eventBulk: EventBulk>, any> = {\n id: eventBulkId,\n events: [],\n checkpoint: null,\n context,\n startTime: now(),\n endTime: 0\n };\n const eventBulkEvents = eventBulk.events;\n\n const attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n digest: string;\n }[] = [];\n const attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n digest: string;\n }[] = [];\n const attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n digest: string;\n }[] = [];\n\n const hasDocsInDb = docsInDb.size > 0;\n let newestRow: BulkWriteRowProcessed | undefined;\n\n /**\n * @performance is really important in this loop!\n */\n const rowAmount = bulkWriteRows.length;\n for (let rowId = 0; rowId < rowAmount; rowId++) {\n const writeRow = bulkWriteRows[rowId];\n\n // use these variables to have less property accesses\n const document = writeRow.document;\n const previous = writeRow.previous;\n const docId = document[primaryPath] as string;\n const documentDeleted = document._deleted;\n const previousDeleted = previous && previous._deleted;\n\n let documentInDb: RxDocumentData | undefined = undefined as any;\n if (hasDocsInDb) {\n documentInDb = docsInDb.get(docId);\n }\n let attachmentError: RxStorageWriteErrorAttachment | undefined;\n\n if (!documentInDb) {\n /**\n * It is possible to insert already deleted documents,\n * this can happen on replication.\n */\n const insertedIsDeleted = documentDeleted ? true : false;\n if (hasAttachments) {\n Object\n .entries(document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n if (\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: docId,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n errors.push(attachmentError);\n } else {\n attachmentsAdd.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as any,\n digest: attachmentData.digest\n });\n }\n });\n }\n if (!attachmentError) {\n if (hasAttachments) {\n bulkInsertDocs.push(stripAttachmentsDataFromRow(writeRow));\n if (onInsert) {\n onInsert(document);\n }\n } else {\n bulkInsertDocs.push(writeRow as any);\n if (onInsert) {\n onInsert(document);\n }\n }\n\n newestRow = writeRow as any;\n }\n\n if (!insertedIsDeleted) {\n const event = {\n documentId: docId,\n operation: 'INSERT' as const,\n documentData: hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any,\n previousDocumentData: hasAttachments && previous ? stripAttachmentsDataFromDocument(previous) : previous as any\n };\n eventBulkEvents.push(event);\n }\n } else {\n // update existing document\n const revInDb: string = documentInDb._rev;\n\n /**\n * Check for conflict\n */\n if (\n (\n !previous\n ) ||\n (\n !!previous &&\n revInDb !== previous._rev\n )\n ) {\n // is conflict error\n const err: RxStorageWriteError = {\n isError: true,\n status: 409,\n documentId: docId,\n writeRow: writeRow,\n documentInDb\n };\n errors.push(err);\n continue;\n }\n\n // handle attachments data\n\n const updatedRow: BulkWriteRowProcessed = hasAttachments ? stripAttachmentsDataFromRow(writeRow) : writeRow as any;\n if (hasAttachments) {\n if (documentDeleted) {\n /**\n * Deleted documents must have cleared all their attachments.\n */\n if (previous) {\n Object\n .keys(previous._attachments)\n .forEach(attachmentId => {\n attachmentsRemove.push({\n documentId: docId,\n attachmentId,\n digest: ensureNotFalsy(previous)._attachments[attachmentId].digest\n });\n });\n }\n } else {\n // first check for errors\n Object\n .entries(document._attachments)\n .find(([attachmentId, attachmentData]) => {\n const previousAttachmentData = previous ? previous._attachments[attachmentId] : undefined;\n if (\n !previousAttachmentData &&\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: docId,\n documentInDb: documentInDb as any,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n }\n return true;\n });\n if (!attachmentError) {\n Object\n .entries(document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n const previousAttachmentData = previous ? previous._attachments[attachmentId] : undefined;\n if (!previousAttachmentData) {\n attachmentsAdd.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as any,\n digest: attachmentData.digest\n });\n } else {\n const newDigest = updatedRow.document._attachments[attachmentId].digest;\n if (\n (attachmentData as RxAttachmentWriteData).data &&\n /**\n * Performance shortcut,\n * do not update the attachment data if it did not change.\n */\n previousAttachmentData.digest !== newDigest\n ) {\n attachmentsUpdate.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as RxAttachmentWriteData,\n digest: attachmentData.digest\n });\n }\n }\n });\n }\n }\n }\n\n if (attachmentError) {\n errors.push(attachmentError);\n } else {\n if (hasAttachments) {\n bulkUpdateDocs.push(stripAttachmentsDataFromRow(updatedRow));\n if (onUpdate) {\n onUpdate(document);\n }\n } else {\n bulkUpdateDocs.push(updatedRow);\n if (onUpdate) {\n onUpdate(document);\n }\n }\n newestRow = updatedRow as any;\n }\n\n let eventDocumentData: RxDocumentData | undefined = null as any;\n let previousEventDocumentData: RxDocumentData | undefined = null as any;\n let operation: 'INSERT' | 'UPDATE' | 'DELETE' = null as any;\n\n if (previousDeleted && !documentDeleted) {\n operation = 'INSERT';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any;\n } else if (previous && !previousDeleted && !documentDeleted) {\n operation = 'UPDATE';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any;\n previousEventDocumentData = previous;\n } else if (documentDeleted) {\n operation = 'DELETE';\n eventDocumentData = ensureNotFalsy(document) as any;\n previousEventDocumentData = previous;\n } else {\n throw newRxError('SNH', { args: { writeRow } });\n }\n\n const event = {\n documentId: docId,\n documentData: eventDocumentData as RxDocumentData,\n previousDocumentData: previousEventDocumentData,\n operation: operation\n };\n eventBulkEvents.push(event);\n }\n }\n\n return {\n bulkInsertDocs,\n bulkUpdateDocs,\n newestRow,\n errors,\n eventBulk,\n attachmentsAdd,\n attachmentsRemove,\n attachmentsUpdate\n };\n}\n\nexport function stripAttachmentsDataFromRow(writeRow: BulkWriteRow): BulkWriteRowProcessed {\n return {\n previous: writeRow.previous,\n document: stripAttachmentsDataFromDocument(writeRow.document)\n };\n}\n\nexport function getAttachmentSize(\n attachmentBase64String: string\n): number {\n return atob(attachmentBase64String).length;\n}\n\n/**\n * Used in custom RxStorage implementations.\n */\nexport function attachmentWriteDataToNormalData(writeData: RxAttachmentData | RxAttachmentWriteData): RxAttachmentData {\n const data = (writeData as RxAttachmentWriteData).data;\n if (!data) {\n return writeData as any;\n }\n const ret: RxAttachmentData = {\n length: getAttachmentSize(data),\n digest: writeData.digest,\n type: writeData.type\n };\n return ret;\n}\n\nexport function stripAttachmentsDataFromDocument(doc: RxDocumentWriteData): RxDocumentData {\n\n if (!doc._attachments || Object.keys(doc._attachments).length === 0) {\n return doc;\n }\n\n const useDoc: RxDocumentData = flatClone(doc) as any;\n useDoc._attachments = {};\n Object\n .entries(doc._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n useDoc._attachments[attachmentId] = attachmentWriteDataToNormalData(attachmentData);\n });\n return useDoc;\n}\n\n/**\n * Flat clone the document data\n * and also the _meta field.\n * Used many times when we want to change the meta\n * during replication etc.\n */\nexport function flatCloneDocWithMeta(\n doc: RxDocumentData\n): RxDocumentData {\n const ret = flatClone(doc);\n ret._meta = flatClone(doc._meta);\n return ret;\n}\n\nexport type WrappedRxStorageInstance = RxStorageInstance & {\n originalStorageInstance: RxStorageInstance;\n};\n\n/**\n * Wraps the normal storageInstance of a RxCollection\n * to ensure that all access is properly using the hooks\n * and other data transformations and also ensure that database.lockedRun()\n * is used properly.\n */\nexport function getWrappedStorageInstance<\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType\n>(\n database: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstance: RxStorageInstance,\n /**\n * The original RxJsonSchema\n * before it was mutated by hooks.\n */\n rxJsonSchema: RxJsonSchema>\n): WrappedRxStorageInstance {\n overwritable.deepFreezeWhenDevMode(rxJsonSchema);\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function transformDocumentDataFromRxDBToRxStorage(\n writeRow: BulkWriteRow\n ) {\n let data = flatClone(writeRow.document);\n data._meta = flatClone(data._meta);\n\n /**\n * Do some checks in dev-mode\n * that would be too performance expensive\n * in production.\n */\n if (overwritable.isDevMode()) {\n // ensure that the primary key has not been changed\n data = fillPrimaryKey(\n primaryPath,\n rxJsonSchema,\n data as any\n );\n\n\n /**\n * Ensure it can be structured cloned\n */\n try {\n /**\n * Notice that structuredClone() is not available\n * in ReactNative, so we test for JSON.stringify() instead\n * @link https://github.com/pubkey/rxdb/issues/5046#issuecomment-1827374498\n */\n if (typeof structuredClone === 'function') {\n structuredClone(writeRow);\n } else {\n JSON.parse(JSON.stringify(writeRow));\n }\n } catch (err) {\n throw newRxError('DOC24', {\n collection: storageInstance.collectionName,\n document: writeRow.document\n });\n }\n\n /**\n * Ensure that the new revision is higher\n * then the previous one\n */\n if (writeRow.previous) {\n // TODO run this in the dev-mode plugin\n // const prev = parseRevision(writeRow.previous._rev);\n // const current = parseRevision(writeRow.document._rev);\n // if (current.height <= prev.height) {\n // throw newRxError('SNH', {\n // dataBefore: writeRow.previous,\n // dataAfter: writeRow.document,\n // args: {\n // prev,\n // current\n // }\n // });\n // }\n }\n\n /**\n * Ensure that _meta fields have been merged\n * and not replaced.\n * This is important so that when one plugin A\n * sets a _meta field and another plugin B does a write\n * to the document, it must be ensured that the\n * field of plugin A was not removed.\n */\n if (writeRow.previous) {\n Object.keys(writeRow.previous._meta)\n .forEach(metaFieldName => {\n if (!Object.prototype.hasOwnProperty.call(writeRow.document._meta, metaFieldName)) {\n throw newRxError('SNH', {\n dataBefore: writeRow.previous,\n dataAfter: writeRow.document\n });\n }\n });\n }\n }\n data._meta.lwt = now();\n\n /**\n * Yes we really want to set the revision here.\n * If you make a plugin that relies on having its own revision\n * stored into the storage, use this.originalStorageInstance.bulkWrite() instead.\n */\n data._rev = createRevision(\n database.token,\n writeRow.previous\n );\n\n return {\n document: data,\n previous: writeRow.previous\n };\n }\n\n const ret: WrappedRxStorageInstance = {\n originalStorageInstance: storageInstance,\n schema: storageInstance.schema,\n internals: storageInstance.internals,\n collectionName: storageInstance.collectionName,\n databaseName: storageInstance.databaseName,\n options: storageInstance.options,\n bulkWrite(\n rows: BulkWriteRow[],\n context: string\n ) {\n const toStorageWriteRows: BulkWriteRow[] = rows\n .map(row => transformDocumentDataFromRxDBToRxStorage(row));\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n toStorageWriteRows,\n context\n )\n )\n /**\n * The RxStorageInstance MUST NOT allow to insert already _deleted documents,\n * without sending the previous document version.\n * But for better developer experience, RxDB does allow to re-insert deleted documents.\n * We do this by automatically fixing the conflict errors for that case\n * by running another bulkWrite() and merging the results.\n * @link https://github.com/pubkey/rxdb/pull/3839\n */\n .then(writeResult => {\n const useWriteResult: typeof writeResult = {\n error: [],\n success: writeResult.success.slice(0)\n };\n const reInsertErrors: RxStorageWriteErrorConflict[] =\n writeResult.error\n .filter((error) => {\n if (\n error.status === 409 &&\n !error.writeRow.previous &&\n !error.writeRow.document._deleted &&\n ensureNotFalsy(error.documentInDb)._deleted\n ) {\n return true;\n }\n useWriteResult.error.push(error);\n return false;\n }) as any;\n if (reInsertErrors.length > 0) {\n const reInserts: BulkWriteRow[] = reInsertErrors\n .map((error) => {\n return {\n previous: error.documentInDb,\n document: Object.assign(\n {},\n error.writeRow.document,\n {\n _rev: createRevision(\n database.token,\n error.documentInDb\n )\n }\n )\n };\n });\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n reInserts,\n context\n )\n ).then(subResult => {\n appendToArray(useWriteResult.error, subResult.error);\n appendToArray(useWriteResult.success, subResult.success);\n return useWriteResult;\n });\n }\n\n return writeResult;\n });\n },\n query(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.query(preparedQuery)\n );\n },\n count(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.count(preparedQuery)\n );\n },\n findDocumentsById(ids, deleted) {\n return database.lockedRun(\n () => storageInstance.findDocumentsById(ids, deleted)\n );\n },\n getAttachmentData(\n documentId: string,\n attachmentId: string,\n digest: string\n ) {\n return database.lockedRun(\n () => storageInstance.getAttachmentData(documentId, attachmentId, digest)\n );\n },\n getChangedDocumentsSince: !storageInstance.getChangedDocumentsSince ? undefined : (limit: number, checkpoint?: any) => {\n return database.lockedRun(\n () => ((storageInstance as any).getChangedDocumentsSince)(ensureNotFalsy(limit), checkpoint)\n );\n },\n cleanup(minDeletedTime: number) {\n return database.lockedRun(\n () => storageInstance.cleanup(minDeletedTime)\n );\n },\n remove() {\n database.storageInstances.delete(ret);\n return database.lockedRun(\n () => storageInstance.remove()\n );\n },\n close() {\n database.storageInstances.delete(ret);\n return database.lockedRun(\n () => storageInstance.close()\n );\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(taskSolution) {\n if (taskSolution.output.isEqual) {\n return storageInstance.resolveConflictResultionTask(taskSolution);\n }\n\n const doc = Object.assign(\n {},\n taskSolution.output.documentData,\n {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n }\n );\n\n const documentData = flatClone(doc);\n delete (documentData as any)._meta;\n delete (documentData as any)._rev;\n delete (documentData as any)._attachments;\n\n return storageInstance.resolveConflictResultionTask({\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData\n }\n });\n }\n };\n\n database.storageInstances.add(ret);\n return ret;\n}\n\n/**\n * Each RxStorage implementation should\n * run this method at the first step of createStorageInstance()\n * to ensure that the configuration is correct.\n */\nexport function ensureRxStorageInstanceParamsAreCorrect(\n params: RxStorageInstanceCreationParams\n) {\n if (params.schema.keyCompression) {\n throw newRxError('UT5', { args: { params } });\n }\n if (hasEncryption(params.schema)) {\n throw newRxError('UT6', { args: { params } });\n }\n if (\n params.schema.attachments &&\n params.schema.attachments.compression\n ) {\n throw newRxError('UT7', { args: { params } });\n }\n}\n\nexport function hasEncryption(jsonSchema: RxJsonSchema): boolean {\n if (\n (!!jsonSchema.encrypted && jsonSchema.encrypted.length > 0) ||\n (jsonSchema.attachments && jsonSchema.attachments.encrypted)\n ) {\n return true;\n } else {\n return false;\n }\n}\n\n\nexport async function getChangedDocumentsSince(\n storageInstance: RxStorageInstance,\n limit: number,\n checkpoint?: CheckpointType\n): Promise<{\n documents: RxDocumentData[];\n /**\n * The checkpoint contains data so that another\n * call to getChangedDocumentsSince() will continue\n * from exactly the last document that was returned before.\n */\n checkpoint: CheckpointType;\n}> {\n if (storageInstance.getChangedDocumentsSince) {\n return storageInstance.getChangedDocumentsSince(limit, checkpoint);\n }\n\n const primaryPath = getPrimaryFieldOfPrimaryKey(storageInstance.schema.primaryKey);\n const sinceLwt = checkpoint ? (checkpoint as unknown as RxStorageDefaultCheckpoint).lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? (checkpoint as unknown as RxStorageDefaultCheckpoint).id : '';\n const query = prepareQuery>(\n storageInstance.schema,\n {\n selector: {\n $or: [\n {\n '_meta.lwt': {\n $gt: sinceLwt\n }\n },\n {\n '_meta.lwt': {\n $eq: sinceLwt\n },\n [primaryPath]: {\n $gt: checkpoint ? sinceId : ''\n }\n }\n ],\n // add this hint for better index usage\n '_meta.lwt': {\n $gte: sinceLwt\n }\n },\n sort: [\n { '_meta.lwt': 'asc' },\n { [primaryPath]: 'asc' }\n ],\n skip: 0,\n limit,\n index: ['_meta.lwt', primaryPath]\n }\n );\n\n const result = await storageInstance.query(query);\n const documents = result.documents;\n const lastDoc = lastOfArray(documents);\n\n return {\n documents: documents,\n checkpoint: lastDoc ? {\n id: (lastDoc as any)[primaryPath],\n lwt: lastDoc._meta.lwt\n } as any : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n}\n\n\n/**\n * Wraps the storage and simluates\n * delays. Mostly used in tests.\n */\nexport function randomDelayStorage(\n input: {\n storage: RxStorage;\n delayTimeBefore: () => number;\n delayTimeAfter: () => number;\n }\n): RxStorage {\n\n const retStorage: RxStorage = {\n name: 'random-delay-' + input.storage.name,\n rxdbVersion: RXDB_VERSION,\n async createStorageInstance(params) {\n await promiseWait(input.delayTimeBefore());\n const storageInstance = await input.storage.createStorageInstance(params);\n await promiseWait(input.delayTimeAfter());\n\n // write still must be processed in order\n let writeQueue: Promise = PROMISE_RESOLVE_TRUE;\n\n return {\n databaseName: storageInstance.databaseName,\n internals: storageInstance.internals,\n options: storageInstance.options,\n schema: storageInstance.schema,\n collectionName: storageInstance.collectionName,\n async bulkWrite(a, b) {\n writeQueue = writeQueue.then(async () => {\n await promiseWait(input.delayTimeBefore());\n const response = await storageInstance.bulkWrite(a, b);\n await promiseWait(input.delayTimeAfter());\n return response;\n });\n const ret = await writeQueue;\n return ret;\n },\n async findDocumentsById(a, b) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.findDocumentsById(a, b);\n await promiseWait(input.delayTimeAfter());\n return ret;\n },\n async query(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.query(a);\n return ret;\n },\n async count(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.count(a);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async getAttachmentData(a, b, c) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.getAttachmentData(a, b, c);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n getChangedDocumentsSince: !storageInstance.getChangedDocumentsSince ? undefined : async (a, b) => {\n await promiseWait(input.delayTimeBefore());\n const ret = await ensureNotFalsy(storageInstance.getChangedDocumentsSince)(a, b);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(a) {\n return storageInstance.resolveConflictResultionTask(a);\n },\n async cleanup(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.cleanup(a);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async close() {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.close();\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async remove() {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.remove();\n await promiseWait(input.delayTimeAfter());\n return ret;\n },\n };\n\n\n }\n };\n return retStorage;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAIA,IAAAA,aAAA,GAAAC,OAAA;AACA,IAAAC,QAAA,GAAAD,OAAA;AACA,IAAAE,eAAA,GAAAF,OAAA;AA2BA,IAAAG,MAAA,GAAAH,OAAA;AAeA,IAAAI,KAAA,GAAAJ,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AG,GAAG,MAAMd,eAAe,CAAC6K,KAAK,CAAC,CAAC;UACzC,MAAM,IAAAuC,kBAAW,EAACN,KAAK,CAACQ,cAAc,CAAC,CAAC,CAAC;UACzC,OAAOxM,GAAG;QAEd,CAAC;QACD,MAAM4J,MAAMA,CAAA,EAAG;UACX,MAAM,IAAA0C,kBAAW,EAACN,KAAK,CAACO,eAAe,CAAC,CAAC,CAAC;UAC1C,IAAMvM,GAAG,GAAG,MAAMd,eAAe,CAAC0K,MAAM,CAAC,CAAC;UAC1C,MAAM,IAAA0C,kBAAW,EAACN,KAAK,CAACQ,cAAc,CAAC,CAAC,CAAC;UACzC,OAAOxM,GAAG;QACd;MACJ,CAAC;IAGL;EACJ,CAAC;EACD,OAAOiM,UAAU;AACrB"} \ No newline at end of file +{"version":3,"file":"rx-storage-helper.js","names":["_overwritable","require","_rxError","_rxSchemaHelper","_index","_rxjs","_rxQuery","_rxQueryHelper","INTERNAL_STORAGE_NAME","exports","RX_DATABASE_LOCAL_DOCS_STORAGE_NAME","getSingleDocument","storageInstance","documentId","results","findDocumentsById","doc","undefined","writeSingle","instance","writeRow","context","writeResult","bulkWrite","error","length","ret","success","observeSingle","firstFindPromise","changeStream","pipe","map","evBulk","events","find","ev","filter","Promise","resolve","ensureNotFalsy","documentData","startWith","switchMap","v","stackCheckpoints","checkpoints","Object","assign","storageChangeEventToRxChangeEvent","isLocal","rxStorageChangeEvent","rxCollection","previousDocumentData","collectionName","name","operation","overwritable","deepFreezeWhenDevMode","throwIfIsStorageWriteError","collection","writeData","status","newRxError","id","writeError","data","categorizeBulkWriteRows","primaryPath","docsInDb","bulkWriteRows","onInsert","onUpdate","hasAttachments","schema","attachments","bulkInsertDocs","bulkUpdateDocs","errors","eventBulkId","randomCouchString","eventBulk","checkpoint","startTime","now","endTime","eventBulkEvents","attachmentsAdd","attachmentsRemove","attachmentsUpdate","hasDocsInDb","size","newestRow","rowAmount","_loop","rowId","document","previous","docId","documentDeleted","_deleted","previousDeleted","documentInDb","get","attachmentError","insertedIsDeleted","entries","_attachments","forEach","attachmentId","attachmentData","isError","push","digest","stripAttachmentsDataFromRow","event","stripAttachmentsDataFromDocument","revInDb","_rev","err","updatedRow","keys","previousAttachmentData","newDigest","eventDocumentData","previousEventDocumentData","args","getAttachmentSize","attachmentBase64String","atob","attachmentWriteDataToNormalData","type","useDoc","flatClone","flatCloneDocWithMeta","_meta","getWrappedStorageInstance","database","rxJsonSchema","getPrimaryFieldOfPrimaryKey","primaryKey","transformDocumentDataFromRxDBToRxStorage","isDevMode","fillPrimaryKey","structuredClone","JSON","parse","stringify","metaFieldName","prototype","hasOwnProperty","call","dataBefore","dataAfter","lwt","createRevision","token","originalStorageInstance","internals","databaseName","options","rows","toStorageWriteRows","row","lockedRun","then","useWriteResult","slice","reInsertErrors","reInserts","subResult","appendToArray","query","preparedQuery","count","ids","deleted","getAttachmentData","getChangedDocumentsSince","limit","cleanup","minDeletedTime","remove","storageInstances","delete","close","conflictResultionTasks","resolveConflictResultionTask","taskSolution","output","isEqual","getDefaultRxDocumentMeta","getDefaultRevision","add","ensureRxStorageInstanceParamsAreCorrect","params","keyCompression","hasEncryption","compression","jsonSchema","encrypted","getChangedDocumentsSinceQuery","sinceLwt","RX_META_LWT_MINIMUM","sinceId","normalizeMangoQuery","selector","$or","$gt","$eq","$gte","sort","skip","prepareQuery","result","documents","lastDoc","lastOfArray","randomDelayStorage","input","retStorage","storage","rxdbVersion","RXDB_VERSION","createStorageInstance","promiseWait","delayTimeBefore","delayTimeAfter","writeQueue","PROMISE_RESOLVE_TRUE","a","b","response","c"],"sources":["../../src/rx-storage-helper.ts"],"sourcesContent":["/**\n * Helper functions for accessing the RxStorage instances.\n */\n\nimport { overwritable } from './overwritable.ts';\nimport { newRxError } from './rx-error.ts';\nimport {\n fillPrimaryKey,\n getPrimaryFieldOfPrimaryKey\n} from './rx-schema-helper.ts';\nimport type {\n BulkWriteRow,\n BulkWriteRowProcessed,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorageWriteError,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n StringKeys,\n RxStorageWriteErrorConflict,\n RxStorageWriteErrorAttachment,\n RxStorage,\n RxStorageDefaultCheckpoint,\n FilledMangoQuery\n} from './types/index.d.ts';\nimport {\n PROMISE_RESOLVE_TRUE,\n RXDB_VERSION,\n RX_META_LWT_MINIMUM,\n appendToArray,\n createRevision,\n ensureNotFalsy,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n lastOfArray,\n now,\n promiseWait,\n randomCouchString\n} from './plugins/utils/index.ts';\nimport { Observable, filter, map, startWith, switchMap } from 'rxjs';\nimport { prepareQuery } from './rx-query.ts';\nimport { normalizeMangoQuery } from './rx-query-helper.ts';\n\nexport const INTERNAL_STORAGE_NAME = '_rxdb_internal';\nexport const RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local';\n\nexport async function getSingleDocument(\n storageInstance: RxStorageInstance,\n documentId: string\n): Promise | undefined> {\n const results = await storageInstance.findDocumentsById([documentId], false);\n const doc = results[0];\n if (doc) {\n return doc;\n } else {\n return undefined;\n }\n}\n\n/**\n * Writes a single document,\n * throws RxStorageBulkWriteError on failure\n */\nexport async function writeSingle(\n instance: RxStorageInstance,\n writeRow: BulkWriteRow,\n context: string\n): Promise> {\n const writeResult = await instance.bulkWrite(\n [writeRow],\n context\n );\n if (writeResult.error.length > 0) {\n const error = writeResult.error[0];\n throw error;\n } else {\n const ret = writeResult.success[0];\n return ret;\n }\n}\n\n/**\n * Observe the plain document data of a single document.\n * Do not forget to unsubscribe.\n */\nexport function observeSingle(\n storageInstance: RxStorageInstance,\n documentId: string\n): Observable> {\n const firstFindPromise = getSingleDocument(storageInstance, documentId);\n const ret = storageInstance\n .changeStream()\n .pipe(\n map(evBulk => evBulk.events.find(ev => ev.documentId === documentId)),\n filter(ev => !!ev),\n map(ev => Promise.resolve(ensureNotFalsy(ev).documentData)),\n startWith(firstFindPromise),\n switchMap(v => v),\n filter(v => !!v)\n ) as any;\n return ret;\n}\n\n\n/**\n * Checkpoints must be stackable over another.\n * This is required form some RxStorage implementations\n * like the sharding plugin, where a checkpoint only represents\n * the document state from some, but not all shards.\n */\nexport function stackCheckpoints(\n checkpoints: CheckpointType[]\n): CheckpointType {\n return Object.assign(\n {},\n ...checkpoints\n );\n}\n\nexport function storageChangeEventToRxChangeEvent(\n isLocal: boolean,\n rxStorageChangeEvent: RxStorageChangeEvent,\n rxCollection?: RxCollection,\n): RxChangeEvent {\n const documentData = rxStorageChangeEvent.documentData;\n const previousDocumentData = rxStorageChangeEvent.previousDocumentData;\n const ret: RxChangeEvent = {\n documentId: rxStorageChangeEvent.documentId,\n collectionName: rxCollection ? rxCollection.name : undefined,\n isLocal,\n operation: rxStorageChangeEvent.operation,\n documentData: overwritable.deepFreezeWhenDevMode(documentData as any),\n previousDocumentData: overwritable.deepFreezeWhenDevMode(previousDocumentData as any)\n };\n return ret;\n}\n\nexport function throwIfIsStorageWriteError(\n collection: RxCollection,\n documentId: string,\n writeData: RxDocumentWriteData | RxDocType,\n error: RxStorageWriteError | undefined\n) {\n if (error) {\n if (error.status === 409) {\n throw newRxError('CONFLICT', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else if (error.status === 422) {\n throw newRxError('VD2', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else {\n throw error;\n }\n }\n}\n\n\n/**\n * Analyzes a list of BulkWriteRows and determines\n * which documents must be inserted, updated or deleted\n * and which events must be emitted and which documents cause a conflict\n * and must not be written.\n * Used as helper inside of some RxStorage implementations.\n * @hotPath The performance of this function is critical\n */\nexport function categorizeBulkWriteRows(\n storageInstance: RxStorageInstance,\n primaryPath: StringKeys,\n /**\n * Current state of the documents\n * inside of the storage. Used to determine\n * which writes cause conflicts.\n * This must be a Map for better performance.\n */\n docsInDb: Map[StringKeys] | string, RxDocumentData>,\n /**\n * The write rows that are passed to\n * RxStorageInstance().bulkWrite().\n */\n bulkWriteRows: BulkWriteRow[],\n context: string,\n /**\n * Used by some storages for better performance.\n * For example when get-by-id and insert/update can run in parallel.\n */\n onInsert?: (docData: RxDocumentData) => void,\n onUpdate?: (docData: RxDocumentData) => void\n): CategorizeBulkWriteRowsOutput {\n const hasAttachments = !!storageInstance.schema.attachments;\n const bulkInsertDocs: BulkWriteRowProcessed[] = [];\n const bulkUpdateDocs: BulkWriteRowProcessed[] = [];\n const errors: RxStorageWriteError[] = [];\n const eventBulkId = randomCouchString(10);\n const eventBulk: EventBulk>, any> = {\n id: eventBulkId,\n events: [],\n checkpoint: null,\n context,\n startTime: now(),\n endTime: 0\n };\n const eventBulkEvents = eventBulk.events;\n\n const attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n digest: string;\n }[] = [];\n const attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n digest: string;\n }[] = [];\n const attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n digest: string;\n }[] = [];\n\n const hasDocsInDb = docsInDb.size > 0;\n let newestRow: BulkWriteRowProcessed | undefined;\n\n /**\n * @performance is really important in this loop!\n */\n const rowAmount = bulkWriteRows.length;\n for (let rowId = 0; rowId < rowAmount; rowId++) {\n const writeRow = bulkWriteRows[rowId];\n\n // use these variables to have less property accesses\n const document = writeRow.document;\n const previous = writeRow.previous;\n const docId = document[primaryPath] as string;\n const documentDeleted = document._deleted;\n const previousDeleted = previous && previous._deleted;\n\n let documentInDb: RxDocumentData | undefined = undefined as any;\n if (hasDocsInDb) {\n documentInDb = docsInDb.get(docId);\n }\n let attachmentError: RxStorageWriteErrorAttachment | undefined;\n\n if (!documentInDb) {\n /**\n * It is possible to insert already deleted documents,\n * this can happen on replication.\n */\n const insertedIsDeleted = documentDeleted ? true : false;\n if (hasAttachments) {\n Object\n .entries(document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n if (\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: docId,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n errors.push(attachmentError);\n } else {\n attachmentsAdd.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as any,\n digest: attachmentData.digest\n });\n }\n });\n }\n if (!attachmentError) {\n if (hasAttachments) {\n bulkInsertDocs.push(stripAttachmentsDataFromRow(writeRow));\n if (onInsert) {\n onInsert(document);\n }\n } else {\n bulkInsertDocs.push(writeRow as any);\n if (onInsert) {\n onInsert(document);\n }\n }\n\n newestRow = writeRow as any;\n }\n\n if (!insertedIsDeleted) {\n const event = {\n documentId: docId,\n operation: 'INSERT' as const,\n documentData: hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any,\n previousDocumentData: hasAttachments && previous ? stripAttachmentsDataFromDocument(previous) : previous as any\n };\n eventBulkEvents.push(event);\n }\n } else {\n // update existing document\n const revInDb: string = documentInDb._rev;\n\n /**\n * Check for conflict\n */\n if (\n (\n !previous\n ) ||\n (\n !!previous &&\n revInDb !== previous._rev\n )\n ) {\n // is conflict error\n const err: RxStorageWriteError = {\n isError: true,\n status: 409,\n documentId: docId,\n writeRow: writeRow,\n documentInDb\n };\n errors.push(err);\n continue;\n }\n\n // handle attachments data\n\n const updatedRow: BulkWriteRowProcessed = hasAttachments ? stripAttachmentsDataFromRow(writeRow) : writeRow as any;\n if (hasAttachments) {\n if (documentDeleted) {\n /**\n * Deleted documents must have cleared all their attachments.\n */\n if (previous) {\n Object\n .keys(previous._attachments)\n .forEach(attachmentId => {\n attachmentsRemove.push({\n documentId: docId,\n attachmentId,\n digest: ensureNotFalsy(previous)._attachments[attachmentId].digest\n });\n });\n }\n } else {\n // first check for errors\n Object\n .entries(document._attachments)\n .find(([attachmentId, attachmentData]) => {\n const previousAttachmentData = previous ? previous._attachments[attachmentId] : undefined;\n if (\n !previousAttachmentData &&\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: docId,\n documentInDb: documentInDb as any,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n }\n return true;\n });\n if (!attachmentError) {\n Object\n .entries(document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n const previousAttachmentData = previous ? previous._attachments[attachmentId] : undefined;\n if (!previousAttachmentData) {\n attachmentsAdd.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as any,\n digest: attachmentData.digest\n });\n } else {\n const newDigest = updatedRow.document._attachments[attachmentId].digest;\n if (\n (attachmentData as RxAttachmentWriteData).data &&\n /**\n * Performance shortcut,\n * do not update the attachment data if it did not change.\n */\n previousAttachmentData.digest !== newDigest\n ) {\n attachmentsUpdate.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as RxAttachmentWriteData,\n digest: attachmentData.digest\n });\n }\n }\n });\n }\n }\n }\n\n if (attachmentError) {\n errors.push(attachmentError);\n } else {\n if (hasAttachments) {\n bulkUpdateDocs.push(stripAttachmentsDataFromRow(updatedRow));\n if (onUpdate) {\n onUpdate(document);\n }\n } else {\n bulkUpdateDocs.push(updatedRow);\n if (onUpdate) {\n onUpdate(document);\n }\n }\n newestRow = updatedRow as any;\n }\n\n let eventDocumentData: RxDocumentData | undefined = null as any;\n let previousEventDocumentData: RxDocumentData | undefined = null as any;\n let operation: 'INSERT' | 'UPDATE' | 'DELETE' = null as any;\n\n if (previousDeleted && !documentDeleted) {\n operation = 'INSERT';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any;\n } else if (previous && !previousDeleted && !documentDeleted) {\n operation = 'UPDATE';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any;\n previousEventDocumentData = previous;\n } else if (documentDeleted) {\n operation = 'DELETE';\n eventDocumentData = ensureNotFalsy(document) as any;\n previousEventDocumentData = previous;\n } else {\n throw newRxError('SNH', { args: { writeRow } });\n }\n\n const event = {\n documentId: docId,\n documentData: eventDocumentData as RxDocumentData,\n previousDocumentData: previousEventDocumentData,\n operation: operation\n };\n eventBulkEvents.push(event);\n }\n }\n\n return {\n bulkInsertDocs,\n bulkUpdateDocs,\n newestRow,\n errors,\n eventBulk,\n attachmentsAdd,\n attachmentsRemove,\n attachmentsUpdate\n };\n}\n\nexport function stripAttachmentsDataFromRow(writeRow: BulkWriteRow): BulkWriteRowProcessed {\n return {\n previous: writeRow.previous,\n document: stripAttachmentsDataFromDocument(writeRow.document)\n };\n}\n\nexport function getAttachmentSize(\n attachmentBase64String: string\n): number {\n return atob(attachmentBase64String).length;\n}\n\n/**\n * Used in custom RxStorage implementations.\n */\nexport function attachmentWriteDataToNormalData(writeData: RxAttachmentData | RxAttachmentWriteData): RxAttachmentData {\n const data = (writeData as RxAttachmentWriteData).data;\n if (!data) {\n return writeData as any;\n }\n const ret: RxAttachmentData = {\n length: getAttachmentSize(data),\n digest: writeData.digest,\n type: writeData.type\n };\n return ret;\n}\n\nexport function stripAttachmentsDataFromDocument(doc: RxDocumentWriteData): RxDocumentData {\n\n if (!doc._attachments || Object.keys(doc._attachments).length === 0) {\n return doc;\n }\n\n const useDoc: RxDocumentData = flatClone(doc) as any;\n useDoc._attachments = {};\n Object\n .entries(doc._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n useDoc._attachments[attachmentId] = attachmentWriteDataToNormalData(attachmentData);\n });\n return useDoc;\n}\n\n/**\n * Flat clone the document data\n * and also the _meta field.\n * Used many times when we want to change the meta\n * during replication etc.\n */\nexport function flatCloneDocWithMeta(\n doc: RxDocumentData\n): RxDocumentData {\n const ret = flatClone(doc);\n ret._meta = flatClone(doc._meta);\n return ret;\n}\n\nexport type WrappedRxStorageInstance = RxStorageInstance & {\n originalStorageInstance: RxStorageInstance;\n};\n\n/**\n * Wraps the normal storageInstance of a RxCollection\n * to ensure that all access is properly using the hooks\n * and other data transformations and also ensure that database.lockedRun()\n * is used properly.\n */\nexport function getWrappedStorageInstance<\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType\n>(\n database: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstance: RxStorageInstance,\n /**\n * The original RxJsonSchema\n * before it was mutated by hooks.\n */\n rxJsonSchema: RxJsonSchema>\n): WrappedRxStorageInstance {\n overwritable.deepFreezeWhenDevMode(rxJsonSchema);\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function transformDocumentDataFromRxDBToRxStorage(\n writeRow: BulkWriteRow\n ) {\n let data = flatClone(writeRow.document);\n data._meta = flatClone(data._meta);\n\n /**\n * Do some checks in dev-mode\n * that would be too performance expensive\n * in production.\n */\n if (overwritable.isDevMode()) {\n // ensure that the primary key has not been changed\n data = fillPrimaryKey(\n primaryPath,\n rxJsonSchema,\n data as any\n );\n\n\n /**\n * Ensure it can be structured cloned\n */\n try {\n /**\n * Notice that structuredClone() is not available\n * in ReactNative, so we test for JSON.stringify() instead\n * @link https://github.com/pubkey/rxdb/issues/5046#issuecomment-1827374498\n */\n if (typeof structuredClone === 'function') {\n structuredClone(writeRow);\n } else {\n JSON.parse(JSON.stringify(writeRow));\n }\n } catch (err) {\n throw newRxError('DOC24', {\n collection: storageInstance.collectionName,\n document: writeRow.document\n });\n }\n\n /**\n * Ensure that the new revision is higher\n * then the previous one\n */\n if (writeRow.previous) {\n // TODO run this in the dev-mode plugin\n // const prev = parseRevision(writeRow.previous._rev);\n // const current = parseRevision(writeRow.document._rev);\n // if (current.height <= prev.height) {\n // throw newRxError('SNH', {\n // dataBefore: writeRow.previous,\n // dataAfter: writeRow.document,\n // args: {\n // prev,\n // current\n // }\n // });\n // }\n }\n\n /**\n * Ensure that _meta fields have been merged\n * and not replaced.\n * This is important so that when one plugin A\n * sets a _meta field and another plugin B does a write\n * to the document, it must be ensured that the\n * field of plugin A was not removed.\n */\n if (writeRow.previous) {\n Object.keys(writeRow.previous._meta)\n .forEach(metaFieldName => {\n if (!Object.prototype.hasOwnProperty.call(writeRow.document._meta, metaFieldName)) {\n throw newRxError('SNH', {\n dataBefore: writeRow.previous,\n dataAfter: writeRow.document\n });\n }\n });\n }\n }\n data._meta.lwt = now();\n\n /**\n * Yes we really want to set the revision here.\n * If you make a plugin that relies on having its own revision\n * stored into the storage, use this.originalStorageInstance.bulkWrite() instead.\n */\n data._rev = createRevision(\n database.token,\n writeRow.previous\n );\n\n return {\n document: data,\n previous: writeRow.previous\n };\n }\n\n const ret: WrappedRxStorageInstance = {\n originalStorageInstance: storageInstance,\n schema: storageInstance.schema,\n internals: storageInstance.internals,\n collectionName: storageInstance.collectionName,\n databaseName: storageInstance.databaseName,\n options: storageInstance.options,\n bulkWrite(\n rows: BulkWriteRow[],\n context: string\n ) {\n const toStorageWriteRows: BulkWriteRow[] = rows\n .map(row => transformDocumentDataFromRxDBToRxStorage(row));\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n toStorageWriteRows,\n context\n )\n )\n /**\n * The RxStorageInstance MUST NOT allow to insert already _deleted documents,\n * without sending the previous document version.\n * But for better developer experience, RxDB does allow to re-insert deleted documents.\n * We do this by automatically fixing the conflict errors for that case\n * by running another bulkWrite() and merging the results.\n * @link https://github.com/pubkey/rxdb/pull/3839\n */\n .then(writeResult => {\n const useWriteResult: typeof writeResult = {\n error: [],\n success: writeResult.success.slice(0)\n };\n const reInsertErrors: RxStorageWriteErrorConflict[] =\n writeResult.error\n .filter((error) => {\n if (\n error.status === 409 &&\n !error.writeRow.previous &&\n !error.writeRow.document._deleted &&\n ensureNotFalsy(error.documentInDb)._deleted\n ) {\n return true;\n }\n useWriteResult.error.push(error);\n return false;\n }) as any;\n if (reInsertErrors.length > 0) {\n const reInserts: BulkWriteRow[] = reInsertErrors\n .map((error) => {\n return {\n previous: error.documentInDb,\n document: Object.assign(\n {},\n error.writeRow.document,\n {\n _rev: createRevision(\n database.token,\n error.documentInDb\n )\n }\n )\n };\n });\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n reInserts,\n context\n )\n ).then(subResult => {\n appendToArray(useWriteResult.error, subResult.error);\n appendToArray(useWriteResult.success, subResult.success);\n return useWriteResult;\n });\n }\n\n return writeResult;\n });\n },\n query(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.query(preparedQuery)\n );\n },\n count(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.count(preparedQuery)\n );\n },\n findDocumentsById(ids, deleted) {\n return database.lockedRun(\n () => storageInstance.findDocumentsById(ids, deleted)\n );\n },\n getAttachmentData(\n documentId: string,\n attachmentId: string,\n digest: string\n ) {\n return database.lockedRun(\n () => storageInstance.getAttachmentData(documentId, attachmentId, digest)\n );\n },\n getChangedDocumentsSince: !storageInstance.getChangedDocumentsSince ? undefined : (limit: number, checkpoint?: any) => {\n return database.lockedRun(\n () => ((storageInstance as any).getChangedDocumentsSince)(ensureNotFalsy(limit), checkpoint)\n );\n },\n cleanup(minDeletedTime: number) {\n return database.lockedRun(\n () => storageInstance.cleanup(minDeletedTime)\n );\n },\n remove() {\n database.storageInstances.delete(ret);\n return database.lockedRun(\n () => storageInstance.remove()\n );\n },\n close() {\n database.storageInstances.delete(ret);\n return database.lockedRun(\n () => storageInstance.close()\n );\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(taskSolution) {\n if (taskSolution.output.isEqual) {\n return storageInstance.resolveConflictResultionTask(taskSolution);\n }\n\n const doc = Object.assign(\n {},\n taskSolution.output.documentData,\n {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n }\n );\n\n const documentData = flatClone(doc);\n delete (documentData as any)._meta;\n delete (documentData as any)._rev;\n delete (documentData as any)._attachments;\n\n return storageInstance.resolveConflictResultionTask({\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData\n }\n });\n }\n };\n\n database.storageInstances.add(ret);\n return ret;\n}\n\n/**\n * Each RxStorage implementation should\n * run this method at the first step of createStorageInstance()\n * to ensure that the configuration is correct.\n */\nexport function ensureRxStorageInstanceParamsAreCorrect(\n params: RxStorageInstanceCreationParams\n) {\n if (params.schema.keyCompression) {\n throw newRxError('UT5', { args: { params } });\n }\n if (hasEncryption(params.schema)) {\n throw newRxError('UT6', { args: { params } });\n }\n if (\n params.schema.attachments &&\n params.schema.attachments.compression\n ) {\n throw newRxError('UT7', { args: { params } });\n }\n}\n\nexport function hasEncryption(jsonSchema: RxJsonSchema): boolean {\n if (\n (!!jsonSchema.encrypted && jsonSchema.encrypted.length > 0) ||\n (jsonSchema.attachments && jsonSchema.attachments.encrypted)\n ) {\n return true;\n } else {\n return false;\n }\n}\n\nexport function getChangedDocumentsSinceQuery(\n storageInstance: RxStorageInstance,\n limit: number,\n checkpoint?: CheckpointType\n): FilledMangoQuery {\n const primaryPath = getPrimaryFieldOfPrimaryKey(storageInstance.schema.primaryKey);\n const sinceLwt = checkpoint ? (checkpoint as unknown as RxStorageDefaultCheckpoint).lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? (checkpoint as unknown as RxStorageDefaultCheckpoint).id : '';\n return normalizeMangoQuery(storageInstance.schema, {\n selector: {\n $or: [\n {\n '_meta.lwt': {\n $gt: sinceLwt\n }\n },\n {\n '_meta.lwt': {\n $eq: sinceLwt\n },\n [primaryPath]: {\n $gt: checkpoint ? sinceId : ''\n }\n }\n ],\n // add this hint for better index usage\n '_meta.lwt': {\n $gte: sinceLwt\n }\n } as any,\n sort: [\n { '_meta.lwt': 'asc' },\n { [primaryPath]: 'asc' }\n ] as any,\n skip: 0,\n limit,\n /**\n * DO NOT SET A SPECIFIC INDEX HERE!\n * The query might be modified by some plugin\n * before sending it to the storage.\n * We can be sure that in the end the query planner\n * will find the best index.\n */\n // index: ['_meta.lwt', primaryPath]\n });\n}\n\nexport async function getChangedDocumentsSince(\n storageInstance: RxStorageInstance,\n limit: number,\n checkpoint?: CheckpointType\n): Promise<{\n documents: RxDocumentData[];\n /**\n * The checkpoint contains data so that another\n * call to getChangedDocumentsSince() will continue\n * from exactly the last document that was returned before.\n */\n checkpoint: CheckpointType;\n}> {\n if (storageInstance.getChangedDocumentsSince) {\n return storageInstance.getChangedDocumentsSince(limit, checkpoint);\n }\n\n const primaryPath = getPrimaryFieldOfPrimaryKey(storageInstance.schema.primaryKey);\n const query = prepareQuery>(\n storageInstance.schema,\n getChangedDocumentsSinceQuery(\n storageInstance,\n limit,\n checkpoint\n )\n );\n\n const result = await storageInstance.query(query);\n const documents = result.documents;\n const lastDoc = lastOfArray(documents);\n\n return {\n documents: documents,\n checkpoint: lastDoc ? {\n id: (lastDoc as any)[primaryPath],\n lwt: lastDoc._meta.lwt\n } as any : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n}\n\n\n/**\n * Wraps the storage and simluates\n * delays. Mostly used in tests.\n */\nexport function randomDelayStorage(\n input: {\n storage: RxStorage;\n delayTimeBefore: () => number;\n delayTimeAfter: () => number;\n }\n): RxStorage {\n\n const retStorage: RxStorage = {\n name: 'random-delay-' + input.storage.name,\n rxdbVersion: RXDB_VERSION,\n async createStorageInstance(params) {\n await promiseWait(input.delayTimeBefore());\n const storageInstance = await input.storage.createStorageInstance(params);\n await promiseWait(input.delayTimeAfter());\n\n // write still must be processed in order\n let writeQueue: Promise = PROMISE_RESOLVE_TRUE;\n\n return {\n databaseName: storageInstance.databaseName,\n internals: storageInstance.internals,\n options: storageInstance.options,\n schema: storageInstance.schema,\n collectionName: storageInstance.collectionName,\n async bulkWrite(a, b) {\n writeQueue = writeQueue.then(async () => {\n await promiseWait(input.delayTimeBefore());\n const response = await storageInstance.bulkWrite(a, b);\n await promiseWait(input.delayTimeAfter());\n return response;\n });\n const ret = await writeQueue;\n return ret;\n },\n async findDocumentsById(a, b) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.findDocumentsById(a, b);\n await promiseWait(input.delayTimeAfter());\n return ret;\n },\n async query(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.query(a);\n return ret;\n },\n async count(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.count(a);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async getAttachmentData(a, b, c) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.getAttachmentData(a, b, c);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n getChangedDocumentsSince: !storageInstance.getChangedDocumentsSince ? undefined : async (a, b) => {\n await promiseWait(input.delayTimeBefore());\n const ret = await ensureNotFalsy(storageInstance.getChangedDocumentsSince)(a, b);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(a) {\n return storageInstance.resolveConflictResultionTask(a);\n },\n async cleanup(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.cleanup(a);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async close() {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.close();\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async remove() {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.remove();\n await promiseWait(input.delayTimeAfter());\n return ret;\n },\n };\n\n\n }\n };\n return retStorage;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAIA,IAAAA,aAAA,GAAAC,OAAA;AACA,IAAAC,QAAA,GAAAD,OAAA;AACA,IAAAE,eAAA,GAAAF,OAAA;AA4BA,IAAAG,MAAA,GAAAH,OAAA;AAeA,IAAAI,KAAA,GAAAJ,OAAA;AACA,IAAAK,QAAA,GAAAL,OAAA;AACA,IAAAM,cAAA,GAAAN,OAAA;AAnDA;AACA;AACA;;AAmDO,IAAMO,qBAAqB,GAAAC,OAAA,CAAAD,qBAAA,GAAG,gBAAgB;AAC9C,IAAME,mCAAmC,GAAAD,OAAA,CAAAC,mCAAA,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,MAAM+J,KAAKA,CAAA,EAAG;UACV,MAAM,IAAAwC,kBAAW,EAACN,KAAK,CAACO,eAAe,CAAC,CAAC,CAAC;UAC1C,IAAMxM,GAAG,GAAG,MAAMd,eAAe,CAAC6K,KAAK,CAAC,CAAC;UACzC,MAAM,IAAAwC,kBAAW,EAACN,KAAK,CAACQ,cAAc,CAAC,CAAC,CAAC;UACzC,OAAOzM,GAAG;QAEd,CAAC;QACD,MAAM4J,MAAMA,CAAA,EAAG;UACX,MAAM,IAAA2C,kBAAW,EAACN,KAAK,CAACO,eAAe,CAAC,CAAC,CAAC;UAC1C,IAAMxM,GAAG,GAAG,MAAMd,eAAe,CAAC0K,MAAM,CAAC,CAAC;UAC1C,MAAM,IAAA2C,kBAAW,EAACN,KAAK,CAACQ,cAAc,CAAC,CAAC,CAAC;UACzC,OAAOzM,GAAG;QACd;MACJ,CAAC;IAGL;EACJ,CAAC;EACD,OAAOkM,UAAU;AACrB"} \ No newline at end of file diff --git a/dist/cjs/types/rx-error.d.js.map b/dist/cjs/types/rx-error.d.js.map index 8a729cb21c4..4656df08485 100644 --- a/dist/cjs/types/rx-error.d.js.map +++ b/dist/cjs/types/rx-error.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-error.d.js","names":[],"sources":["../../../src/types/rx-error.d.ts"],"sourcesContent":["import type { RxJsonSchema } from './rx-schema.d.ts';\nimport {\n RxSchema\n} from '../rx-schema.ts';\nimport type { RxPlugin } from './rx-plugin.d.ts';\nimport { ERROR_MESSAGES } from '../plugins/dev-mode/error-messages.ts';\nimport type { RxReplicationWriteToMasterRow } from './replication-protocol.d.ts';\nimport type { BulkWriteRow, RxDocumentData } from './rx-storage.d.ts';\n\ntype KeyOf = Extract;\nexport type RxErrorKey = KeyOf;\n\nexport type {\n RxError,\n RxTypeError\n} from '../rx-error.ts';\n\n/**\n * this lists all possible parameters\n */\nexport interface RxErrorParameters {\n readonly error?: PlainJsonError;\n readonly errors?: PlainJsonError[];\n readonly writeError?: RxStorageWriteError;\n readonly schemaPath?: string;\n readonly objPath?: string;\n readonly rootPath?: string;\n readonly childpath?: string;\n readonly obj?: any;\n readonly document?: any;\n readonly schema?: Readonly | RxSchema>;\n readonly schemaObj?: any;\n readonly pluginKey?: string;\n readonly originalDoc?: Readonly;\n readonly finalDoc?: Readonly;\n readonly regex?: string;\n readonly fieldName?: string;\n readonly id?: string;\n readonly data?: any;\n readonly missingCollections?: string[];\n readonly primaryPath?: string;\n readonly primary?: string;\n readonly primaryKey?: string;\n readonly have?: any;\n readonly should?: any;\n readonly name?: string;\n readonly adapter?: any;\n readonly link?: string;\n readonly path?: string;\n readonly value?: any;\n readonly givenName?: string;\n readonly fromVersion?: number;\n readonly toVersion?: number;\n readonly version?: number;\n readonly args?: any;\n readonly opts?: any;\n readonly dataBefore?: any;\n readonly dataAfter?: any;\n readonly pull?: boolean;\n readonly push?: boolean;\n readonly key?: string;\n readonly queryObj?: any;\n readonly query?: any;\n readonly op?: string;\n readonly skip?: any;\n readonly limit?: any;\n readonly passwordHash?: string;\n readonly existingPasswordHash?: string;\n readonly password?: string | any;\n readonly minPassLength?: number;\n readonly own?: any;\n readonly source?: any;\n readonly method?: any;\n readonly field?: string;\n readonly ref?: string;\n readonly funName?: string;\n readonly functionName?: string;\n readonly schemaHash?: string;\n readonly previousSchema?: Readonly>;\n readonly previousSchemaHash?: string;\n readonly type?: string;\n readonly when?: string;\n readonly parallel?: boolean;\n readonly collection?: any;\n readonly database?: any;\n readonly indexes?: Array | Readonly>;\n readonly index?: string | string[] | readonly string[];\n readonly plugin?: RxPlugin | any;\n readonly plugins?: Set;\n\n // used in the replication plugin\n\n /**\n * The checkpoint of the response from the last successful\n * pull by the client.\n * Null if there was no pull operation before\n * so that there is no last pulled checkpoint.\n */\n readonly checkpoint?: any;\n /**\n * The documents that failed to be pushed.\n * Typed as 'any' because they might be modified by the push modifier.\n */\n readonly pushRows?: RxReplicationWriteToMasterRow[];\n readonly direction?: 'pull' | 'push';\n\n}\n\n/**\n * Error-Items which are created by the jsonschema-validator\n */\nexport type RxValidationError = {\n readonly field: string;\n readonly message: string;\n};\n\n/**\n * Use to have a transferable error object\n * in plain json instead of a JavaScript Error instance.\n */\nexport type PlainJsonError = {\n name: string;\n message: string;\n rxdb?: true;\n code?: RxErrorKey;\n parameters?: RxErrorParameters;\n stack?: string;\n};\n\n\n\n\n\n/**\n * Error that can happen per document when\n * RxStorage.bulkWrite() is called\n */\nexport type RxStorageWriteErrorBase = {\n\n status: number\n | 409 // conflict\n | 422 // schema validation error\n | 510 // attachment data missing\n ;\n\n /**\n * set this property to make it easy\n * to detect if the object is a RxStorageBulkWriteError\n */\n isError: true;\n\n // primary key of the document\n documentId: string;\n\n // the original document data that should have been written.\n writeRow: BulkWriteRow;\n};\n\nexport type RxStorageWriteErrorConflict = RxStorageWriteErrorBase & {\n status: 409;\n /**\n * A conflict error state must contain the\n * document state in the database.\n * This ensures that we can continue resolving a conflict\n * without having to pull the document out of the db first.\n * Is not set if the error happens on an insert.\n */\n documentInDb: RxDocumentData;\n};\n\nexport type RxStorageWriteErrorValidation = RxStorageWriteErrorBase & {\n status: 422;\n /**\n * Other properties that give\n * information about the error,\n * for example a schema validation error\n * might contain the exact error from the validator here.\n * Must be plain JSON!\n */\n validationErrors: RxValidationError[];\n};\n\nexport type RxStorageWriteErrorAttachment = RxStorageWriteErrorBase & {\n status: 510;\n attachmentId: string;\n documentInDb?: RxDocumentData;\n};\n\n\nexport type RxStorageWriteError =\n RxStorageWriteErrorConflict |\n RxStorageWriteErrorValidation |\n RxStorageWriteErrorAttachment;\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-error.d.js","names":[],"sources":["../../../src/types/rx-error.d.ts"],"sourcesContent":["import type { RxJsonSchema } from './rx-schema.d.ts';\nimport {\n RxSchema\n} from '../rx-schema.ts';\nimport type { RxPlugin } from './rx-plugin.d.ts';\nimport { ERROR_MESSAGES } from '../plugins/dev-mode/error-messages.ts';\nimport type { RxReplicationWriteToMasterRow } from './replication-protocol.d.ts';\nimport type { BulkWriteRow, RxDocumentData } from './rx-storage.d.ts';\n\ntype KeyOf = Extract;\nexport type RxErrorKey = KeyOf;\n\nexport type {\n RxError,\n RxTypeError\n} from '../rx-error.ts';\n\n/**\n * this lists all possible parameters\n */\nexport interface RxErrorParameters {\n readonly error?: PlainJsonError;\n readonly errors?: PlainJsonError[];\n readonly writeError?: RxStorageWriteError;\n readonly schemaPath?: string;\n readonly objPath?: string;\n readonly rootPath?: string;\n readonly childpath?: string;\n readonly obj?: any;\n readonly document?: any;\n readonly schema?: Readonly | RxSchema>;\n readonly schemaObj?: any;\n readonly pluginKey?: string;\n readonly originalDoc?: Readonly;\n readonly finalDoc?: Readonly;\n readonly regex?: string;\n readonly fieldName?: string;\n readonly id?: string;\n readonly data?: any;\n readonly missingCollections?: string[];\n readonly primaryPath?: string;\n readonly primary?: string;\n readonly primaryKey?: string;\n readonly have?: any;\n readonly should?: any;\n readonly name?: string;\n readonly adapter?: any;\n readonly link?: string;\n readonly path?: string;\n readonly value?: any;\n readonly givenName?: string;\n readonly fromVersion?: number;\n readonly toVersion?: number;\n readonly version?: number;\n readonly args?: any;\n readonly opts?: any;\n readonly dataBefore?: any;\n readonly dataAfter?: any;\n readonly pull?: boolean;\n readonly push?: boolean;\n readonly url?: string;\n readonly key?: string;\n readonly queryObj?: any;\n readonly query?: any;\n readonly op?: string;\n readonly skip?: any;\n readonly limit?: any;\n readonly passwordHash?: string;\n readonly existingPasswordHash?: string;\n readonly password?: string | any;\n readonly minPassLength?: number;\n readonly own?: any;\n readonly source?: any;\n readonly method?: any;\n readonly field?: string;\n readonly ref?: string;\n readonly funName?: string;\n readonly functionName?: string;\n readonly schemaHash?: string;\n readonly previousSchema?: Readonly>;\n readonly previousSchemaHash?: string;\n readonly type?: string;\n readonly when?: string;\n readonly parallel?: boolean;\n readonly collection?: any;\n readonly database?: any;\n readonly indexes?: Array | Readonly>;\n readonly index?: string | string[] | readonly string[];\n readonly plugin?: RxPlugin | any;\n readonly plugins?: Set;\n\n // used in the replication plugin\n\n /**\n * The checkpoint of the response from the last successful\n * pull by the client.\n * Null if there was no pull operation before\n * so that there is no last pulled checkpoint.\n */\n readonly checkpoint?: any;\n /**\n * The documents that failed to be pushed.\n * Typed as 'any' because they might be modified by the push modifier.\n */\n readonly pushRows?: RxReplicationWriteToMasterRow[];\n readonly direction?: 'pull' | 'push';\n\n}\n\n/**\n * Error-Items which are created by the jsonschema-validator\n */\nexport type RxValidationError = {\n readonly field: string;\n readonly message: string;\n};\n\n/**\n * Use to have a transferable error object\n * in plain json instead of a JavaScript Error instance.\n */\nexport type PlainJsonError = {\n name: string;\n message: string;\n rxdb?: true;\n code?: RxErrorKey;\n parameters?: RxErrorParameters;\n stack?: string;\n};\n\n\n\n\n\n/**\n * Error that can happen per document when\n * RxStorage.bulkWrite() is called\n */\nexport type RxStorageWriteErrorBase = {\n\n status: number\n | 409 // conflict\n | 422 // schema validation error\n | 510 // attachment data missing\n ;\n\n /**\n * set this property to make it easy\n * to detect if the object is a RxStorageBulkWriteError\n */\n isError: true;\n\n // primary key of the document\n documentId: string;\n\n // the original document data that should have been written.\n writeRow: BulkWriteRow;\n};\n\nexport type RxStorageWriteErrorConflict = RxStorageWriteErrorBase & {\n status: 409;\n /**\n * A conflict error state must contain the\n * document state in the database.\n * This ensures that we can continue resolving a conflict\n * without having to pull the document out of the db first.\n * Is not set if the error happens on an insert.\n */\n documentInDb: RxDocumentData;\n};\n\nexport type RxStorageWriteErrorValidation = RxStorageWriteErrorBase & {\n status: 422;\n /**\n * Other properties that give\n * information about the error,\n * for example a schema validation error\n * might contain the exact error from the validator here.\n * Must be plain JSON!\n */\n validationErrors: RxValidationError[];\n};\n\nexport type RxStorageWriteErrorAttachment = RxStorageWriteErrorBase & {\n status: 510;\n attachmentId: string;\n documentInDb?: RxDocumentData;\n};\n\n\nexport type RxStorageWriteError =\n RxStorageWriteErrorConflict |\n RxStorageWriteErrorValidation |\n RxStorageWriteErrorAttachment;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/types/rx-schema.d.js.map b/dist/cjs/types/rx-schema.d.js.map index 0373625cb7e..6741008bf55 100644 --- a/dist/cjs/types/rx-schema.d.js.map +++ b/dist/cjs/types/rx-schema.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-schema.d.js","names":[],"sources":["../../../src/types/rx-schema.d.ts"],"sourcesContent":["import { AsTyped } from 'as-typed';\nimport type { CRDTSchemaOptions } from './plugins/crdt.d.ts';\nimport type { StringKeys } from './util.d.ts';\n\n/**\n * @link https://github.com/types/lib-json-schema/blob/master/v4/index.d.ts\n */\nexport type JsonSchemaTypes = 'array' | 'boolean' | 'integer' | 'number' | 'null' | 'object' | 'string' | (string & {});\n\nexport type CompositePrimaryKey = {\n /**\n * The top level field of the document that will be used\n * to store the composite key as string.\n */\n key: StringKeys;\n\n /**\n * The fields of the composite key,\n * the fields must be required and final\n * and have the type number, int, or string.\n */\n fields: (StringKeys | string)[] | readonly (StringKeys | string)[];\n /**\n * The separator which is used to concat the\n * primary fields values.\n * Choose a character as separator that is known\n * to never appear inside of the primary fields values.\n * I recommend to use the pipe char '|'.\n */\n separator: string;\n};\n\nexport type PrimaryKey = StringKeys | CompositePrimaryKey;\n\nexport type JsonSchema = {\n allOf?: JsonSchema[] | readonly JsonSchema[];\n anyOf?: JsonSchema[] | readonly JsonSchema[];\n oneOf?: JsonSchema[] | readonly JsonSchema[];\n additionalItems?: boolean | JsonSchema;\n additionalProperties?: boolean | JsonSchema;\n type?: JsonSchemaTypes | JsonSchemaTypes[] | readonly JsonSchemaTypes[];\n description?: string;\n dependencies?: {\n [key: string]: JsonSchema | string[] | readonly string[];\n };\n exclusiveMinimum?: boolean;\n exclusiveMaximum?: boolean;\n items?: JsonSchema | JsonSchema[] | readonly JsonSchema[];\n multipleOf?: number;\n maxProperties?: number;\n maximum?: number;\n minimum?: number;\n maxLength?: number;\n minLength?: number;\n maxItems?: number;\n minItems?: number;\n minProperties?: number;\n pattern?: string;\n patternProperties?: {\n [key: string]: JsonSchema;\n };\n properties?: {\n [key in StringKeys]: JsonSchema;\n };\n required?: string[] | readonly string[];\n uniqueItems?: boolean;\n enum?: any[] | readonly any[];\n not?: JsonSchema;\n definitions?: {\n [key: string]: JsonSchema;\n };\n format?: 'date-time' | 'email' | 'hostname' | 'ipv4' | 'ipv6' | 'uri' | string;\n example?: any;\n\n // RxDB-specific\n ref?: string;\n final?: boolean;\n};\n\nexport interface TopLevelProperty extends JsonSchema {\n default?: any;\n}\n\n/**\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API\n */\nexport type CompressionMode = 'deflate' | 'gzip';\n\nexport type RxJsonSchema<\n /**\n * The doctype must be given, and '=any' cannot be used,\n * otherwise the keyof of primaryKey\n * would be optional when the type of the document is not known.\n */\n RxDocType\n> = {\n title?: string;\n description?: string;\n version: number;\n\n /**\n * The primary key of the documents.\n * Must be in the top level of the properties of the schema\n * and that property must have the type 'string'\n */\n primaryKey: PrimaryKey;\n\n /**\n * TODO this looks like a typescript-bug\n * we have to allows all string because the 'object'-literal is not recognized\n * retry this in later typescript-versions\n */\n type: 'object' | string;\n properties: { [key in StringKeys]: TopLevelProperty };\n\n /**\n * On the top level the required-array must be set\n * because we always have to set the primary key to required.\n *\n * TODO required should be made non-optional on the top level\n */\n required?: StringKeys[] | readonly StringKeys[];\n\n\n indexes?: (string | string[])[] | (string | readonly string[])[] | readonly (string | string[])[] | readonly (string | readonly string[])[];\n encrypted?: string[] | readonly string[];\n keyCompression?: boolean;\n /**\n * if not set, rxdb will set 'false' as default\n * Having additionalProperties: true is not allowed on the root level to ensure\n * that property names do not clash with properties of the RxDocument class\n * or ORM methods.\n */\n additionalProperties?: false;\n attachments?: {\n encrypted?: boolean;\n /**\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API\n */\n compression?: CompressionMode;\n };\n /**\n * Options for the sharding plugin of rxdb-premium.\n * We set these on the schema because changing the shard amount or mode\n * will require a migration.\n * @link https://rxdb.info/rx-storage-sharding.html\n */\n sharding?: {\n /**\n * Amount of shards.\n * This value cannot be changed after you have stored data,\n * if you change it anyway, you will loose the existing data.\n */\n shards: number;\n /**\n * Either shard by collection or by database.\n * For most use cases (IndexedDB based storages), sharding by collection is the way to go\n * because it has a faster initial load time.\n */\n mode: 'database' | 'collection';\n };\n crdt?: CRDTSchemaOptions;\n};\n\n/**\n * Used to aggregate the document type from the schema.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport type ExtractDocumentTypeFromTypedRxJsonSchema = AsTyped;\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-schema.d.js","names":[],"sources":["../../../src/types/rx-schema.d.ts"],"sourcesContent":["import { AsTyped } from 'as-typed';\nimport type { CRDTSchemaOptions } from './plugins/crdt.d.ts';\nimport type { StringKeys } from './util.d.ts';\n\n/**\n * @link https://github.com/types/lib-json-schema/blob/master/v4/index.d.ts\n */\nexport type JsonSchemaTypes = 'array' | 'boolean' | 'integer' | 'number' | 'null' | 'object' | 'string' | (string & {});\n\nexport type CompositePrimaryKey = {\n /**\n * The top level field of the document that will be used\n * to store the composite key as string.\n */\n key: StringKeys;\n\n /**\n * The fields of the composite key,\n * the fields must be required and final\n * and have the type number, int, or string.\n */\n fields: (StringKeys | string)[] | readonly (StringKeys | string)[];\n /**\n * The separator which is used to concat the\n * primary fields values.\n * Choose a character as separator that is known\n * to never appear inside of the primary fields values.\n * I recommend to use the pipe char '|'.\n */\n separator: string;\n};\n\nexport type PrimaryKey = StringKeys | CompositePrimaryKey;\n\nexport type JsonSchema = {\n allOf?: JsonSchema[] | readonly JsonSchema[];\n anyOf?: JsonSchema[] | readonly JsonSchema[];\n oneOf?: JsonSchema[] | readonly JsonSchema[];\n additionalItems?: boolean | JsonSchema;\n additionalProperties?: boolean | JsonSchema;\n type?: JsonSchemaTypes | JsonSchemaTypes[] | readonly JsonSchemaTypes[];\n description?: string;\n dependencies?: {\n [key: string]: JsonSchema | string[] | readonly string[];\n };\n exclusiveMinimum?: boolean;\n exclusiveMaximum?: boolean;\n items?: JsonSchema | JsonSchema[] | readonly JsonSchema[];\n multipleOf?: number;\n maxProperties?: number;\n maximum?: number;\n minimum?: number;\n maxLength?: number;\n minLength?: number;\n maxItems?: number;\n minItems?: number;\n minProperties?: number;\n pattern?: string;\n patternProperties?: {\n [key: string]: JsonSchema;\n };\n properties?: {\n [key in StringKeys]: JsonSchema;\n };\n required?: string[] | readonly string[];\n uniqueItems?: boolean;\n enum?: any[] | readonly any[];\n not?: JsonSchema;\n definitions?: {\n [key: string]: JsonSchema;\n };\n format?: 'date-time' | 'email' | 'hostname' | 'ipv4' | 'ipv6' | 'uri' | string;\n example?: any;\n\n // RxDB-specific\n ref?: string;\n final?: boolean;\n};\n\nexport interface TopLevelProperty extends JsonSchema {\n default?: any;\n}\n\n/**\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API\n */\nexport type CompressionMode = 'deflate' | 'gzip';\n\nexport type RxJsonSchema<\n /**\n * The doctype must be given, and '=any' cannot be used,\n * otherwise the keyof of primaryKey\n * would be optional when the type of the document is not known.\n */\n RxDocType\n> = {\n title?: string;\n description?: string;\n version: number;\n\n /**\n * The primary key of the documents.\n * Must be in the top level of the properties of the schema\n * and that property must have the type 'string'\n */\n primaryKey: PrimaryKey;\n\n /**\n * TODO this looks like a typescript-bug\n * we have to allows all string because the 'object'-literal is not recognized\n * retry this in later typescript-versions\n */\n type: 'object' | string;\n properties: { [key in StringKeys]: TopLevelProperty };\n\n /**\n * On the top level the required-array must be set\n * because we always have to set the primary key to required.\n *\n * TODO required should be made non-optional on the top level\n */\n required?: StringKeys[] | readonly StringKeys[];\n\n\n /**\n * Indexes that will be used for the queries.\n * RxDB will internally prepend the _deleted field to the index\n * because queries do NOT return documents with _deleted=true.\n */\n indexes?: (string | string[])[] | (string | readonly string[])[] | readonly (string | string[])[] | readonly (string | readonly string[])[];\n\n /**\n * Internally used indexes that do not get _deleted prepended\n * by RxDB. Use these to speed up queries that are run manually on the storage\n * or to speed up requests when you use the RxDB server.\n * These could also be utilised when you build a plugin that\n * has to query documents without respecting the _deleted value.\n */\n internalIndexes?: string[][] | readonly string[][];\n\n\n encrypted?: string[] | readonly string[];\n keyCompression?: boolean;\n /**\n * if not set, rxdb will set 'false' as default\n * Having additionalProperties: true is not allowed on the root level to ensure\n * that property names do not clash with properties of the RxDocument class\n * or ORM methods.\n */\n additionalProperties?: false;\n attachments?: {\n encrypted?: boolean;\n /**\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API\n */\n compression?: CompressionMode;\n };\n /**\n * Options for the sharding plugin of rxdb-premium.\n * We set these on the schema because changing the shard amount or mode\n * will require a migration.\n * @link https://rxdb.info/rx-storage-sharding.html\n */\n sharding?: {\n /**\n * Amount of shards.\n * This value cannot be changed after you have stored data,\n * if you change it anyway, you will loose the existing data.\n */\n shards: number;\n /**\n * Either shard by collection or by database.\n * For most use cases (IndexedDB based storages), sharding by collection is the way to go\n * because it has a faster initial load time.\n */\n mode: 'database' | 'collection';\n };\n crdt?: CRDTSchemaOptions;\n};\n\n/**\n * Used to aggregate the document type from the schema.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport type ExtractDocumentTypeFromTypedRxJsonSchema = AsTyped;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/esm/custom-index.js b/dist/esm/custom-index.js index af0d686f7c3..2ef49c3b315 100644 --- a/dist/esm/custom-index.js +++ b/dist/esm/custom-index.js @@ -173,7 +173,7 @@ export function getStartIndexStringFromLowerBound(schema, index, lowerBound) { var type = schemaPart.type; switch (type) { case 'string': - var maxLength = ensureNotFalsy(schemaPart.maxLength); + var maxLength = ensureNotFalsy(schemaPart.maxLength, 'maxLength not set'); if (typeof bound === 'string') { str += bound.padEnd(maxLength, ' '); } else { @@ -220,7 +220,7 @@ export function getStartIndexStringFromUpperBound(schema, index, upperBound) { var type = schemaPart.type; switch (type) { case 'string': - var maxLength = ensureNotFalsy(schemaPart.maxLength); + var maxLength = ensureNotFalsy(schemaPart.maxLength, 'maxLength not set'); if (typeof bound === 'string' && bound !== INDEX_MAX) { str += bound.padEnd(maxLength, ' '); } else if (bound === INDEX_MIN) { diff --git a/dist/esm/custom-index.js.map b/dist/esm/custom-index.js.map index 5415e3c35e0..c207c1479eb 100644 --- a/dist/esm/custom-index.js.map +++ b/dist/esm/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","getValue","maxLength","getIndexStringPart","docData","fieldValue","padEnd","getNumberIndexString","ret","getIndexableStringMonad","fieldNamePropertiesAmount","length","indexPartsFunctions","r","str","i","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","multipleOfParts","split","decimals","roundedMinimum","getIndexStringLength","forEach","props","getPrimaryKeyFromIndexableString","indexableString","primaryKeyLength","paddedPrimaryKey","slice","primaryKey","trim","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","idx","bound","boolToStr","fillChar","repeat","add","getStartIndexStringFromUpperBound","upperBound","changeIndexableStringByOneQuantum","direction","lastChar","charCode","charCodeAt","withoutLastChar","String","fromCharCode"],"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 * We really often have to craft an index string for a given document.\n * Performance of everything in this file is very important\n * which is why the code sometimes looks strange.\n * Run performance tests before and after you touch anything here!\n */\n\nimport {\n getSchemaByObjectPath\n} from './rx-schema-helper.ts';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types/index.ts';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './plugins/utils/index.ts';\nimport {\n INDEX_MAX,\n INDEX_MIN\n} from './query-planner.ts';\n\n\n/**\n * Prepare all relevant information\n * outside of the returned function\n * from getIndexableStringMonad()\n * to save performance when the returned\n * function is called many times.\n */\ntype IndexMetaField = {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValue: ObjectPathMonadFunction;\n getIndexStringPart: (docData: RxDocumentData) => string;\n};\n\nexport function getIndexMeta(\n schema: RxJsonSchema>,\n index: string[]\n): IndexMetaField[] {\n const fieldNameProperties: IndexMetaField[] = 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 const getValue = objectPathMonad(fieldName);\n const maxLength = schemaPart.maxLength ? schemaPart.maxLength : 0;\n\n let getIndexStringPart: (docData: RxDocumentData) => string;\n if (type === 'string') {\n getIndexStringPart = docData => {\n let fieldValue = getValue(docData);\n if (!fieldValue) {\n fieldValue = '';\n }\n return fieldValue.padEnd(maxLength, ' ');\n };\n } else if (type === 'boolean') {\n getIndexStringPart = docData => {\n const fieldValue = getValue(docData);\n return fieldValue ? '1' : '0';\n };\n } else { // number\n getIndexStringPart = docData => {\n const fieldValue = getValue(docData);\n return getNumberIndexString(\n parsedLengths as any,\n fieldValue\n );\n };\n }\n\n const ret: IndexMetaField = {\n fieldName,\n schemaPart,\n parsedLengths,\n getValue,\n getIndexStringPart\n };\n return ret;\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 const fieldNamePropertiesAmount = fieldNameProperties.length;\n const indexPartsFunctions = fieldNameProperties.map(r => r.getIndexStringPart);\n\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 < fieldNamePropertiesAmount; ++i) {\n str += indexPartsFunctions[i](docData);\n }\n return str;\n };\n return ret;\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 // we can safely trim here because the primary key is not allowed to start or end with a space char.\n const primaryKey = paddedPrimaryKey.trim();\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 const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n let str = nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n if (parsedLengths.decimals > 0) {\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '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): 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 += '0';\n } else if (bound === INDEX_MIN) {\n str += '0';\n } else if (bound === INDEX_MAX) {\n str += '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_MIN) {\n const fillChar = '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else if (bound === INDEX_MAX) {\n str += getNumberIndexString(\n parsedLengths,\n parsedLengths.maximum\n );\n } else {\n const add = getNumberIndexString(\n parsedLengths,\n bound as number\n );\n str += add;\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): 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' && bound !== INDEX_MAX) {\n str += (bound as string).padEnd(maxLength, ' ');\n } else if (bound === INDEX_MIN) {\n str += ''.padEnd(maxLength, ' ');\n } else {\n str += ''.padEnd(maxLength, INDEX_MAX);\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += '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 = '9';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else if (bound === INDEX_MIN) {\n const fillChar = '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\n/**\n * Used in storages where it is not possible\n * to define inclusiveEnd/inclusiveStart\n */\nexport function changeIndexableStringByOneQuantum(str: string, direction: 1 | -1): string {\n const lastChar = str.slice(-1);\n let charCode = lastChar.charCodeAt(0);\n charCode = charCode + direction;\n const withoutLastChar = str.slice(0, -1);\n return withoutLastChar + String.fromCharCode(charCode);\n}\n"],"m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eAAe,GAAGC,MAAM,CAACC,YAAY,CAACJ,QAAQ,CAAC;AAC1D"} \ 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","getValue","maxLength","getIndexStringPart","docData","fieldValue","padEnd","getNumberIndexString","ret","getIndexableStringMonad","fieldNamePropertiesAmount","length","indexPartsFunctions","r","str","i","minimum","Math","floor","maximum","ceil","multipleOf","valueSpan","nonDecimals","toString","multipleOfParts","split","decimals","roundedMinimum","getIndexStringLength","forEach","props","getPrimaryKeyFromIndexableString","indexableString","primaryKeyLength","paddedPrimaryKey","slice","primaryKey","trim","nonDecimalsValueAsString","padStart","splitByDecimalPoint","decimalValueAsString","getStartIndexStringFromLowerBound","lowerBound","idx","bound","boolToStr","fillChar","repeat","add","getStartIndexStringFromUpperBound","upperBound","changeIndexableStringByOneQuantum","direction","lastChar","charCode","charCodeAt","withoutLastChar","String","fromCharCode"],"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 * We really often have to craft an index string for a given document.\n * Performance of everything in this file is very important\n * which is why the code sometimes looks strange.\n * Run performance tests before and after you touch anything here!\n */\n\nimport {\n getSchemaByObjectPath\n} from './rx-schema-helper.ts';\nimport type {\n JsonSchema,\n RxDocumentData,\n RxJsonSchema\n} from './types/index.ts';\nimport {\n ensureNotFalsy,\n objectPathMonad,\n ObjectPathMonadFunction\n} from './plugins/utils/index.ts';\nimport {\n INDEX_MAX,\n INDEX_MIN\n} from './query-planner.ts';\n\n\n/**\n * Prepare all relevant information\n * outside of the returned function\n * from getIndexableStringMonad()\n * to save performance when the returned\n * function is called many times.\n */\ntype IndexMetaField = {\n fieldName: string;\n schemaPart: JsonSchema;\n /*\n * Only in number fields.\n */\n parsedLengths?: ParsedLengths;\n getValue: ObjectPathMonadFunction;\n getIndexStringPart: (docData: RxDocumentData) => string;\n};\n\nexport function getIndexMeta(\n schema: RxJsonSchema>,\n index: string[]\n): IndexMetaField[] {\n const fieldNameProperties: IndexMetaField[] = 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 const getValue = objectPathMonad(fieldName);\n const maxLength = schemaPart.maxLength ? schemaPart.maxLength : 0;\n\n let getIndexStringPart: (docData: RxDocumentData) => string;\n if (type === 'string') {\n getIndexStringPart = docData => {\n let fieldValue = getValue(docData);\n if (!fieldValue) {\n fieldValue = '';\n }\n return fieldValue.padEnd(maxLength, ' ');\n };\n } else if (type === 'boolean') {\n getIndexStringPart = docData => {\n const fieldValue = getValue(docData);\n return fieldValue ? '1' : '0';\n };\n } else { // number\n getIndexStringPart = docData => {\n const fieldValue = getValue(docData);\n return getNumberIndexString(\n parsedLengths as any,\n fieldValue\n );\n };\n }\n\n const ret: IndexMetaField = {\n fieldName,\n schemaPart,\n parsedLengths,\n getValue,\n getIndexStringPart\n };\n return ret;\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 const fieldNamePropertiesAmount = fieldNameProperties.length;\n const indexPartsFunctions = fieldNameProperties.map(r => r.getIndexStringPart);\n\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 < fieldNamePropertiesAmount; ++i) {\n str += indexPartsFunctions[i](docData);\n }\n return str;\n };\n return ret;\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 // we can safely trim here because the primary key is not allowed to start or end with a space char.\n const primaryKey = paddedPrimaryKey.trim();\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 const nonDecimalsValueAsString = (Math.floor(fieldValue) - parsedLengths.roundedMinimum).toString();\n let str = nonDecimalsValueAsString.padStart(parsedLengths.nonDecimals, '0');\n\n if (parsedLengths.decimals > 0) {\n const splitByDecimalPoint = fieldValue.toString().split('.');\n const decimalValueAsString = splitByDecimalPoint.length > 1 ? splitByDecimalPoint[1] : '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): 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, 'maxLength not set');\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 += '0';\n } else if (bound === INDEX_MIN) {\n str += '0';\n } else if (bound === INDEX_MAX) {\n str += '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_MIN) {\n const fillChar = '0';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else if (bound === INDEX_MAX) {\n str += getNumberIndexString(\n parsedLengths,\n parsedLengths.maximum\n );\n } else {\n const add = getNumberIndexString(\n parsedLengths,\n bound as number\n );\n str += add;\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): 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, 'maxLength not set');\n if (typeof bound === 'string' && bound !== INDEX_MAX) {\n str += (bound as string).padEnd(maxLength, ' ');\n } else if (bound === INDEX_MIN) {\n str += ''.padEnd(maxLength, ' ');\n } else {\n str += ''.padEnd(maxLength, INDEX_MAX);\n }\n break;\n case 'boolean':\n if (bound === null) {\n str += '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 = '9';\n str += fillChar.repeat(parsedLengths.nonDecimals + parsedLengths.decimals);\n } else if (bound === INDEX_MIN) {\n const fillChar = '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\n/**\n * Used in storages where it is not possible\n * to define inclusiveEnd/inclusiveStart\n */\nexport function changeIndexableStringByOneQuantum(str: string, direction: 1 | -1): string {\n const lastChar = str.slice(-1);\n let charCode = lastChar.charCodeAt(0);\n charCode = charCode + direction;\n const withoutLastChar = str.slice(0, -1);\n return withoutLastChar + String.fromCharCode(charCode);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SACIA,qBAAqB,QAClB,uBAAuB;AAM9B,SACIC,cAAc,EACdC,eAAe,QAEZ,0BAA0B;AACjC,SACIC,SAAS,EACTC,SAAS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b119d394992..2cfa7cf5d26 100644 --- a/dist/esm/plugins/dev-mode/error-messages.js +++ b/dist/esm/plugins/dev-mode/error-messages.js @@ -151,6 +151,9 @@ export var ERROR_MESSAGES = { RC_WEBRTC_PEER: 'RxReplication WebRTC Peer has error', RC_COUCHDB_1: 'replicateCouchDB() url must end with a slash like \'https://example.com/mydatabase/\'', RC_COUCHDB_2: 'replicateCouchDB() did not get valid result with rows.', + RC_OUTDATED: 'Outdated client, update required. Replication was canceled', + RC_UNAUTHORIZED: 'Unauthorized client, update the replicationState.headers to set correct auth data', + RC_FORBIDDEN: 'Client behaves wrong so the replication was canceled. Mostly happens if the client tries to write data that it is not allowed to', // plugins/dev-mode/check-schema.js SC1: 'fieldnames do not match the regex', SC2: 'SchemaCheck: name \'item\' reserved for array-fields', diff --git a/dist/esm/plugins/dev-mode/error-messages.js.map b/dist/esm/plugins/dev-mode/error-messages.js.map index e424fd80d63..18ed6efeaec 100644 --- a/dist/esm/plugins/dev-mode/error-messages.js.map +++ b/dist/esm/plugins/dev-mode/error-messages.js.map @@ -1 +1 @@ -{"version":3,"file":"error-messages.js","names":["ERROR_MESSAGES","UT1","UT2","UT3","UT4","UT5","UT6","UT7","PL1","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","QU16","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB11","DB12","DB13","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL20","CONFLICT","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DOC20","DOC21","DOC22","DOC23","DOC24","DM1","DM2","DM3","DM4","DM5","AT1","EN1","EN2","EN3","EN4","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC4","RC5","RC6","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_WEBRTC_PEER","RC_COUCHDB_1","RC_COUCHDB_2","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC27","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","SC40","VD1","VD2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n UT7: 'attachments.compression is enabled but no attachment-compression plugin is used',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin.',\n // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importing a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n QU16: '$regex queries must be defined by a string, not an RegExp instance. ' +\n 'This is because RegExp objects cannot be JSON stringified and also they are mutable which would be dangerous',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional',\n // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n DB12: 'RxDatabase.addCollections(): could not write to internal store',\n DB13: 'createRxDatabase(): Invalid db-name or collection name, name contains the dollar sign',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.incrementalUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n COL20: 'Storage write error',\n CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.destroy() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n DOC20: 'PrimaryKey missing',\n DOC21: 'PrimaryKey must be equal to PrimaryKey.trim(). It cannot start or end with a whitespace',\n DOC22: 'PrimaryKey must not contain a linebreak',\n DOC23: 'PrimaryKey must not contain a double-quote [\"]',\n DOC24: 'Given document data could not be structured cloned. This happens if you pass non-plain-json data into it, like a Date() or a Function. ' +\n 'In vue.js this happens if you use ref() on the document data which transforms it into a Proxy object.',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n DM4: 'Migration errored',\n DM5: 'Cannot open database state with newer RxDB version. You have to migrate your database state first. See see https://rxdb.info/migration-storage.html',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption-crypto-js.js\n EN1: 'password is not valid',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n EN4: 'Password not valid',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'replicateCouchDB() query must be from the same RxCollection',\n // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_WEBRTC_PEER: 'RxReplication WebRTC Peer has error',\n RC_COUCHDB_1: 'replicateCouchDB() url must end with a slash like \\'https://example.com/mydatabase/\\'',\n RC_COUCHDB_2: 'replicateCouchDB() did not get valid result with rows.',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n SC40: '$ref fields in the schema are not allowed. RxDB cannot resolve related schemas because it would have a negative performance impact.' +\n 'It would have to run http requests on runtime. $ref fields should be resolved during build time.',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 instead - DEV1: 'dev-mode added multiple times',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/storage-dexie/\n // removed in 15.0.0, added boolean index support to dexie storage - DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAGA,OAAO,IAAMA,cAAc,GAAG;EAC1B;EACAC,GAAG,EAAE,kCAAkC;EACvCC,GAAG,kTAE8F;EACjGC,GAAG,EAAE,yEAAyE;EAC9EC,GAAG,EAAE,qCAAqC;EAC1CC,GAAG,EAAE,mGAAmG;EACxGC,GAAG,EAAE,mFAAmF;EACxFC,GAAG,EAAE,iFAAiF;EAEtF;E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C,IAAI,EAAE,gEAAgE;EACtEC,IAAI,EAAE,iDAAiD;EACvDC,IAAI,EAAE,mDAAmD;EACzDC,IAAI,EAAE,gDAAgD;EACtDC,IAAI,EAAE,uCAAuC;EAC7CC,IAAI,EAAE,mJAAmJ;EACzJC,IAAI,EAAE,yEAAyE;EAC/EC,IAAI,EAAE,uEAAuE;EAC7EC,IAAI,EAAE,+EAA+E;EACrFC,IAAI,EAAE,4DAA4D;EAClEC,IAAI,EAAE,gDAAgD;EACtDC,IAAI,EAAE,qCAAqC;EAC3CC,IAAI,EAAE,qEAAqE;EAC3EC,IAAI,EAAE,+DAA+D;EACrEC,IAAI,EAAE,sGAAsG;EAC5GC,IAAI,EAAE,+GAA+G;EACrHC,IAAI,EAAE,8CAA8C;EACpDC,IAAI,EAAE,gHAAgH;EACtHC,IAAI,EAAE,kFAAkF;EACxFC,IAAI,EAAE,uDAAuD;EAC7DC,IAAI,EAAE,qIAAqI,GACvI,kGAAkG;EAEtG;EACA;;EAEA;EACAC,GAAG,EAAE,kEAAkE;EACvEC,GAAG,EAAE,8BAA8B;EAEnC;EACA;EACA;;EAEA;EACAC,EAAE,EAAE,iEAAiE;EAErE;EACAC,IAAI,EAAE,oDAAoD;EAC1D;EACAC,IAAI,EAAE,iEAAiE;EACvE;;EAEA;EACAC,KAAK,EAAE,oFAAoF;EAC3FC,KAAK,EAAE,yEAAyE;EAChFC,KAAK,EAAE,wGAAwG;EAE/G;EACA;;EAEA;AACJ;AACA;AACA;AACA;EACIC,GAAG,EAAE;AACT,CAAC"} \ No newline at end of file +{"version":3,"file":"error-messages.js","names":["ERROR_MESSAGES","UT1","UT2","UT3","UT4","UT5","UT6","UT7","PL1","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","QU16","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB11","DB12","DB13","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL20","CONFLICT","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DOC20","DOC21","DOC22","DOC23","DOC24","DM1","DM2","DM3","DM4","DM5","AT1","EN1","EN2","EN3","EN4","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC4","RC5","RC6","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_WEBRTC_PEER","RC_COUCHDB_1","RC_COUCHDB_2","RC_OUTDATED","RC_UNAUTHORIZED","RC_FORBIDDEN","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC27","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","SC40","VD1","VD2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n UT7: 'attachments.compression is enabled but no attachment-compression plugin is used',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin.',\n // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importing a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n QU16: '$regex queries must be defined by a string, not an RegExp instance. ' +\n 'This is because RegExp objects cannot be JSON stringified and also they are mutable which would be dangerous',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase.[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://pubkey.github.io/rxdb/questions-answers.html#cant-change-the-schema',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'RxDatabase.create(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional',\n // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n DB12: 'RxDatabase.addCollections(): could not write to internal store',\n DB13: 'createRxDatabase(): Invalid db-name or collection name, name contains the dollar sign',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.incrementalUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n COL20: 'Storage write error',\n CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.destroy() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n DOC20: 'PrimaryKey missing',\n DOC21: 'PrimaryKey must be equal to PrimaryKey.trim(). It cannot start or end with a whitespace',\n DOC22: 'PrimaryKey must not contain a linebreak',\n DOC23: 'PrimaryKey must not contain a double-quote [\"]',\n DOC24: 'Given document data could not be structured cloned. This happens if you pass non-plain-json data into it, like a Date() or a Function. ' +\n 'In vue.js this happens if you use ref() on the document data which transforms it into a Proxy object.',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n DM4: 'Migration errored',\n DM5: 'Cannot open database state with newer RxDB version. You have to migrate your database state first. See see https://rxdb.info/migration-storage.html',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption-crypto-js.js\n EN1: 'password is not valid',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n EN4: 'Password not valid',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'replicateCouchDB() query must be from the same RxCollection',\n // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_WEBRTC_PEER: 'RxReplication WebRTC Peer has error',\n RC_COUCHDB_1: 'replicateCouchDB() url must end with a slash like \\'https://example.com/mydatabase/\\'',\n RC_COUCHDB_2: 'replicateCouchDB() did not get valid result with rows.',\n RC_OUTDATED: 'Outdated client, update required. Replication was canceled',\n RC_UNAUTHORIZED: 'Unauthorized client, update the replicationState.headers to set correct auth data',\n RC_FORBIDDEN: 'Client behaves wrong so the replication was canceled. Mostly happens if the client tries to write data that it is not allowed to',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n SC40: '$ref fields in the schema are not allowed. RxDB cannot resolve related schemas because it would have a negative performance impact.' +\n 'It would have to run http requests on runtime. $ref fields should be resolved during build time.',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 instead - DEV1: 'dev-mode added multiple times',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/storage-dexie/\n // removed in 15.0.0, added boolean index support to dexie storage - DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAGA,OAAO,IAAMA,cAAc,GAAG;EAC1B;EACAC,GAAG,EAAE,kCAAkC;EACvCC,GAAG,kTAE8F;EACjGC,GAAG,EAAE,yEAAyE;EAC9EC,GAAG,EAAE,qCAAqC;EAC1CC,GAAG,EAAE,mGAAmG;EACxGC,GAAG,EAAE,mFAAmF;EACxFC,GAAG,EAAE,iFAAiF;EAEtF;EACAC,GAAG,EAAE,kCAAkC;EACvC;EACAC,GAAG,EAAE,+FAA+F;EAEpG;EACA;EACAC,EAAE,EAAE,kDAAkD;EACtD;;EAEA;EACAC,GAAG,EAAE,2CAA2C;EAChD;EACA;EACAC,GAAG,EAAE,+DAA+D;EACpEC,GAAG,EAAE,wEAAwE;EAC7EC,GAAG,EAAE,iDAAiD;EACtD;EACA;EACAC,GAAG,EAAE,oDAAoD;EACzDC,IAAI,EAAE,uCAAuC;EAC7CC,IAAI,EAAE,sCAAsC;EAC5CC,IAAI,EAAE,8BAA8B;EACpCC,IAAI,EAAE,8DAA8D;EACpEC,IAAI,EAAE,8HAA8H,GAChI,8DAA8D;EAClEC,IAAI,EAAE,0DAA0D;EAChEC,IAAI,EAAE,sEAAsE,GACxE,8GAA8G;EAElH;EACAC,GAAG,EAAE,iCAAiC;EACtCC,GAAG,EAAE,kBAAkB;EACvBC,GAAG,EAAE,6DAA6D;EAClEC,GAAG,EAAE,8DAA8D;EACnEC,GAAG,EAAE,oEAAoE;EACzEC,GAAG,EAAE,gIAAgI;EACrIC,GAAG,EAAE,oBAAoB;EACzBC,GAAG,EAAE,sDAAsD;EAE3D;EACAC,G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vEC,GAAG,EAAE,8BAA8B;EAEnC;EACA;EACA;;EAEA;EACAC,EAAE,EAAE,iEAAiE;EAErE;EACAC,IAAI,EAAE,oDAAoD;EAC1D;EACAC,IAAI,EAAE,iEAAiE;EACvE;;EAEA;EACAC,KAAK,EAAE,oFAAoF;EAC3FC,KAAK,EAAE,yEAAyE;EAChFC,KAAK,EAAE,wGAAwG;EAE/G;EACA;;EAEA;AACJ;AACA;AACA;AACA;EACIC,GAAG,EAAE;AACT,CAAC"} \ No newline at end of file diff --git a/dist/esm/plugins/migration-schema/index.js b/dist/esm/plugins/migration-schema/index.js index 74dc8e698fa..927f8edbd04 100644 --- a/dist/esm/plugins/migration-schema/index.js +++ b/dist/esm/plugins/migration-schema/index.js @@ -6,7 +6,7 @@ import { addRxPlugin } from "../../plugin.js"; import { RxDBLocalDocumentsPlugin } from "../local-documents/index.js"; export var DATA_MIGRATOR_BY_COLLECTION = new WeakMap(); export var RxDBMigrationPlugin = { - name: 'migration', + name: 'migration-schema', rxdb: true, init() { addRxPlugin(RxDBLocalDocumentsPlugin); diff --git a/dist/esm/plugins/migration-schema/index.js.map b/dist/esm/plugins/migration-schema/index.js.map index a02bdddf7a3..18a3594fa0f 100644 --- a/dist/esm/plugins/migration-schema/index.js.map +++ b/dist/esm/plugins/migration-schema/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["shareReplay","getFromMapOrCreate","PROMISE_RESOLVE_FALSE","RXJS_SHARE_REPLAY_DEFAULTS","RxMigrationState","getMigrationStateByDatabase","mustMigrate","onDatabaseDestroy","addRxPlugin","RxDBLocalDocumentsPlugin","DATA_MIGRATOR_BY_COLLECTION","WeakMap","RxDBMigrationPlugin","name","rxdb","init","hooks","preDestroyRxDatabase","after","prototypes","RxDatabase","proto","migrationStates","pipe","RxCollection","getMigrationState","asRxCollection","migrationStrategies","migrationNeeded","schema","version"],"sources":["../../../../src/plugins/migration-schema/index.ts"],"sourcesContent":["import {\n Observable\n} from 'rxjs';\nimport {\n shareReplay\n} from 'rxjs';\nimport type {\n RxPlugin,\n RxCollection,\n RxDatabase\n} from '../../types/index.ts';\nimport {\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS\n} from '../../plugins/utils/index.ts';\nimport {\n RxMigrationState\n} from './rx-migration-state.ts';\nimport {\n getMigrationStateByDatabase,\n mustMigrate,\n onDatabaseDestroy\n} from './migration-helpers.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { RxDBLocalDocumentsPlugin } from '../local-documents/index.ts';\n\nexport const DATA_MIGRATOR_BY_COLLECTION: WeakMap = new WeakMap();\n\nexport const RxDBMigrationPlugin: RxPlugin = {\n name: 'migration',\n rxdb: true,\n init() {\n addRxPlugin(RxDBLocalDocumentsPlugin);\n },\n hooks: {\n preDestroyRxDatabase: {\n after: onDatabaseDestroy\n }\n },\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.migrationStates = function (this: RxDatabase): Observable {\n return getMigrationStateByDatabase(this).pipe(\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n };\n },\n RxCollection: (proto: any) => {\n proto.getMigrationState = function (this: RxCollection): RxMigrationState {\n return getFromMapOrCreate(\n DATA_MIGRATOR_BY_COLLECTION,\n this,\n () => new RxMigrationState(\n this.asRxCollection,\n this.migrationStrategies\n )\n );\n };\n proto.migrationNeeded = function (this: RxCollection) {\n if (this.schema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return mustMigrate(this.getMigrationState());\n };\n }\n }\n};\n\n\nexport * from './rx-migration-state.ts';\nexport * from './migration-helpers.ts';\nexport * from './migration-types.ts';\n"],"mappings":"AAGA,SACIA,WAAW,QACR,MAAM;AAMb,SACIC,kBAAkB,EAClBC,qBAAqB,EACrBC,0BAA0B,QACvB,8BAA8B;AACrC,SACIC,gBAAgB,QACb,yBAAyB;AAChC,SACIC,2BAA2B,EAC3BC,WAAW,EACXC,iBAAiB,QACd,wBAAwB;AAC/B,SAASC,WAAW,QAAQ,iBAAiB;AAC7C,SAASC,wBAAwB,QAAQ,6BAA6B;AAEtE,OAAO,IAAMC,2BAAoE,GAAG,IAAIC,OAAO,CAAC,CAAC;AAEjG,OAAO,IAAMC,mBAA6B,GAAG;EACzCC,IAAI,EAAE,WAAW;EACjBC,IAAI,EAAE,IAAI;EACVC,IAAIA,CAAA,EAAG;IACHP,WAAW,CAACC,wBAAwB,CAAC;EACzC,CAAC;EACDO,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAEX;IACX;EACJ,CAAC;EACDY,UAAU,EAAE;IACRC,UAAU,EAAGC,KAAU,IAAK;MACxBA,KAAK,CAACC,eAAe,GAAG,YAA4D;QAChF,OAAOjB,2BAA2B,CAAC,IAAI,CAAC,CAACkB,IAAI,CACzCvB,WAAW,CAACG,0BAA0B,CAC1C,CAAC;MACL,CAAC;IACL,CAAC;IACDqB,YAAY,EAAGH,KAAU,IAAK;MAC1BA,KAAK,CAACI,iBAAiB,GAAG,YAAgD;QACtE,OAAOxB,kBAAkB,CACrBS,2BAA2B,EAC3B,IAAI,EACJ,MAAM,IAAIN,gBAAgB,CACtB,IAAI,CAACsB,cAAc,EACnB,IAAI,CAACC,mBACT,CACJ,CAAC;MACL,CAAC;MACDN,KAAK,CAACO,eAAe,GAAG,YAA8B;QAClD,IAAI,IAAI,CAACC,MAAM,CAACC,OAAO,KAAK,CAAC,EAAE;UAC3B,OAAO5B,qBAAqB;QAChC;QACA,OAAOI,WAAW,CAAC,IAAI,CAACmB,iBAAiB,CAAC,CAAC,CAAC;MAChD,CAAC;IACL;EACJ;AACJ,CAAC;AAGD,cAAc,yBAAyB;AACvC,cAAc,wBAAwB;AACtC,cAAc,sBAAsB"} \ No newline at end of file +{"version":3,"file":"index.js","names":["shareReplay","getFromMapOrCreate","PROMISE_RESOLVE_FALSE","RXJS_SHARE_REPLAY_DEFAULTS","RxMigrationState","getMigrationStateByDatabase","mustMigrate","onDatabaseDestroy","addRxPlugin","RxDBLocalDocumentsPlugin","DATA_MIGRATOR_BY_COLLECTION","WeakMap","RxDBMigrationPlugin","name","rxdb","init","hooks","preDestroyRxDatabase","after","prototypes","RxDatabase","proto","migrationStates","pipe","RxCollection","getMigrationState","asRxCollection","migrationStrategies","migrationNeeded","schema","version"],"sources":["../../../../src/plugins/migration-schema/index.ts"],"sourcesContent":["import {\n Observable\n} from 'rxjs';\nimport {\n shareReplay\n} from 'rxjs';\nimport type {\n RxPlugin,\n RxCollection,\n RxDatabase\n} from '../../types/index.ts';\nimport {\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n RXJS_SHARE_REPLAY_DEFAULTS\n} from '../../plugins/utils/index.ts';\nimport {\n RxMigrationState\n} from './rx-migration-state.ts';\nimport {\n getMigrationStateByDatabase,\n mustMigrate,\n onDatabaseDestroy\n} from './migration-helpers.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { RxDBLocalDocumentsPlugin } from '../local-documents/index.ts';\n\nexport const DATA_MIGRATOR_BY_COLLECTION: WeakMap = new WeakMap();\n\nexport const RxDBMigrationPlugin: RxPlugin = {\n name: 'migration-schema',\n rxdb: true,\n init() {\n addRxPlugin(RxDBLocalDocumentsPlugin);\n },\n hooks: {\n preDestroyRxDatabase: {\n after: onDatabaseDestroy\n }\n },\n prototypes: {\n RxDatabase: (proto: any) => {\n proto.migrationStates = function (this: RxDatabase): Observable {\n return getMigrationStateByDatabase(this).pipe(\n shareReplay(RXJS_SHARE_REPLAY_DEFAULTS)\n );\n };\n },\n RxCollection: (proto: any) => {\n proto.getMigrationState = function (this: RxCollection): RxMigrationState {\n return getFromMapOrCreate(\n DATA_MIGRATOR_BY_COLLECTION,\n this,\n () => new RxMigrationState(\n this.asRxCollection,\n this.migrationStrategies\n )\n );\n };\n proto.migrationNeeded = function (this: RxCollection) {\n if (this.schema.version === 0) {\n return PROMISE_RESOLVE_FALSE;\n }\n return mustMigrate(this.getMigrationState());\n };\n }\n }\n};\n\n\nexport * from './rx-migration-state.ts';\nexport * from './migration-helpers.ts';\nexport * from './migration-types.ts';\n"],"mappings":"AAGA,SACIA,WAAW,QACR,MAAM;AAMb,SACIC,kBAAkB,EAClBC,qBAAqB,EACrBC,0BAA0B,QACvB,8BAA8B;AACrC,SACIC,gBAAgB,QACb,yBAAyB;AAChC,SACIC,2BAA2B,EAC3BC,WAAW,EACXC,iBAAiB,QACd,wBAAwB;AAC/B,SAASC,WAAW,QAAQ,iBAAiB;AAC7C,SAASC,wBAAwB,QAAQ,6BAA6B;AAEtE,OAAO,IAAMC,2BAAoE,GAAG,IAAIC,OAAO,CAAC,CAAC;AAEjG,OAAO,IAAMC,mBAA6B,GAAG;EACzCC,IAAI,EAAE,kBAAkB;EACxBC,IAAI,EAAE,IAAI;EACVC,IAAIA,CAAA,EAAG;IACHP,WAAW,CAACC,wBAAwB,CAAC;EACzC,CAAC;EACDO,KAAK,EAAE;IACHC,oBAAoB,EAAE;MAClBC,KAAK,EAAEX;IACX;EACJ,CAAC;EACDY,UAAU,EAAE;IACRC,UAAU,EAAGC,KAAU,IAAK;MACxBA,KAAK,CAACC,eAAe,GAAG,YAA4D;QAChF,OAAOjB,2BAA2B,CAAC,IAAI,CAAC,CAACkB,IAAI,CACzCvB,WAAW,CAACG,0BAA0B,CAC1C,CAAC;MACL,CAAC;IACL,CAAC;IACDqB,YAAY,EAAGH,KAAU,IAAK;MAC1BA,KAAK,CAACI,iBAAiB,GAAG,YAAgD;QACtE,OAAOxB,kBAAkB,CACrBS,2BAA2B,EAC3B,IAAI,EACJ,MAAM,IAAIN,gBAAgB,CACtB,IAAI,CAACsB,cAAc,EACnB,IAAI,CAACC,mBACT,CACJ,CAAC;MACL,CAAC;MACDN,KAAK,CAACO,eAAe,GAAG,YAA8B;QAClD,IAAI,IAAI,CAACC,MAAM,CAACC,OAAO,KAAK,CAAC,EAAE;UAC3B,OAAO5B,qBAAqB;QAChC;QACA,OAAOI,WAAW,CAAC,IAAI,CAACmB,iBAAiB,CAAC,CAAC,CAAC;MAChD,CAAC;IACL;EACJ;AACJ,CAAC;AAGD,cAAc,yBAAyB;AACvC,cAAc,wBAAwB;AACtC,cAAc,sBAAsB"} \ No newline at end of file diff --git a/dist/esm/plugins/replication-graphql/index.js b/dist/esm/plugins/replication-graphql/index.js index 97f4a091285..be41306b2b8 100644 --- a/dist/esm/plugins/replication-graphql/index.js +++ b/dist/esm/plugins/replication-graphql/index.js @@ -3,7 +3,7 @@ import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; * this plugin adds the RxCollection.syncGraphQl()-function to rxdb * you can use it to sync collections with a remote graphql endpoint. */ -import { ensureNotFalsy, getProperty } from "../../plugins/utils/index.js"; +import { ensureNotFalsy, flatClone, getProperty } from "../../plugins/utils/index.js"; import { graphQLRequest as _graphQLRequest } from "./helper.js"; import { RxDBLeaderElectionPlugin } from "../leader-election/index.js"; import { RxReplicationState, startReplicationOnLeaderShip } from "../replication/index.js"; @@ -30,7 +30,7 @@ export var RxGraphQLReplicationState = /*#__PURE__*/function (_RxReplicationStat } var _proto = RxGraphQLReplicationState.prototype; _proto.setHeaders = function setHeaders(headers) { - this.clientState.headers = headers; + this.clientState.headers = flatClone(headers); }; _proto.setCredentials = function setCredentials(credentials) { this.clientState.credentials = credentials; diff --git a/dist/esm/plugins/replication-graphql/index.js.map b/dist/esm/plugins/replication-graphql/index.js.map index d40daacc4e5..10958a52997 100644 --- a/dist/esm/plugins/replication-graphql/index.js.map +++ b/dist/esm/plugins/replication-graphql/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["ensureNotFalsy","getProperty","graphQLRequest","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","removeGraphQLWebSocketRef","getGraphQLWebSocket","Subject","RxGraphQLReplicationState","_RxReplicationState","_inheritsLoose","url","clientState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","customFetch","_this","call","_proto","prototype","setHeaders","headers","setCredentials","credentials","queryParams","fetch","http","replicateGraphQL","waitForLeadership","mutateableClientState","pullStream$","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","pullGraphQL","queryBuilder","result","graphqlReplicationState","errors","dataPath","Object","keys","data","responseModifier","docsData","documents","newCheckpoint","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","mustUseSocket","ws","streamQueryBuilder","startBefore","start","bind","httpHeaders","includeWsHeaders","undefined","wsClient","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","isStopped"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport {\n ensureNotFalsy,\n getProperty\n} from '../../plugins/utils/index.ts';\n\nimport {\n graphQLRequest\n} from './helper.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index.ts';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket.ts';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n public readonly customFetch?: WindowOrWorkerGlobalScope['fetch']\n ) {\n super(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: { [k: string]: string; }): void {\n this.clientState.headers = headers;\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n this.customFetch ?? fetch,\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\nexport function replicateGraphQL(\n {\n collection,\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n fetch: customFetch,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n replicationIdentifier\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType | undefined\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = getProperty(result, dataPath);\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = push.dataPath || Object.keys(result.data)[0];\n let data: any = getProperty(result.data, dataPath);\n\n if (push.responseModifier) {\n data = await push.responseModifier(\n data,\n );\n }\n\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n replicationIdentifier,\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart,\n customFetch\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const httpHeaders = pull.includeWsHeaders ? mutateableClientState.headers : undefined;\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws), httpHeaders);\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n if (!graphqlReplicationState.isStopped()) {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper.ts';\nexport * from './graphql-schema-from-rx-schema.ts';\nexport * from './query-builder-from-rx-schema.ts';\nexport * from './graphql-websocket.ts';\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA,SACIA,cAAc,EACdC,WAAW,QACR,8BAA8B;AAErC,SACIC,cAAc,IAAdA,eAAc,QACX,aAAa;AAEpB,SAASC,wBAAwB,QAAQ,6BAA6B;AAWtE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,yBAAyB;AAChC,SACIC,WAAW,QAGR,gBAAgB;AAEvB,SACIC,yBAAyB,EACzBC,mBAAmB,QAChB,wBAAwB;AAC/B,SAASC,OAAO,QAAQ,MAAM;AAK9B,WAAaC,yBAAyB,0BAAAC,mBAAA;EAAAC,cAAA,CAAAF,yBAAA,EAAAC,mBAAA;EAClC,SAAAD,0BACoBG,GAAqB,EACrBC,WAA4C,EAC5CC,qBAA6B,EAC7BC,UAAmC,EACnCC,YAAoB,EACpBC,IAAwD,EACxDC,IAAwC,EACxCC,IAAc,EACvBC,SAAkB,EAClBC,SAAmB,EACVC,WAAgD,EAClE;IAAA,IAAAC,KAAA;IACEA,KAAA,GAAAb,mBAAA,CAAAc,IAAA,OACIV,qBAAqB,EACrBC,UAAU,EACVC,YAAY,EACZC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SACJ,CAAC;IAACE,KAAA,CArBcX,GAAqB,GAArBA,GAAqB;IAAAW,KAAA,CACrBV,WAA4C,GAA5CA,WAA4C;IAAAU,KAAA,CAC5CT,qBAA6B,GAA7BA,qBAA6B;IAAAS,KAAA,CAC7BR,UAAmC,GAAnCA,UAAmC;IAAAQ,KAAA,CACnCP,YAAoB,GAApBA,YAAoB;IAAAO,KAAA,CACpBN,IAAwD,GAAxDA,IAAwD;IAAAM,KAAA,CACxDL,IAAwC,GAAxCA,IAAwC;IAAAK,KAAA,CACxCJ,IAAc,GA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Aa,EAAE;QACfzD,yBAAyB,CAACP,cAAc,CAACa,GAAG,CAACoD,EAAE,CAAC,CAAC;MACrD;IACJ;IACA,OAAOiB,YAAY,CAAC,CAAC;EACzB,CAAC;EAED7E,4BAA4B,CAAC+B,iBAAiB,EAAEW,uBAAuB,CAAC;EACxE,OAAOA,uBAAuB;AAClC;AAEA,cAAc,aAAa;AAC3B,cAAc,oCAAoC;AAClD,cAAc,mCAAmC;AACjD,cAAc,wBAAwB"} \ No newline at end of file +{"version":3,"file":"index.js","names":["ensureNotFalsy","flatClone","getProperty","graphQLRequest","RxDBLeaderElectionPlugin","RxReplicationState","startReplicationOnLeaderShip","addRxPlugin","removeGraphQLWebSocketRef","getGraphQLWebSocket","Subject","RxGraphQLReplicationState","_RxReplicationState","_inheritsLoose","url","clientState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","customFetch","_this","call","_proto","prototype","setHeaders","headers","setCredentials","credentials","queryParams","fetch","http","replicateGraphQL","waitForLeadership","mutateableClientState","pullStream$","replicationPrimitivesPull","pullBatchSize","batchSize","handler","lastPulledCheckpoint","pullGraphQL","queryBuilder","result","graphqlReplicationState","errors","dataPath","Object","keys","data","responseModifier","docsData","documents","newCheckpoint","checkpoint","modifier","stream$","asObservable","replicationPrimitivesPush","rows","pushObj","mustUseSocket","ws","streamQueryBuilder","startBefore","start","bind","httpHeaders","includeWsHeaders","undefined","wsClient","on","next","query","subscribe","streamResponse","firstField","error","complete","cancelBefore","cancel","isStopped"],"sources":["../../../../src/plugins/replication-graphql/index.ts"],"sourcesContent":["/**\n * this plugin adds the RxCollection.syncGraphQl()-function to rxdb\n * you can use it to sync collections with a remote graphql endpoint.\n */\nimport {\n ensureNotFalsy,\n flatClone,\n getProperty\n} from '../../plugins/utils/index.ts';\n\nimport {\n graphQLRequest\n} from './helper.ts';\n\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport type {\n RxCollection,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxReplicationWriteToMasterRow,\n GraphQLServerUrl,\n RxReplicationPullStreamItem,\n RxGraphQLReplicationQueryBuilderResponseObject,\n RxGraphQLReplicationClientState,\n ById\n} from '../../types/index.d.ts';\nimport {\n RxReplicationState,\n startReplicationOnLeaderShip\n} from '../replication/index.ts';\nimport {\n addRxPlugin,\n SyncOptionsGraphQL,\n WithDeleted\n} from '../../index.ts';\n\nimport {\n removeGraphQLWebSocketRef,\n getGraphQLWebSocket\n} from './graphql-websocket.ts';\nimport { Subject } from 'rxjs';\n\n\n\n\nexport class RxGraphQLReplicationState extends RxReplicationState {\n constructor(\n public readonly url: GraphQLServerUrl,\n public readonly clientState: RxGraphQLReplicationClientState,\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n public readonly customFetch?: WindowOrWorkerGlobalScope['fetch']\n ) {\n super(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n }\n\n setHeaders(headers: ById): void {\n this.clientState.headers = flatClone(headers);\n }\n\n setCredentials(credentials: RequestCredentials | undefined) {\n this.clientState.credentials = credentials;\n }\n\n graphQLRequest(\n queryParams: RxGraphQLReplicationQueryBuilderResponseObject\n ) {\n return graphQLRequest(\n this.customFetch ?? fetch,\n ensureNotFalsy(this.url.http),\n this.clientState,\n queryParams\n );\n }\n}\n\nexport function replicateGraphQL(\n {\n collection,\n url,\n headers = {},\n credentials,\n deletedField = '_deleted',\n waitForLeadership = true,\n pull,\n push,\n live = true,\n fetch: customFetch,\n retryTime = 1000 * 5, // in ms\n autoStart = true,\n replicationIdentifier\n }: SyncOptionsGraphQL\n): RxGraphQLReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n /**\n * We use this object to store the GraphQL client\n * so we can later swap out the client inside of the replication handlers.\n */\n const mutateableClientState = {\n headers,\n credentials\n };\n\n\n const pullStream$: Subject> = new Subject();\n\n let replicationPrimitivesPull: ReplicationPullOptions | undefined;\n if (pull) {\n const pullBatchSize = pull.batchSize ? pull.batchSize : 20;\n replicationPrimitivesPull = {\n async handler(\n lastPulledCheckpoint: CheckpointType | undefined\n ) {\n const pullGraphQL = await pull.queryBuilder(lastPulledCheckpoint, pullBatchSize);\n const result = await graphqlReplicationState.graphQLRequest(pullGraphQL);\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = pull.dataPath || ['data', Object.keys(result.data)[0]];\n let data: any = getProperty(result, dataPath);\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'handler',\n lastPulledCheckpoint\n );\n }\n\n const docsData: WithDeleted[] = data.documents;\n const newCheckpoint = data.checkpoint;\n\n return {\n documents: docsData,\n checkpoint: newCheckpoint\n };\n },\n batchSize: pull.batchSize,\n modifier: pull.modifier,\n stream$: pullStream$.asObservable()\n };\n }\n let replicationPrimitivesPush: ReplicationPushOptions | undefined;\n if (push) {\n replicationPrimitivesPush = {\n async handler(\n rows: RxReplicationWriteToMasterRow[]\n ) {\n const pushObj = await push.queryBuilder(rows);\n const result = await graphqlReplicationState.graphQLRequest(pushObj);\n\n if (result.errors) {\n throw result.errors;\n }\n const dataPath = push.dataPath || Object.keys(result.data)[0];\n let data: any = getProperty(result.data, dataPath);\n\n if (push.responseModifier) {\n data = await push.responseModifier(\n data,\n );\n }\n\n return data;\n },\n batchSize: push.batchSize,\n modifier: push.modifier\n };\n }\n\n const graphqlReplicationState = new RxGraphQLReplicationState(\n url,\n mutateableClientState,\n replicationIdentifier,\n collection,\n deletedField,\n replicationPrimitivesPull,\n replicationPrimitivesPush,\n live,\n retryTime,\n autoStart,\n customFetch\n );\n\n const mustUseSocket = url.ws &&\n pull &&\n pull.streamQueryBuilder &&\n live;\n\n const startBefore = graphqlReplicationState.start.bind(graphqlReplicationState);\n graphqlReplicationState.start = () => {\n if (mustUseSocket) {\n const httpHeaders = pull.includeWsHeaders ? mutateableClientState.headers : undefined;\n const wsClient = getGraphQLWebSocket(ensureNotFalsy(url.ws), httpHeaders);\n\n wsClient.on('connected', () => {\n pullStream$.next('RESYNC');\n });\n\n const query: any = ensureNotFalsy(pull.streamQueryBuilder)(mutateableClientState.headers);\n\n wsClient.subscribe(\n query,\n {\n next: async (streamResponse: any) => {\n const firstField = Object.keys(streamResponse.data)[0];\n let data = streamResponse.data[firstField];\n if (pull.responseModifier) {\n data = await pull.responseModifier(\n data,\n 'stream'\n );\n }\n pullStream$.next(data);\n },\n error: (error: any) => {\n pullStream$.error(error);\n },\n complete: () => {\n pullStream$.complete();\n }\n });\n }\n return startBefore();\n };\n\n const cancelBefore = graphqlReplicationState.cancel.bind(graphqlReplicationState);\n graphqlReplicationState.cancel = () => {\n if (!graphqlReplicationState.isStopped()) {\n pullStream$.complete();\n if (mustUseSocket) {\n removeGraphQLWebSocketRef(ensureNotFalsy(url.ws));\n }\n }\n return cancelBefore();\n };\n\n startReplicationOnLeaderShip(waitForLeadership, graphqlReplicationState);\n return graphqlReplicationState;\n}\n\nexport * from './helper.ts';\nexport * from './graphql-schema-from-rx-schema.ts';\nexport * from './query-builder-from-rx-schema.ts';\nexport * from './graphql-websocket.ts';\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA,SACIA,cAAc,EACdC,SAAS,EACTC,WAAW,QACR,8BAA8B;AAErC,SACIC,cAAc,IAAdA,eAAc,QACX,aAAa;AAEpB,SAASC,wBAAwB,QAAQ,6BAA6B;AAYtE,SACIC,kBAAkB,EAClBC,4BAA4B,QACzB,yBAAyB;AAChC,SACIC,WAAW,QAGR,gBAAgB;AAEvB,SACIC,yBAAyB,EACzBC,mBAAmB,QAChB,wBAAwB;AAC/B,SAASC,OAAO,QAAQ,MAAM;AAK9B,WAAaC,yBAAyB,0BAAAC,mBAAA;EAAAC,cAAA,CAAAF,yBAAA,EAAAC,mBAAA;EAClC,SAAAD,0BACoBG,GAAqB,EACrBC,WAA4C,EAC5CC,qBAA6B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ACmC,gBAAgB,EAAE;YACvBD,IAAI,GAAG,MAAMlC,IAAI,CAACmC,gBAAgB,CAC9BD,IAAI,EACJ,QACJ,CAAC;UACL;UACAd,WAAW,CAACqC,IAAI,CAACvB,IAAI,CAAC;QAC1B,CAAC;QACD4B,KAAK,EAAGA,KAAU,IAAK;UACnB1C,WAAW,CAAC0C,KAAK,CAACA,KAAK,CAAC;QAC5B,CAAC;QACDC,QAAQ,EAAEA,CAAA,KAAM;UACZ3C,WAAW,CAAC2C,QAAQ,CAAC,CAAC;QAC1B;MACJ,CAAC,CAAC;IACV;IACA,OAAOd,WAAW,CAAC,CAAC;EACxB,CAAC;EAED,IAAMe,YAAY,GAAGnC,uBAAuB,CAACoC,MAAM,CAACd,IAAI,CAACtB,uBAAuB,CAAC;EACjFA,uBAAuB,CAACoC,MAAM,GAAG,MAAM;IACnC,IAAI,CAACpC,uBAAuB,CAACqC,SAAS,CAAC,CAAC,EAAE;MACtC9C,WAAW,CAAC2C,QAAQ,CAAC,CAAC;MACtB,IAAIjB,aAAa,EAAE;QACfzD,yBAAyB,CAACR,cAAc,CAACc,GAAG,CAACoD,EAAE,CAAC,CAAC;MACrD;IACJ;IACA,OAAOiB,YAAY,CAAC,CAAC;EACzB,CAAC;EAED7E,4BAA4B,CAAC+B,iBAAiB,EAAEW,uBAAuB,CAAC;EACxE,OAAOA,uBAAuB;AAClC;AAEA,cAAc,aAAa;AAC3B,cAAc,oCAAoC;AAClD,cAAc,mCAAmC;AACjD,cAAc,wBAAwB"} \ No newline at end of file diff --git a/dist/esm/plugins/replication-websocket/websocket-client.js b/dist/esm/plugins/replication-websocket/websocket-client.js index a032786195b..abad1100a21 100644 --- a/dist/esm/plugins/replication-websocket/websocket-client.js +++ b/dist/esm/plugins/replication-websocket/websocket-client.js @@ -5,7 +5,7 @@ import { errorToPlainJson, randomCouchString, toArray } from "../../plugins/util import { filter, map, Subject, firstValueFrom, BehaviorSubject } from 'rxjs'; import { newRxError } from "../../rx-error.js"; /** - * Copied and adapter from the 'reconnecting-websocket' npm module. + * Copied and adapted from the 'reconnecting-websocket' npm module. * Some bundlers have problems with bundling the isomorphic-ws plugin * so we directly check the correctness in RxDB to ensure that we can * throw a helpful error. @@ -17,14 +17,34 @@ export function ensureIsWebsocket(w) { throw new Error('websocket not valid'); } } -export async function createWebSocketClient(url) { +export async function createWebSocketClient(options) { ensureIsWebsocket(IsomorphicWebSocket); - var wsClient = new ReconnectingWebSocket(url, [], { + var wsClient = new ReconnectingWebSocket(options.url, [], { WebSocket: IsomorphicWebSocket }); var connected$ = new BehaviorSubject(false); + var message$ = new Subject(); + var error$ = new Subject(); + wsClient.onerror = err => { + console.log('--- WAS CLIENT GOT ERROR:'); + console.log(err.error.message); + var emitError = newRxError('RC_STREAM', { + errors: toArray(err).map(er => errorToPlainJson(er)), + direction: 'pull' + }); + error$.next(emitError); + }; await new Promise(res => { wsClient.onopen = () => { + if (options.headers) { + var authMessage = { + collection: options.collection.name, + id: randomCouchString(10), + params: [options.headers], + method: 'auth' + }; + wsClient.send(JSON.stringify(authMessage)); + } connected$.next(true); res(); }; @@ -32,21 +52,12 @@ export async function createWebSocketClient(url) { wsClient.onclose = () => { connected$.next(false); }; - var message$ = new Subject(); wsClient.onmessage = messageObj => { var message = JSON.parse(messageObj.data); message$.next(message); }; - var error$ = new Subject(); - wsClient.onerror = err => { - var emitError = newRxError('RC_STREAM', { - errors: toArray(err).map(er => errorToPlainJson(er)), - direction: 'pull' - }); - error$.next(emitError); - }; return { - url, + url: options.url, socket: wsClient, connected$, message$, @@ -54,7 +65,7 @@ export async function createWebSocketClient(url) { }; } export async function replicateWithWebsocketServer(options) { - var websocketClient = await createWebSocketClient(options.url); + var websocketClient = await createWebSocketClient(options); var wsClient = websocketClient.socket; var messages$ = websocketClient.message$; var requestCounter = 0; diff --git a/dist/esm/plugins/replication-websocket/websocket-client.js.map b/dist/esm/plugins/replication-websocket/websocket-client.js.map index 91238967a5b..e2e7da5c423 100644 --- a/dist/esm/plugins/replication-websocket/websocket-client.js.map +++ b/dist/esm/plugins/replication-websocket/websocket-client.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-client.js","names":["replicateRxCollection","ReconnectingWebSocket","IsomorphicWebSocket","errorToPlainJson","randomCouchString","toArray","filter","map","Subject","firstValueFrom","BehaviorSubject","newRxError","ensureIsWebsocket","w","is","CLOSING","console","dir","Error","createWebSocketClient","url","wsClient","WebSocket","connected$","Promise","res","onopen","next","onclose","message$","onmessage","messageObj","message","JSON","parse","data","error$","onerror","err","emitError","errors","er","direction","socket","replicateWithWebsocketServer","options","websocketClient","messages$","requestCounter","requestFlag","getRequestId","count","collection","database","token","replicationState","replicationIdentifier","live","pull","batchSize","stream$","pipe","msg","id","name","result","handler","lastPulledCheckpoint","requestId","request","method","params","send","stringify","push","docs","subscribe","subjects","error","isConnected","reSync","streamRequest","onDestroy","close"],"sources":["../../../../src/plugins/replication-websocket/websocket-client.ts"],"sourcesContent":["import {\n replicateRxCollection,\n RxReplicationState\n} from '../replication/index.ts';\nimport {\n WebsocketClientOptions,\n WebsocketMessageType\n} from './websocket-types.ts';\n\nimport ReconnectingWebSocket from 'reconnecting-websocket';\n\nimport IsomorphicWebSocket from 'isomorphic-ws';\nimport {\n errorToPlainJson,\n randomCouchString,\n toArray\n} from '../../plugins/utils/index.ts';\nimport {\n filter,\n map,\n Subject,\n firstValueFrom,\n BehaviorSubject\n} from 'rxjs';\nimport type {\n RxError,\n RxReplicationWriteToMasterRow\n} from '../../types/index.d.ts';\nimport { newRxError } from '../../rx-error.ts';\n\nexport type WebsocketClient = {\n url: string;\n socket: any;\n connected$: BehaviorSubject;\n message$: Subject;\n error$: Subject;\n};\n\n\n/**\n * Copied and adapter from the 'reconnecting-websocket' npm module.\n * Some bundlers have problems with bundling the isomorphic-ws plugin\n * so we directly check the correctness in RxDB to ensure that we can\n * throw a helpful error.\n */\nexport function ensureIsWebsocket(w: typeof IsomorphicWebSocket) {\n const is = typeof w !== 'undefined' && !!w && w.CLOSING === 2;\n if (!is) {\n console.dir(w);\n throw new Error('websocket not valid');\n }\n}\n\n\nexport async function createWebSocketClient(url: string): Promise {\n ensureIsWebsocket(IsomorphicWebSocket);\n const wsClient = new ReconnectingWebSocket(\n url,\n [],\n {\n WebSocket: IsomorphicWebSocket\n }\n );\n\n const connected$ = new BehaviorSubject(false);\n await new Promise(res => {\n wsClient.onopen = () => {\n connected$.next(true);\n res();\n };\n });\n wsClient.onclose = () => {\n connected$.next(false);\n };\n\n const message$ = new Subject();\n wsClient.onmessage = (messageObj) => {\n const message = JSON.parse(messageObj.data);\n message$.next(message);\n };\n\n const error$ = new Subject();\n wsClient.onerror = (err) => {\n const emitError = newRxError('RC_STREAM', {\n errors: toArray(err).map((er: any) => errorToPlainJson(er)),\n direction: 'pull'\n });\n error$.next(emitError);\n };\n\n\n return {\n url,\n socket: wsClient,\n connected$,\n message$,\n error$\n };\n\n}\n\nexport async function replicateWithWebsocketServer(\n options: WebsocketClientOptions\n): Promise> {\n const websocketClient = await createWebSocketClient(options.url);\n const wsClient = websocketClient.socket;\n const messages$ = websocketClient.message$;\n\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return options.collection.database.token + '|' + requestFlag + '|' + count;\n }\n const replicationState = replicateRxCollection({\n collection: options.collection,\n replicationIdentifier: options.replicationIdentifier,\n live: options.live,\n pull: {\n batchSize: options.batchSize,\n stream$: messages$.pipe(\n filter(msg => msg.id === 'stream' && msg.collection === options.collection.name),\n map(msg => msg.result)\n ),\n async handler(lastPulledCheckpoint: CheckpointType | undefined, batchSize: number) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterChangesSince',\n params: [lastPulledCheckpoint, batchSize]\n };\n wsClient.send(JSON.stringify(request));\n const result = await firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n return result;\n }\n },\n push: {\n batchSize: options.batchSize,\n handler(docs: RxReplicationWriteToMasterRow[]) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterWrite',\n params: [docs]\n };\n wsClient.send(JSON.stringify(request));\n return firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n }\n }\n });\n\n websocketClient.error$.subscribe(err => replicationState.subjects.error.next(err));\n\n websocketClient.connected$.subscribe(isConnected => {\n if (isConnected) {\n /**\n * When the client goes offline and online again,\n * we have to send a 'RESYNC' signal because the client\n * might have missed out events while being offline.\n */\n replicationState.reSync();\n\n /**\n * Because reconnecting creates a new websocket-instance,\n * we have to start the changestream from the remote again\n * each time.\n */\n const streamRequest: WebsocketMessageType = {\n id: 'stream',\n collection: options.collection.name,\n method: 'masterChangeStream$',\n params: []\n };\n wsClient.send(JSON.stringify(streamRequest));\n }\n });\n\n options.collection.onDestroy.push(() => websocketClient.socket.close());\n return replicationState;\n}\n"],"mappings":"AAAA,SACIA,qBAAqB,QAElB,yBAAyB;AAMhC,OAAOC,qBAAqB,MAAM,wBAAwB;AAE1D,OAAOC,mBAAmB,MAAM,eAAe;AAC/C,SACIC,gBAAgB,EAChBC,iBAAiB,EACjBC,OAAO,QACJ,8BAA8B;AACrC,SACIC,MAAM,EACNC,GAAG,EACHC,OAAO,EACPC,cAAc,EACdC,eAAe,QACZ,MAAM;AAKb,SAASC,UAAU,QAAQ,mBAAmB;AAW9C;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,iBAAiBA,CAACC,CAA6B,EAAE;EAC7D,IAAMC,EAAE,GAAG,OAAOD,CAAC,KAAK,WAAW,IAAI,CAAC,CAACA,CAAC,IAAIA,CAAC,CAACE,OAAO,KAAK,CAAC;EAC7D,IAAI,CAACD,EAAE,EAAE;IACLE,OAAO,CAACC,GAAG,CAACJ,CAAC,CAAC;IACd,MAAM,IAAIK,KAAK,CAAC,qBAAqB,CAAC;EAC1C;AACJ;AAGA,OAA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;AACA;AACA;AACA;MACY,IAAMC,aAAmC,GAAG;QACxClB,EAAE,EAAE,QAAQ;QACZX,UAAU,EAAEP,OAAO,CAACO,UAAU,CAACY,IAAI;QACnCM,MAAM,EAAE,qBAAqB;QAC7BC,MAAM,EAAE;MACZ,CAAC;MACDlD,QAAQ,CAACmD,IAAI,CAACvC,IAAI,CAACwC,SAAS,CAACQ,aAAa,CAAC,CAAC;IAChD;EACJ,CAAC,CAAC;EAEFpC,OAAO,CAACO,UAAU,CAAC8B,SAAS,CAACR,IAAI,CAAC,MAAM5B,eAAe,CAACH,MAAM,CAACwC,KAAK,CAAC,CAAC,CAAC;EACvE,OAAO5B,gBAAgB;AAC3B"} \ No newline at end of file +{"version":3,"file":"websocket-client.js","names":["replicateRxCollection","ReconnectingWebSocket","IsomorphicWebSocket","errorToPlainJson","randomCouchString","toArray","filter","map","Subject","firstValueFrom","BehaviorSubject","newRxError","ensureIsWebsocket","w","is","CLOSING","console","dir","Error","createWebSocketClient","options","wsClient","url","WebSocket","connected$","message$","error$","onerror","err","log","error","message","emitError","errors","er","direction","next","Promise","res","onopen","headers","authMessage","collection","name","id","params","method","send","JSON","stringify","onclose","onmessage","messageObj","parse","data","socket","replicateWithWebsocketServer","websocketClient","messages$","requestCounter","requestFlag","getRequestId","count","database","token","replicationState","replicationIdentifier","live","pull","batchSize","stream$","pipe","msg","result","handler","lastPulledCheckpoint","requestId","request","push","docs","subscribe","subjects","isConnected","reSync","streamRequest","onDestroy","close"],"sources":["../../../../src/plugins/replication-websocket/websocket-client.ts"],"sourcesContent":["import {\n replicateRxCollection,\n RxReplicationState\n} from '../replication/index.ts';\nimport {\n WebsocketClientOptions,\n WebsocketMessageType\n} from './websocket-types.ts';\n\nimport ReconnectingWebSocket from 'reconnecting-websocket';\n\nimport IsomorphicWebSocket from 'isomorphic-ws';\nimport {\n errorToPlainJson,\n randomCouchString,\n toArray\n} from '../../plugins/utils/index.ts';\nimport {\n filter,\n map,\n Subject,\n firstValueFrom,\n BehaviorSubject\n} from 'rxjs';\nimport type {\n RxError,\n RxReplicationWriteToMasterRow\n} from '../../types/index.d.ts';\nimport { newRxError } from '../../rx-error.ts';\n\nexport type WebsocketClient = {\n url: string;\n socket: any;\n connected$: BehaviorSubject;\n message$: Subject;\n error$: Subject;\n};\n\n\n/**\n * Copied and adapted from the 'reconnecting-websocket' npm module.\n * Some bundlers have problems with bundling the isomorphic-ws plugin\n * so we directly check the correctness in RxDB to ensure that we can\n * throw a helpful error.\n */\nexport function ensureIsWebsocket(w: typeof IsomorphicWebSocket) {\n const is = typeof w !== 'undefined' && !!w && w.CLOSING === 2;\n if (!is) {\n console.dir(w);\n throw new Error('websocket not valid');\n }\n}\n\n\nexport async function createWebSocketClient(options: WebsocketClientOptions): Promise {\n ensureIsWebsocket(IsomorphicWebSocket);\n const wsClient = new ReconnectingWebSocket(\n options.url,\n [],\n {\n WebSocket: IsomorphicWebSocket\n }\n );\n const connected$ = new BehaviorSubject(false);\n const message$ = new Subject();\n const error$ = new Subject();\n wsClient.onerror = (err) => {\n\n console.log('--- WAS CLIENT GOT ERROR:');\n console.log(err.error.message);\n\n const emitError = newRxError('RC_STREAM', {\n errors: toArray(err).map((er: any) => errorToPlainJson(er)),\n direction: 'pull'\n });\n error$.next(emitError);\n };\n await new Promise(res => {\n wsClient.onopen = () => {\n\n if (options.headers) {\n const authMessage: WebsocketMessageType = {\n collection: options.collection.name,\n id: randomCouchString(10),\n params: [options.headers],\n method: 'auth'\n };\n wsClient.send(JSON.stringify(authMessage));\n }\n\n connected$.next(true);\n res();\n };\n });\n wsClient.onclose = () => {\n connected$.next(false);\n };\n\n wsClient.onmessage = (messageObj) => {\n const message = JSON.parse(messageObj.data);\n message$.next(message);\n };\n\n return {\n url: options.url,\n socket: wsClient,\n connected$,\n message$,\n error$\n };\n\n}\n\nexport async function replicateWithWebsocketServer(\n options: WebsocketClientOptions\n): Promise> {\n const websocketClient = await createWebSocketClient(options);\n const wsClient = websocketClient.socket;\n const messages$ = websocketClient.message$;\n\n let requestCounter = 0;\n const requestFlag = randomCouchString(10);\n function getRequestId() {\n const count = requestCounter++;\n return options.collection.database.token + '|' + requestFlag + '|' + count;\n }\n const replicationState = replicateRxCollection({\n collection: options.collection,\n replicationIdentifier: options.replicationIdentifier,\n live: options.live,\n pull: {\n batchSize: options.batchSize,\n stream$: messages$.pipe(\n filter(msg => msg.id === 'stream' && msg.collection === options.collection.name),\n map(msg => msg.result)\n ),\n async handler(lastPulledCheckpoint: CheckpointType | undefined, batchSize: number) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterChangesSince',\n params: [lastPulledCheckpoint, batchSize]\n };\n wsClient.send(JSON.stringify(request));\n const result = await firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n return result;\n }\n },\n push: {\n batchSize: options.batchSize,\n handler(docs: RxReplicationWriteToMasterRow[]) {\n const requestId = getRequestId();\n const request: WebsocketMessageType = {\n id: requestId,\n collection: options.collection.name,\n method: 'masterWrite',\n params: [docs]\n };\n wsClient.send(JSON.stringify(request));\n return firstValueFrom(\n messages$.pipe(\n filter(msg => msg.id === requestId),\n map(msg => msg.result)\n )\n );\n }\n }\n });\n\n websocketClient.error$.subscribe(err => replicationState.subjects.error.next(err));\n\n websocketClient.connected$.subscribe(isConnected => {\n if (isConnected) {\n /**\n * When the client goes offline and online again,\n * we have to send a 'RESYNC' signal because the client\n * might have missed out events while being offline.\n */\n replicationState.reSync();\n\n /**\n * Because reconnecting creates a new websocket-instance,\n * we have to start the changestream from the remote again\n * each time.\n */\n const streamRequest: WebsocketMessageType = {\n id: 'stream',\n collection: options.collection.name,\n method: 'masterChangeStream$',\n params: []\n };\n wsClient.send(JSON.stringify(streamRequest));\n }\n });\n\n options.collection.onDestroy.push(() => websocketClient.socket.close());\n return replicationState;\n}\n"],"mappings":"AAAA,SACIA,qBAAqB,QAElB,yBAAyB;AAMhC,OAAOC,q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AM,EAAE,qBAAqB;QAC7BD,MAAM,EAAE;MACZ,CAAC;MACDxB,QAAQ,CAAC0B,IAAI,CAACC,IAAI,CAACC,SAAS,CAACmC,aAAa,CAAC,CAAC;IAChD;EACJ,CAAC,CAAC;EAEFhE,OAAO,CAACsB,UAAU,CAAC2C,SAAS,CAACP,IAAI,CAAC,MAAMrB,eAAe,CAACF,MAAM,CAAC+B,KAAK,CAAC,CAAC,CAAC;EACvE,OAAOrB,gBAAgB;AAC3B"} \ No newline at end of file diff --git a/dist/esm/plugins/replication-websocket/websocket-server.js b/dist/esm/plugins/replication-websocket/websocket-server.js index 73a4c9a3824..ecd81df167b 100644 --- a/dist/esm/plugins/replication-websocket/websocket-server.js +++ b/dist/esm/plugins/replication-websocket/websocket-server.js @@ -40,6 +40,17 @@ export function startSocketServer(options) { onConnection$: onConnection$.asObservable() }; } +var REPLICATION_HANDLER_BY_COLLECTION = new Map(); +export function getReplicationHandlerByCollection(database, collectionName) { + if (!database.collections[collectionName]) { + throw new Error('collection ' + collectionName + ' does not exist'); + } + var collection = database.collections[collectionName]; + var handler = getFromMapOrCreate(REPLICATION_HANDLER_BY_COLLECTION, collection, () => { + return rxStorageInstanceToReplicationHandler(collection.storageInstance, collection.conflictHandler, database.token); + }); + return handler; +} export function startWebsocketServer(options) { var { database, @@ -49,17 +60,6 @@ export function startWebsocketServer(options) { // auto close when the database gets destroyed database.onDestroy.push(() => serverState.close()); - var replicationHandlerByCollection = new Map(); - function getReplicationHandler(collectionName) { - if (!database.collections[collectionName]) { - throw new Error('collection ' + collectionName + ' does not exist'); - } - var handler = getFromMapOrCreate(replicationHandlerByCollection, collectionName, () => { - var collection = database.collections[collectionName]; - return rxStorageInstanceToReplicationHandler(collection.storageInstance, collection.conflictHandler, database.token); - }); - return handler; - } serverState.onConnection$.subscribe(ws => { var onCloseHandlers = []; ws.onclose = () => { @@ -67,7 +67,10 @@ export function startWebsocketServer(options) { }; ws.on('message', async messageString => { var message = JSON.parse(messageString); - var handler = getReplicationHandler(message.collection); + var handler = getReplicationHandlerByCollection(database, message.collection); + if (message.method === 'auth') { + return; + } var method = handler[message.method]; /** diff --git a/dist/esm/plugins/replication-websocket/websocket-server.js.map b/dist/esm/plugins/replication-websocket/websocket-server.js.map index a829835bb36..1c5927b359e 100644 --- a/dist/esm/plugins/replication-websocket/websocket-server.js.map +++ b/dist/esm/plugins/replication-websocket/websocket-server.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-server.js","names":["pkg","WebSocketServer","rxStorageInstanceToReplicationHandler","PROMISE_RESOLVE_VOID","getFromMapOrCreate","Subject","startSocketServer","options","wss","closed","closeServer","onConnection$","complete","Promise","res","rej","ws","clients","close","err","on","next","server","asObservable","startWebsocketServer","database","wsOptions","serverState","onDestroy","push","replicationHandlerByCollection","Map","getReplicationHandler","collectionName","collections","Error","handler","collection","storageInstance","conflictHandler","token","subscribe","onCloseHandlers","onclose","map","fn","messageString","message","JSON","parse","method","changeStreamSub","masterChangeStream$","ev","streamResponse","id","result","send","stringify","unsubscribe","params","response"],"sources":["../../../../src/plugins/replication-websocket/websocket-server.ts"],"sourcesContent":["import type {\n RxReplicationHandler\n} from '../../types/index.d.ts';\n\nimport type {\n WebSocket,\n ServerOptions\n} from 'isomorphic-ws';\nimport pkg from 'isomorphic-ws';\nconst { WebSocketServer } = pkg;\n\nimport type {\n WebsocketMessageResponseType,\n WebsocketMessageType,\n WebsocketServerOptions,\n WebsocketServerState\n} from './websocket-types.ts';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol/index.ts';\nimport {\n PROMISE_RESOLVE_VOID, getFromMapOrCreate\n} from '../../plugins/utils/index.ts';\nimport { Subject } from 'rxjs';\n\nexport function startSocketServer(options: ServerOptions): WebsocketServerState {\n const wss = new WebSocketServer(options);\n let closed = false;\n function closeServer() {\n if (closed) {\n return PROMISE_RESOLVE_VOID;\n }\n closed = true;\n onConnection$.complete();\n return new Promise((res, rej) => {\n /**\n * We have to close all client connections,\n * otherwise wss.close() will never call the callback.\n * @link https://github.com/websockets/ws/issues/1288#issuecomment-360594458\n */\n for (const ws of wss.clients) {\n ws.close();\n }\n wss.close((err: any) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n\n const onConnection$ = new Subject();\n wss.on('connection', (ws: any) => onConnection$.next(ws));\n\n return {\n server: wss,\n close: closeServer,\n onConnection$: onConnection$.asObservable()\n };\n}\n\nexport function startWebsocketServer(options: WebsocketServerOptions): WebsocketServerState {\n const { database, ...wsOptions } = options;\n const serverState = startSocketServer(wsOptions);\n\n // auto close when the database gets destroyed\n database.onDestroy.push(() => serverState.close());\n\n const replicationHandlerByCollection: Map> = new Map();\n function getReplicationHandler(collectionName: string): RxReplicationHandler {\n if (!database.collections[collectionName]) {\n throw new Error('collection ' + collectionName + ' does not exist');\n }\n\n const handler = getFromMapOrCreate(\n replicationHandlerByCollection,\n collectionName,\n () => {\n const collection = database.collections[collectionName];\n return rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n database.token\n );\n }\n );\n return handler;\n }\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', async (messageString: string) => {\n const message: WebsocketMessageType = JSON.parse(messageString);\n const handler = getReplicationHandler(message.collection);\n const method = handler[message.method];\n\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n if (typeof method !== 'function') {\n const changeStreamSub = handler.masterChangeStream$.subscribe(ev => {\n const streamResponse: WebsocketMessageResponseType = {\n id: 'stream',\n collection: message.collection,\n result: ev\n };\n ws.send(JSON.stringify(streamResponse));\n });\n onCloseHandlers.push(() => changeStreamSub.unsubscribe());\n return;\n }\n const result = await (method as any)(...message.params);\n const response: WebsocketMessageResponseType = {\n id: message.id,\n collection: message.collection,\n result\n };\n ws.send(JSON.stringify(response));\n });\n });\n\n\n return serverState;\n}\n"],"mappings":"AAQA,OAAOA,GAAG,MAAM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eAAe,GAAGf,OAAO,CAACgB,mBAAmB,CAACX,SAAS,CAACY,EAAE,IAAI;UAChE,IAAMC,cAA4C,GAAG;YACjDC,EAAE,EAAE,QAAQ;YACZlB,UAAU,EAAEU,OAAO,CAACV,UAAU;YAC9BmB,MAAM,EAAEH;UACZ,CAAC;UACDrC,EAAE,CAACyC,IAAI,CAACT,IAAI,CAACU,SAAS,CAACJ,cAAc,CAAC,CAAC;QAC3C,CAAC,CAAC;QACFZ,eAAe,CAACb,IAAI,CAAC,MAAMsB,eAAe,CAACQ,WAAW,CAAC,CAAC,CAAC;QACzD;MACJ;MACA,IAAMH,MAAM,GAAG,MAAON,MAAM,CAAS,GAAGH,OAAO,CAACa,MAAM,CAAC;MACvD,IAAMC,QAAsC,GAAG;QAC3CN,EAAE,EAAER,OAAO,CAACQ,EAAE;QACdlB,UAAU,EAAEU,OAAO,CAACV,UAAU;QAC9BmB;MACJ,CAAC;MACDxC,EAAE,CAACyC,IAAI,CAACT,IAAI,CAACU,SAAS,CAACG,QAAQ,CAAC,CAAC;IACrC,CAAC,CAAC;EACN,CAAC,CAAC;EAGF,OAAOlC,WAAW;AACtB"} \ No newline at end of file +{"version":3,"file":"websocket-server.js","names":["pkg","WebSocketServer","rxStorageInstanceToReplicationHandler","PROMISE_RESOLVE_VOID","getFromMapOrCreate","Subject","startSocketServer","options","wss","closed","closeServer","onConnection$","complete","Promise","res","rej","ws","clients","close","err","on","next","server","asObservable","REPLICATION_HANDLER_BY_COLLECTION","Map","getReplicationHandlerByCollection","database","collectionName","collections","Error","collection","handler","storageInstance","conflictHandler","token","startWebsocketServer","wsOptions","serverState","onDestroy","push","subscribe","onCloseHandlers","onclose","map","fn","messageString","message","JSON","parse","method","changeStreamSub","masterChangeStream$","ev","streamResponse","id","result","send","stringify","unsubscribe","params","response"],"sources":["../../../../src/plugins/replication-websocket/websocket-server.ts"],"sourcesContent":["import type {\n RxCollection,\n RxDatabase,\n RxReplicationHandler\n} from '../../types/index.d.ts';\n\nimport type {\n WebSocket,\n ServerOptions\n} from 'isomorphic-ws';\nimport pkg from 'isomorphic-ws';\nconst { WebSocketServer } = pkg;\n\nimport type {\n WebsocketMessageResponseType,\n WebsocketMessageType,\n WebsocketServerOptions,\n WebsocketServerState\n} from './websocket-types.ts';\nimport { rxStorageInstanceToReplicationHandler } from '../../replication-protocol/index.ts';\nimport {\n PROMISE_RESOLVE_VOID, getFromMapOrCreate\n} from '../../plugins/utils/index.ts';\nimport { Subject } from 'rxjs';\n\nexport function startSocketServer(options: ServerOptions): WebsocketServerState {\n const wss = new WebSocketServer(options);\n let closed = false;\n function closeServer() {\n if (closed) {\n return PROMISE_RESOLVE_VOID;\n }\n closed = true;\n onConnection$.complete();\n return new Promise((res, rej) => {\n /**\n * We have to close all client connections,\n * otherwise wss.close() will never call the callback.\n * @link https://github.com/websockets/ws/issues/1288#issuecomment-360594458\n */\n for (const ws of wss.clients) {\n ws.close();\n }\n wss.close((err: any) => {\n if (err) {\n rej(err);\n } else {\n res();\n }\n });\n });\n }\n\n const onConnection$ = new Subject();\n wss.on('connection', (ws: any) => onConnection$.next(ws));\n\n return {\n server: wss,\n close: closeServer,\n onConnection$: onConnection$.asObservable()\n };\n}\n\nconst REPLICATION_HANDLER_BY_COLLECTION: WeakMap> = new Map();\nexport function getReplicationHandlerByCollection(\n database: RxDatabase,\n collectionName: string\n): RxReplicationHandler {\n if (!database.collections[collectionName]) {\n throw new Error('collection ' + collectionName + ' does not exist');\n }\n\n const collection = database.collections[collectionName];\n const handler = getFromMapOrCreate>(\n REPLICATION_HANDLER_BY_COLLECTION,\n collection,\n () => {\n return rxStorageInstanceToReplicationHandler(\n collection.storageInstance,\n collection.conflictHandler,\n database.token\n );\n }\n );\n return handler;\n}\n\nexport function startWebsocketServer(options: WebsocketServerOptions): WebsocketServerState {\n const { database, ...wsOptions } = options;\n const serverState = startSocketServer(wsOptions);\n\n // auto close when the database gets destroyed\n database.onDestroy.push(() => serverState.close());\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', async (messageString: string) => {\n const message: WebsocketMessageType = JSON.parse(messageString);\n const handler = getReplicationHandlerByCollection(database, message.collection);\n if (message.method === 'auth') {\n return;\n }\n const method = handler[message.method];\n\n /**\n * If it is not a function,\n * it means that the client requested the masterChangeStream$\n */\n if (typeof method !== 'function') {\n const changeStreamSub = handler.masterChangeStream$.subscribe(ev => {\n const streamResponse: WebsocketMessageResponseType = {\n id: 'stream',\n collection: message.collection,\n result: ev\n };\n ws.send(JSON.stringify(streamResponse));\n });\n onCloseHandlers.push(() => changeStreamSub.unsubscribe());\n return;\n }\n const result = await (method as any)(...message.params);\n const response: WebsocketMessageResponseType = {\n id: message.id,\n collection: message.collection,\n result\n };\n ws.send(JSON.stringify(response));\n });\n });\n\n\n return serverState;\n}\n"],"mappings":"AAUA,OAAOA,GAAG,MAAM,eAAe;AAC/B,IAAM;EAAEC;AAAgB,CAAC,GAAGD,GAAG;AAQ/B,SAASE,qCAAqC,QAAQ,qCAAqC;AAC3F,SACIC,oBAAoB,EAAEC,kBAAkB,QACrC,8BAA8B;AACrC,SAASC,OAAO,QAAQ,MAAM;AAE9B,OAAO,SAASC,iBAAiBA,CAACC,OAAsB,EAAwB;EAC5E,IAAMC,GAAG,GAAG,IAAIP,eAAe,CAACM,OAAO,CAAC;EACxC,IAAIE,MAAM,GAAG,KAAK;EAClB,SAASC,WAAWA,CAAA,EAAG;IACnB,IAAID,MAAM,EAAE;MACR,OAAON,oBAAoB;IAC/B;IACAM,MAAM,GAAG,IAAI;IACbE,aAAa,CAACC,QAAQ,CAAC,CAAC;IACxB,OAAO,IAAIC,OAAO,CAAO,CAACC,GAAG,EAAEC,GAAG,KAAK;MACnC;AACZ;AACA;AACA;AACA;MACY,KAAK,IAAMC,EAAE,IAAIR,GAAG,CAACS,OAAO,EAAE;QAC1BD,EAAE,CAACE,KAAK,CAAC,CAAC;MACd;MAC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O,CAAChB,UAAU;QAC9ByB;MACJ,CAAC;MACDxC,EAAE,CAACyC,IAAI,CAACT,IAAI,CAACU,SAAS,CAACG,QAAQ,CAAC,CAAC;IACrC,CAAC,CAAC;EACN,CAAC,CAAC;EAGF,OAAOvB,WAAW;AACtB"} \ No newline at end of file diff --git a/dist/esm/plugins/replication-websocket/websocket-types.js.map b/dist/esm/plugins/replication-websocket/websocket-types.js.map index b9f2efec8af..5dd2ffab3b1 100644 --- a/dist/esm/plugins/replication-websocket/websocket-types.js.map +++ b/dist/esm/plugins/replication-websocket/websocket-types.js.map @@ -1 +1 @@ -{"version":3,"file":"websocket-types.js","names":[],"sources":["../../../../src/plugins/replication-websocket/websocket-types.ts"],"sourcesContent":["import type {\n Observable,\n} from 'rxjs';\nimport type {\n ServerOptions,\n ClientOptions,\n WebSocketServer,\n WebSocket\n} from 'ws';\nimport type {\n RxCollection,\n RxDatabase,\n RxReplicationHandler,\n StringKeys\n} from '../../types/index.d.ts';\n\nexport type WebsocketServerOptions = {\n database: RxDatabase;\n} & ServerOptions;\n\nexport type WebsocketServerState = {\n server: WebSocketServer;\n close: () => Promise;\n onConnection$: Observable;\n};\n\nexport type WebsocketClientOptions = {\n replicationIdentifier: string;\n collection: RxCollection;\n url: string;\n batchSize?: number;\n live?: boolean;\n} & ClientOptions;\n\nexport type WebsocketMessageType = {\n id: string;\n collection: string;\n method: StringKeys>;\n params: any[];\n};\n\nexport type WebsocketMessageResponseType = {\n id: string;\n collection: string;\n result: any;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"websocket-types.js","names":[],"sources":["../../../../src/plugins/replication-websocket/websocket-types.ts"],"sourcesContent":["import type {\n Observable,\n} from 'rxjs';\nimport type {\n ServerOptions,\n ClientOptions,\n WebSocketServer,\n WebSocket\n} from 'ws';\nimport type {\n RxCollection,\n RxDatabase,\n RxReplicationHandler,\n StringKeys\n} from '../../types/index.d.ts';\n\nexport type WebsocketServerOptions = {\n database: RxDatabase;\n} & ServerOptions;\n\nexport type WebsocketServerState = {\n server: WebSocketServer;\n close: () => Promise;\n onConnection$: Observable;\n};\n\nexport type WebsocketClientOptions = {\n replicationIdentifier: string;\n collection: RxCollection;\n url: string;\n batchSize?: number;\n live?: boolean;\n headers?: { [k: string]: string; };\n} & ClientOptions;\n\nexport type WebsocketMessageType = {\n id: string;\n collection: string;\n method: StringKeys> | 'auth';\n params: any[];\n};\n\nexport type WebsocketMessageResponseType = {\n id: string;\n collection: string;\n result: any;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/esm/plugins/replication/index.js b/dist/esm/plugins/replication/index.js index 9ecb870a114..6dea6020427 100644 --- a/dist/esm/plugins/replication/index.js +++ b/dist/esm/plugins/replication/index.js @@ -7,7 +7,7 @@ import { BehaviorSubject, combineLatest, filter, mergeMap, Subject } from 'rxjs'; import { RxDBLeaderElectionPlugin } from "../leader-election/index.js"; -import { arrayFilterNotEmpty, ensureNotFalsy, errorToPlainJson, flatClone, getFromMapOrCreate, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_TRUE, toArray } from "../../plugins/utils/index.js"; +import { arrayFilterNotEmpty, ensureNotFalsy, errorToPlainJson, flatClone, getFromMapOrCreate, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_TRUE, toArray, toPromise } from "../../plugins/utils/index.js"; import { awaitRxStorageReplicationFirstInSync, awaitRxStorageReplicationInSync, cancelRxStorageReplication, getRxReplicationMetaInstanceSchema, replicateRxStorageInstance } from "../../replication-protocol/index.js"; import { newRxError } from "../../rx-error.js"; import { awaitRetry, DEFAULT_MODIFIER, swapDefaultDeletedTodeletedField, handlePulledDocuments } from "./replication-helper.js"; @@ -41,6 +41,7 @@ export var RxReplicationState = /*#__PURE__*/function () { this.error$ = this.subjects.error.asObservable(); this.canceled$ = this.subjects.canceled.asObservable(); this.active$ = this.subjects.active.asObservable(); + this.onCancel = []; this.callOnStart = undefined; this.remoteEvents$ = new Subject(); this.replicationIdentifier = replicationIdentifier; @@ -304,7 +305,7 @@ export var RxReplicationState = /*#__PURE__*/function () { if (this.isStopped()) { return PROMISE_RESOLVE_FALSE; } - var promises = []; + var promises = this.onCancel.map(fn => toPromise(fn())); if (this.internalReplicationState) { await cancelRxStorageReplication(this.internalReplicationState); } diff --git a/dist/esm/plugins/replication/index.js.map b/dist/esm/plugins/replication/index.js.map index 5e57406f083..5333635218d 100644 --- a/dist/esm/plugins/replication/index.js.map +++ b/dist/esm/plugins/replication/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["BehaviorSubject","combineLatest","filter","mergeMap","Subject","RxDBLeaderElectionPlugin","arrayFilterNotEmpty","ensureNotFalsy","errorToPlainJson","flatClone","getFromMapOrCreate","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_TRUE","toArray","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","cancelRxStorageReplication","getRxReplicationMetaInstanceSchema","replicateRxStorageInstance","newRxError","awaitRetry","DEFAULT_MODIFIER","swapDefaultDeletedTodeletedField","handlePulledDocuments","addConnectedStorageToCollection","addRxPlugin","hasEncryption","overwritable","runAsyncPluginHooks","REPLICATION_STATE_BY_COLLECTION","WeakMap","RxReplicationState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","sent","error","canceled","active","received$","asObservable","sent$","error$","canceled$","active$","callOnStart","undefined","remoteEvents$","replicationStates","onDestroy","cancel","Object","keys","forEach","key","defineProperty","get","startPromise","Promise","res","_proto","prototype","start","isStopped","pullModifier","modifier","pushModifier","database","metaInstanceCollectionName","hashFunction","name","join","metaInstanceSchema","schema","jsonSchema","metaInstance","all","storage","createStorageInstance","databaseName","collectionName","databaseInstanceToken","token","multiInstance","options","password","devMode","isDevMode","internalReplicationState","pushBatchSize","batchSize","pullBatchSize","initialCheckpoint","upstream","downstream","forkInstance","storageInstance","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","_v","ev","useEv","documents","map","d","masterChangesSince","checkpoint","done","result","handler","err","emitError","errors","er","direction","next","useResult","masterWrite","rows","useRowsOrNull","row","newDocumentState","assumedMasterState","useRows","length","Array","isArray","pushRows","args","rxdb","conflicts","events","subscribe","processed","down","document","up","writeToMasterRow","isActive","stream$","getValue","awaitInitialReplication","awaitInSync","requestIdlePromise","reSync","emitEvent","promises","checkpointQueue","then","close","sub","unsubscribe","complete","replicateRxCollection","waitForLeadership","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport {\n arrayFilterNotEmpty,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n toArray\n} from '../../plugins/utils/index.ts';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n getRxReplicationMetaInstanceSchema,\n replicateRxStorageInstance\n} from '../../replication-protocol/index.ts';\nimport { newRxError } from '../../rx-error.ts';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n handlePulledDocuments\n} from './replication-helper.ts';\nimport {\n addConnectedStorageToCollection\n} from '../../rx-database-internal-store.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { hasEncryption } from '../../rx-storage-helper.ts';\nimport { overwritable } from '../../overwritable.ts';\nimport {\n runAsyncPluginHooks\n} from '../../hooks.ts';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n sent: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false) // true when something is running, false when not\n };\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly sent$: Observable> = this.subjects.sent.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n public startPromise: Promise;\n constructor(\n /**\n * The identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n const replicationStates = getFromMapOrCreate(\n REPLICATION_STATE_BY_COLLECTION,\n collection,\n () => []\n );\n replicationStates.push(this);\n\n // stop the replication when the collection gets destroyed\n this.collection.onDestroy.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance, any, {}, any>;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n const metaInstanceCollectionName = 'rx-replication-meta-' + await database.hashFunction([\n this.collection.name,\n this.replicationIdentifier\n ].join('-'));\n const metaInstanceSchema = getRxReplicationMetaInstanceSchema(\n this.collection.schema.jsonSchema,\n hasEncryption(this.collection.schema.jsonSchema)\n );\n\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance>({\n databaseName: database.name,\n collectionName: metaInstanceCollectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance, // TODO is this always false?\n options: {},\n schema: metaInstanceSchema,\n password: database.password,\n devMode: overwritable.isDevMode()\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInstanceCollectionName,\n metaInstanceSchema\n )\n ]);\n this.metaInstance = metaInstance;\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n initialCheckpoint: {\n upstream: this.push ? this.push.initialCheckpoint : undefined,\n downstream: this.pull ? this.pull.initialCheckpoint : undefined\n },\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rxdbreplication' + this.replicationIdentifier,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n filter(_v => !!this.pull),\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n useEv.documents = handlePulledDocuments(this.collection, this.deletedField, useEv.documents);\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType | undefined,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n useResult.documents = handlePulledDocuments(this.collection, this.deletedField, useResult.documents);\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n\n await runAsyncPluginHooks('preReplicationMasterWrite', {\n rows,\n collection: this.collection\n });\n\n const useRowsOrNull = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.newDocumentState === null) {\n return null;\n }\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n return row;\n })\n );\n const useRows: RxReplicationWriteToMasterRow[] = useRowsOrNull.filter(arrayFilterNotEmpty);\n\n let result: WithDeleted[] = null as any;\n\n // In case all the rows have been filtered and nothing has to be sent\n if (useRows.length === 0) {\n done = true;\n result = [];\n }\n\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n if (this.isStopped()) {\n return [];\n }\n\n await runAsyncPluginHooks('preReplicationMasterWriteDocumentsHandle', {\n result,\n collection: this.collection\n });\n\n const conflicts = handlePulledDocuments(this.collection, this.deletedField, ensureNotFalsy(result));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.sent.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n async cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = [];\n\n if (this.internalReplicationState) {\n await cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.sent.complete();\n\n return Promise.all(promises);\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n /**\n * It is a common error to forget to add these config\n * objects. So we check here because it makes no sense\n * to start a replication with neither push nor pull.\n */\n if (!pull && !push) {\n throw newRxError('UT3', {\n collection: collection.name,\n args: {\n replicationIdentifier\n }\n });\n }\n\n const replicationState = new RxReplicationState(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA,SACIA,eAAe,EACfC,aAAa,EACbC,MAAM,EACNC,QAAQ,EAERC,OAAO,QAEJ,MAAM;AAiBb,SAASC,wBAAwB,QAAQ,6BAA6B;AACtE,SACIC,mBAAmB,EACnBC,cAAc,EACdC,gBAAgB,EAChBC,SAAS,EACTC,kBAAkB,EAClBC,qBAAqB,EACrBC,oBAAoB,EACpBC,OAAO,QACJ,8BAA8B;AACrC,SACIC,oCAAoC,EACpCC,+BAA+B,EAC/BC,0BAA0B,EAC1BC,kCAAkC,EAClCC,0BAA0B,QACvB,qCAAqC;AAC5C,SAASC,UAAU,QAAQ,mBAAmB;AAC9C,SACIC,UAAU,EACVC,gBAAgB,EAChBC,gCAAgC,EAChCC,qBAAqB,QAClB,yBAAyB;AAChC,SACIC,+BAA+B,QAC5B,qCAAqC;AAC5C,SAASC,WAAW,QAAQ,iBAAiB;AAC7C,SAASC,aAAa,QAAQ,4BAA4B;AAC1D,SAASC,YAAY,QAAQ,uBAAuB;AACpD,SACIC,mBAAmB,QAChB,gBAAgB;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AACA;EACI,IAAME,qBAAqB,GAAGH,iBAAiB,IAAIC,gBAAgB,CAACrI,UAAU,CAAC0C,QAAQ,CAACgB,aAAa;EACrG,IAAM8E,WAAyB,GAAGD,qBAAqB,GAAGF,gBAAgB,CAACrI,UAAU,CAAC0C,QAAQ,CAAC0F,iBAAiB,CAAC,CAAC,GAAGzJ,oBAAoB;EACzI,OAAO6J,WAAW,CAACV,IAAI,CAAC,MAAM;IAC1B,IAAIO,gBAAgB,CAAC/F,SAAS,CAAC,CAAC,EAAE;MAC9B;IACJ;IACA,IAAI+F,gBAAgB,CAAC/H,SAAS,EAAE;MAC5B+H,gBAAgB,CAAChG,KAAK,CAAC,CAAC;IAC5B;EACJ,CAAC,CAAC;AACN"} \ No newline at end of file +{"version":3,"file":"index.js","names":["BehaviorSubject","combineLatest","filter","mergeMap","Subject","RxDBLeaderElectionPlugin","arrayFilterNotEmpty","ensureNotFalsy","errorToPlainJson","flatClone","getFromMapOrCreate","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_TRUE","toArray","toPromise","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","cancelRxStorageReplication","getRxReplicationMetaInstanceSchema","replicateRxStorageInstance","newRxError","awaitRetry","DEFAULT_MODIFIER","swapDefaultDeletedTodeletedField","handlePulledDocuments","addConnectedStorageToCollection","addRxPlugin","hasEncryption","overwritable","runAsyncPluginHooks","REPLICATION_STATE_BY_COLLECTION","WeakMap","RxReplicationState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","sent","error","canceled","active","received$","asObservable","sent$","error$","canceled$","active$","onCancel","callOnStart","undefined","remoteEvents$","replicationStates","onDestroy","cancel","Object","keys","forEach","key","defineProperty","get","startPromise","Promise","res","_proto","prototype","start","isStopped","pullModifier","modifier","pushModifier","database","metaInstanceCollectionName","hashFunction","name","join","metaInstanceSchema","schema","jsonSchema","metaInstance","all","storage","createStorageInstance","databaseName","collectionName","databaseInstanceToken","token","multiInstance","options","password","devMode","isDevMode","internalReplicationState","pushBatchSize","batchSize","pullBatchSize","initialCheckpoint","upstream","downstream","forkInstance","storageInstance","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","_v","ev","useEv","documents","map","d","masterChangesSince","checkpoint","done","result","handler","err","emitError","errors","er","direction","next","useResult","masterWrite","rows","useRowsOrNull","row","newDocumentState","assumedMasterState","useRows","length","Array","isArray","pushRows","args","rxdb","conflicts","events","subscribe","processed","down","document","up","writeToMasterRow","isActive","stream$","getValue","awaitInitialReplication","awaitInSync","requestIdlePromise","reSync","emitEvent","promises","fn","checkpointQueue","then","close","sub","unsubscribe","complete","replicateRxCollection","waitForLeadership","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport {\n arrayFilterNotEmpty,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n toArray,\n toPromise\n} from '../../plugins/utils/index.ts';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n getRxReplicationMetaInstanceSchema,\n replicateRxStorageInstance\n} from '../../replication-protocol/index.ts';\nimport { newRxError } from '../../rx-error.ts';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n handlePulledDocuments\n} from './replication-helper.ts';\nimport {\n addConnectedStorageToCollection\n} from '../../rx-database-internal-store.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { hasEncryption } from '../../rx-storage-helper.ts';\nimport { overwritable } from '../../overwritable.ts';\nimport {\n runAsyncPluginHooks\n} from '../../hooks.ts';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n sent: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false) // true when something is running, false when not\n };\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly sent$: Observable> = this.subjects.sent.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n public startPromise: Promise;\n\n public onCancel: (() => void)[] = [];\n\n constructor(\n /**\n * The identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n const replicationStates = getFromMapOrCreate(\n REPLICATION_STATE_BY_COLLECTION,\n collection,\n () => []\n );\n replicationStates.push(this);\n\n // stop the replication when the collection gets destroyed\n this.collection.onDestroy.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance, any, {}, any>;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n const metaInstanceCollectionName = 'rx-replication-meta-' + await database.hashFunction([\n this.collection.name,\n this.replicationIdentifier\n ].join('-'));\n const metaInstanceSchema = getRxReplicationMetaInstanceSchema(\n this.collection.schema.jsonSchema,\n hasEncryption(this.collection.schema.jsonSchema)\n );\n\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance>({\n databaseName: database.name,\n collectionName: metaInstanceCollectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance, // TODO is this always false?\n options: {},\n schema: metaInstanceSchema,\n password: database.password,\n devMode: overwritable.isDevMode()\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInstanceCollectionName,\n metaInstanceSchema\n )\n ]);\n this.metaInstance = metaInstance;\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n initialCheckpoint: {\n upstream: this.push ? this.push.initialCheckpoint : undefined,\n downstream: this.pull ? this.pull.initialCheckpoint : undefined\n },\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rxdbreplication' + this.replicationIdentifier,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n filter(_v => !!this.pull),\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n useEv.documents = handlePulledDocuments(this.collection, this.deletedField, useEv.documents);\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType | undefined,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n useResult.documents = handlePulledDocuments(this.collection, this.deletedField, useResult.documents);\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n\n await runAsyncPluginHooks('preReplicationMasterWrite', {\n rows,\n collection: this.collection\n });\n\n const useRowsOrNull = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.newDocumentState === null) {\n return null;\n }\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n return row;\n })\n );\n const useRows: RxReplicationWriteToMasterRow[] = useRowsOrNull.filter(arrayFilterNotEmpty);\n\n let result: WithDeleted[] = null as any;\n\n // In case all the rows have been filtered and nothing has to be sent\n if (useRows.length === 0) {\n done = true;\n result = [];\n }\n\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n if (this.isStopped()) {\n return [];\n }\n\n await runAsyncPluginHooks('preReplicationMasterWriteDocumentsHandle', {\n result,\n collection: this.collection\n });\n\n const conflicts = handlePulledDocuments(this.collection, this.deletedField, ensureNotFalsy(result));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.sent.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n async cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = this.onCancel.map(fn => toPromise(fn()));\n\n if (this.internalReplicationState) {\n await cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.sent.complete();\n\n return Promise.all(promises);\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n /**\n * It is a common error to forget to add these config\n * objects. So we check here because it makes no sense\n * to start a replication with neither push nor pull.\n */\n if (!pull && !push) {\n throw newRxError('UT3', {\n collection: collection.name,\n args: {\n replicationIdentifier\n }\n });\n }\n\n const replicationState = new RxReplicationState(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA,SACIA,eAAe,EACfC,aAAa,EACbC,MAAM,EACNC,QAAQ,EAERC,OAAO,QAEJ,MAAM;AAiBb,SAASC,wBAAwB,QAAQ,6BAA6B;AACtE,SACIC,mBAAmB,EACnBC,cAAc,EACdC,gBAAgB,EAChBC,SAAS,EACTC,kBAAkB,EAClBC,qBAAqB,EACrBC,oBAAoB,EACpBC,OAAO,EACPC,SAAS,QACN,8BAA8B;AACrC,SACIC,oCAAoC,EACpCC,+BAA+B,EAC/BC,0BAA0B,EAC1BC,kCAAkC,EAClCC,0BAA0B,QACvB,qCAAqC;AAC5C,SAASC,UAAU,QAAQ,mBAAmB;AAC9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AAI;MAC3B6D,IAAI,EAAE;QACF5G;MACJ;IACJ,CAAC,CAAC;EACN;EAEA,IAAMwI,gBAAgB,GAAG,IAAIzI,kBAAkB,CAC3CC,qBAAqB,EACrBC,UAAU,EACVC,YAAY,EACZC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SACJ,CAAC;EAGDkI,4BAA4B,CAACF,iBAAiB,EAAEC,gBAAgB,CAAC;EACjE,OAAOA,gBAAgB;AAC3B;AAGA,OAAO,SAASC,4BAA4BA,CACxCF,iBAA0B,EAC1BC,gBAA8C,EAChD;EACE;AACJ;AACA;AACA;EACI,IAAME,qBAAqB,GAAGH,iBAAiB,IAAIC,gBAAgB,CAACvI,UAAU,CAAC2C,QAAQ,CAACgB,aAAa;EACrG,IAAM+E,WAAyB,GAAGD,qBAAqB,GAAGF,gBAAgB,CAACvI,UAAU,CAAC2C,QAAQ,CAAC2F,iBAAiB,CAAC,CAAC,GAAG5J,oBAAoB;EACzI,OAAOgK,WAAW,CAACV,IAAI,CAAC,MAAM;IAC1B,IAAIO,gBAAgB,CAAChG,SAAS,CAAC,CAAC,EAAE;MAC9B;IACJ;IACA,IAAIgG,gBAAgB,CAACjI,SAAS,EAAE;MAC5BiI,gBAAgB,CAACjG,KAAK,CAAC,CAAC;IAC5B;EACJ,CAAC,CAAC;AACN"} \ No newline at end of file diff --git a/dist/esm/plugins/storage-memory/memory-types.js.map b/dist/esm/plugins/storage-memory/memory-types.js.map index d327fec2950..7d699393ddd 100644 --- a/dist/esm/plugins/storage-memory/memory-types.js.map +++ b/dist/esm/plugins/storage-memory/memory-types.js.map @@ -1 +1 @@ -{"version":3,"file":"memory-types.js","names":[],"sources":["../../../../src/plugins/storage-memory/memory-types.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageChangeEvent,\n RxStorageDefaultCheckpoint\n} from '../../types/index.d.ts';\n\nexport type RxStorageMemorySettings = {};\nexport type RxStorageMemoryInstanceCreationOptions = {};\nexport type RxStorageMemory = RxStorage, RxStorageMemoryInstanceCreationOptions> & {\n /**\n * State by collectionKey\n */\n collectionStates: Map>;\n};\n\nexport type MemoryStorageInternalsByIndex = {\n index: string[];\n docsWithIndex: DocWithIndexString[];\n getIndexableString: (docData: RxDocumentData) => string;\n};\n\n/**\n * The internals are shared between multiple storage instances\n * that have been created with the same [databaseName+collectionName] combination.\n */\nexport type MemoryStorageInternals = {\n\n /**\n * Schema of the first instance created with the given settings.\n * Used to ensure that the same storage is not re-created with\n * a different schema.\n */\n schema: RxJsonSchema>;\n\n /**\n * We reuse the memory state when multiple instances\n * are created with the same params.\n * If refCount becomes 0, we can delete the state.\n */\n refCount: number;\n /**\n * If this becomes true,\n * it means that an instance has called remove()\n * so all other instances should also not work anymore.\n */\n removed: boolean;\n documents: Map>;\n /**\n * Attachments data, indexed by a combined string\n * consisting of [documentId + '||' + attachmentId]\n */\n attachments: Map;\n byIndex: {\n /**\n * Because RxDB requires a deterministic sorting\n * on all indexes, we can be sure that the composed index key\n * of each document is unique, because it contains the primaryKey\n * as last index part.\n * So we do not have to store the index-position when we want to do fast\n * writes. Instead we can do a binary search over the existing array\n * because RxDB also knows the previous state of the document when we do a bulkWrite().\n */\n [indexName: string]: MemoryStorageInternalsByIndex;\n };\n\n /**\n * We need these to do lazy writes.\n */\n ensurePersistenceTask?: CategorizeBulkWriteRowsOutput;\n ensurePersistenceIdlePromise?: Promise;\n\n /**\n * To easier test the conflict resolution,\n * the memory storage exposes the conflict resolution task subject\n * so that we can inject own tasks during tests.\n */\n conflictResultionTasks$: Subject>;\n changes$: Subject>, RxStorageDefaultCheckpoint>>;\n};\n\nexport type DocWithIndexString = {\n id: string;\n doc: RxDocumentData;\n indexString: string;\n};\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"memory-types.js","names":[],"sources":["../../../../src/plugins/storage-memory/memory-types.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentWriteData,\n RxConflictResultionTask,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageChangeEvent,\n RxStorageDefaultCheckpoint\n} from '../../types/index.d.ts';\n\nexport type RxStorageMemorySettings = {};\nexport type RxStorageMemoryInstanceCreationOptions = {};\nexport type RxStorageMemory = RxStorage, RxStorageMemoryInstanceCreationOptions> & {\n /**\n * State by collectionKey\n */\n collectionStates: Map>;\n};\n\nexport type MemoryStorageInternalsByIndex = {\n index: string[];\n docsWithIndex: DocWithIndexString[];\n getIndexableString: (docData: RxDocumentData) => string;\n};\n\n/**\n * The internals are shared between multiple storage instances\n * that have been created with the same [databaseName+collectionName] combination.\n */\nexport type MemoryStorageInternals = {\n // used to debug stuff and identify instances\n id: string;\n\n /**\n * Schema of the first instance created with the given settings.\n * Used to ensure that the same storage is not re-created with\n * a different schema.\n */\n schema: RxJsonSchema>;\n\n /**\n * We reuse the memory state when multiple instances\n * are created with the same params.\n * If refCount becomes 0, we can delete the state.\n */\n refCount: number;\n /**\n * If this becomes true,\n * it means that an instance has called remove()\n * so all other instances should also not work anymore.\n */\n removed: boolean;\n documents: Map>;\n /**\n * Attachments data, indexed by a combined string\n * consisting of [documentId + '||' + attachmentId]\n */\n attachments: Map;\n byIndex: {\n /**\n * Because RxDB requires a deterministic sorting\n * on all indexes, we can be sure that the composed index key\n * of each document is unique, because it contains the primaryKey\n * as last index part.\n * So we do not have to store the index-position when we want to do fast\n * writes. Instead we can do a binary search over the existing array\n * because RxDB also knows the previous state of the document when we do a bulkWrite().\n */\n [indexName: string]: MemoryStorageInternalsByIndex;\n };\n\n /**\n * We need these to do lazy writes.\n */\n ensurePersistenceTask?: CategorizeBulkWriteRowsOutput;\n ensurePersistenceIdlePromise?: Promise;\n\n /**\n * To easier test the conflict resolution,\n * the memory storage exposes the conflict resolution task subject\n * so that we can inject own tasks during tests.\n */\n conflictResultionTasks$: Subject>;\n changes$: Subject>, RxStorageDefaultCheckpoint>>;\n};\n\nexport type DocWithIndexString = {\n id: string;\n doc: RxDocumentData;\n indexString: string;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/dist/esm/plugins/storage-memory/rx-storage-instance-memory.js b/dist/esm/plugins/storage-memory/rx-storage-instance-memory.js index f1b0efb7e74..2967d12e386 100644 --- a/dist/esm/plugins/storage-memory/rx-storage-instance-memory.js +++ b/dist/esm/plugins/storage-memory/rx-storage-instance-memory.js @@ -2,7 +2,7 @@ import { Subject } from 'rxjs'; import { getStartIndexStringFromLowerBound, getStartIndexStringFromUpperBound } from "../../custom-index.js"; import { getPrimaryFieldOfPrimaryKey } from "../../rx-schema-helper.js"; import { categorizeBulkWriteRows } from "../../rx-storage-helper.js"; -import { deepEqual, ensureNotFalsy, now, PROMISE_RESOLVE_TRUE, PROMISE_RESOLVE_VOID, requestIdlePromiseNoQueue } from "../../plugins/utils/index.js"; +import { deepEqual, ensureNotFalsy, now, PROMISE_RESOLVE_TRUE, PROMISE_RESOLVE_VOID, randomCouchString, requestIdlePromiseNoQueue } from "../../plugins/utils/index.js"; import { boundGE, boundGT, boundLE, boundLT } from "./binary-search-bounds.js"; import { attachmentMapKey, compareDocsWithIndex, ensureNotRemoved, getMemoryCollectionKey, putWriteRowToState, removeDocFromState } from "./memory-helper.js"; import { addIndexesToInternalsState, getMemoryIndexName } from "./memory-indexes.js"; @@ -94,7 +94,7 @@ export var RxStorageInstanceMemory = /*#__PURE__*/function () { var documentsById = this.internals.documents; var primaryPath = this.primaryPath; var categorized = this.internals.ensurePersistenceTask; - delete this.internals.ensurePersistenceTask; + this.internals.ensurePersistenceTask = undefined; /** * Do inserts/updates @@ -175,17 +175,6 @@ export var RxStorageInstanceMemory = /*#__PURE__*/function () { upperBound = upperBound; var upperBoundString = getStartIndexStringFromUpperBound(this.schema, index, upperBound); var indexName = getMemoryIndexName(index); - - // console.log('in memory query:'); - // console.dir({ - // queryPlan, - // lowerBound, - // upperBound, - // lowerBoundString, - // upperBoundString, - // indexName - // }); - if (!this.internals.byIndex[indexName]) { throw new Error('index does not exist ' + indexName); } @@ -300,6 +289,7 @@ export function createMemoryStorageInstance(storage, params, settings) { var internals = storage.collectionStates.get(collectionKey); if (!internals) { internals = { + id: randomCouchString(5), schema: params.schema, removed: false, refCount: 1, diff --git a/dist/esm/plugins/storage-memory/rx-storage-instance-memory.js.map b/dist/esm/plugins/storage-memory/rx-storage-instance-memory.js.map index 6dbe31e762d..687bb02c08d 100644 --- a/dist/esm/plugins/storage-memory/rx-storage-instance-memory.js.map +++ b/dist/esm/plugins/storage-memory/rx-storage-instance-memory.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-instance-memory.js","names":["Subject","getStartIndexStringFromLowerBound","getStartIndexStringFromUpperBound","getPrimaryFieldOfPrimaryKey","categorizeBulkWriteRows","deepEqual","ensureNotFalsy","now","PROMISE_RESOLVE_TRUE","PROMISE_RESOLVE_VOID","requestIdlePromiseNoQueue","boundGE","boundGT","boundLE","boundLT","attachmentMapKey","compareDocsWithIndex","ensureNotRemoved","getMemoryCollectionKey","putWriteRowToState","removeDocFromState","addIndexesToInternalsState","getMemoryIndexName","getQueryMatcher","getSortComparator","OPEN_MEMORY_INSTANCES","Set","RxStorageInstanceMemory","storage","databaseName","collectionName","schema","internals","options","settings","closed","add","primaryPath","primaryKey","_proto","prototype","bulkWrite","documentWrites","context","ensurePersistence","documentsById","documents","categorized","error","errors","success","Array","bulkInsertDocs","length","i","writeRow","doc","document","bulkUpdateDocs","push","ensurePersistenceTask","ensurePersistenceIdlePromise","then","undefined","eventBulk","events","lastState","newestRow","checkpoint","id","lwt","_meta","endTime","changes$","next","ret","Promise","resolve","stateByIndex","Object","values","byIndex","docId","get","attachments","attachmentsMap","attachmentsAdd","forEach","attachment","set","documentId","attachmentId","writeData","attachmentData","digest","attachmentsUpdate","attachmentsRemove","delete","findDocumentsById","docIds","withDeleted","size","docInDb","_deleted","query","preparedQuery","queryPlan","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","queryPlanFields","index","mustManuallyResort","sortSatisfiedByIndex","lowerBound","startKeys","lowerBoundString","upperBound","endKeys","upperBoundString","indexName","Error","docsWithIndex","indexOfLower","inclusiveStart","indexString","indexOfUpper","inclusiveEnd","rows","done","currentRow","currentDoc","sortComparator","sort","slice","count","result","mode","cleanup","minimumDeletedTime","maxDeletionTime","getAttachmentData","key","data","changeStream","asObservable","remove","removed","collectionStates","version","close","refCount","conflictResultionTasks","conflictResultionTasks$","resolveConflictResultionTask","_taskSolution","createMemoryStorageInstance","params","collectionKey","Map","devMode","instance"],"sources":["../../../../src/plugins/storage-memory/rx-storage-instance-memory.ts"],"sourcesContent":["import {\n Observable,\n Subject\n} from 'rxjs';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index.ts';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper.ts';\nimport {\n categorizeBulkWriteRows\n} from '../../rx-storage-helper.ts';\nimport type {\n BulkWriteRow,\n EventBulk,\n PreparedQuery,\n QueryMatcher,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types/index.d.ts';\nimport {\n deepEqual,\n ensureNotFalsy,\n lastOfArray,\n now,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID,\n requestIdlePromiseNoQueue,\n RX_META_LWT_MINIMUM,\n toArray\n} from '../../plugins/utils/index.ts';\nimport {\n boundGE,\n boundGT,\n boundLE,\n boundLT\n} from './binary-search-bounds.ts';\nimport {\n attachmentMapKey,\n compareDocsWithIndex,\n ensureNotRemoved,\n getMemoryCollectionKey,\n putWriteRowToState,\n removeDocFromState\n} from './memory-helper.ts';\nimport {\n addIndexesToInternalsState,\n getMemoryIndexName\n} from './memory-indexes.ts';\nimport type {\n MemoryStorageInternals,\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types.ts';\nimport { getQueryMatcher, getSortComparator } from '../../rx-query-helper.ts';\n\n/**\n * Used in tests to ensure everything\n * is closed correctly\n */\nexport const OPEN_MEMORY_INSTANCES = new Set>();\n\nexport class RxStorageInstanceMemory implements RxStorageInstance<\n RxDocType,\n MemoryStorageInternals,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n public closed = false;\n\n constructor(\n public readonly storage: RxStorageMemory,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: MemoryStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageMemorySettings\n ) {\n OPEN_MEMORY_INSTANCES.add(this);\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n this.ensurePersistence();\n ensureNotRemoved(this);\n const internals = this.internals;\n const documentsById = this.internals.documents;\n const primaryPath = this.primaryPath;\n\n const categorized = categorizeBulkWriteRows(\n this,\n primaryPath as any,\n documentsById,\n documentWrites,\n context\n );\n const error = categorized.errors;\n const success: RxDocumentData[] = new Array(categorized.bulkInsertDocs.length);\n const bulkInsertDocs = categorized.bulkInsertDocs;\n for (let i = 0; i < bulkInsertDocs.length; ++i) {\n const writeRow = bulkInsertDocs[i];\n const doc = writeRow.document;\n success[i] = doc;\n }\n const bulkUpdateDocs = categorized.bulkUpdateDocs;\n for (let i = 0; i < bulkUpdateDocs.length; ++i) {\n const writeRow = bulkUpdateDocs[i];\n const doc = writeRow.document;\n success.push(doc);\n }\n\n this.internals.ensurePersistenceTask = categorized;\n if (!this.internals.ensurePersistenceIdlePromise) {\n this.internals.ensurePersistenceIdlePromise = requestIdlePromiseNoQueue().then(() => {\n this.internals.ensurePersistenceIdlePromise = undefined;\n this.ensurePersistence();\n });\n }\n\n /**\n * Important: The events must be emitted AFTER the persistence\n * task has been added.\n */\n if (categorized.eventBulk.events.length > 0) {\n const lastState = ensureNotFalsy(categorized.newestRow).document;\n categorized.eventBulk.checkpoint = {\n id: lastState[primaryPath],\n lwt: lastState._meta.lwt\n };\n categorized.eventBulk.endTime = now();\n PROMISE_RESOLVE_TRUE.then(() => {\n internals.changes$.next(categorized.eventBulk);\n });\n }\n\n const ret = Promise.resolve({ success, error });\n return ret;\n }\n\n /**\n * Instead of directly inserting the documents into all indexes,\n * we do it lazy in the background. This gives the application time\n * to directly work with the write-result and to do stuff like rendering DOM\n * notes and processing RxDB queries.\n * Then in some later time, or just before the next read/write,\n * it is ensured that the indexes have been written.\n */\n public ensurePersistence() {\n if (\n !this.internals.ensurePersistenceTask\n ) {\n return;\n }\n const internals = this.internals;\n const documentsById = this.internals.documents;\n const primaryPath = this.primaryPath;\n\n const categorized = this.internals.ensurePersistenceTask;\n delete this.internals.ensurePersistenceTask;\n\n /**\n * Do inserts/updates\n */\n const stateByIndex = Object.values(this.internals.byIndex);\n\n const bulkInsertDocs = categorized.bulkInsertDocs;\n for (let i = 0; i < bulkInsertDocs.length; ++i) {\n const writeRow = bulkInsertDocs[i];\n const doc = writeRow.document;\n const docId = doc[primaryPath];\n putWriteRowToState(\n docId as any,\n internals,\n stateByIndex,\n writeRow,\n undefined\n );\n }\n\n const bulkUpdateDocs = categorized.bulkUpdateDocs;\n for (let i = 0; i < bulkUpdateDocs.length; ++i) {\n const writeRow = bulkUpdateDocs[i];\n const doc = writeRow.document;\n const docId = doc[primaryPath];\n putWriteRowToState(\n docId as any,\n internals,\n stateByIndex,\n writeRow,\n documentsById.get(docId as any)\n );\n }\n\n /**\n * Handle attachments\n */\n if (this.schema.attachments) {\n const attachmentsMap = internals.attachments;\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n {\n writeData: attachment.attachmentData,\n digest: attachment.digest\n }\n );\n });\n if (this.schema.attachments) {\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n {\n writeData: attachment.attachmentData,\n digest: attachment.digest\n }\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentsMap.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n }\n }\n }\n\n findDocumentsById(\n docIds: string[],\n withDeleted: boolean\n ): Promise[]> {\n this.ensurePersistence();\n const documentsById = this.internals.documents;\n const ret: RxDocumentData[] = [];\n if (documentsById.size === 0) {\n return Promise.resolve(ret);\n }\n for (let i = 0; i < docIds.length; ++i) {\n const docId = docIds[i];\n const docInDb = documentsById.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret.push(docInDb);\n }\n }\n return Promise.resolve(ret);\n }\n\n query(\n preparedQuery: PreparedQuery\n ): Promise> {\n this.ensurePersistence();\n\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = getQueryMatcher(\n this.schema,\n preparedQuery.query\n );\n }\n\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortSatisfiedByIndex;\n const index: string[] | undefined = queryPlanFields;\n const lowerBound: any[] = queryPlan.startKeys;\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n lowerBound\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = upperBound;\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n upperBound\n );\n const indexName = getMemoryIndexName(index);\n\n // console.log('in memory query:');\n // console.dir({\n // queryPlan,\n // lowerBound,\n // upperBound,\n // lowerBoundString,\n // upperBoundString,\n // indexName\n // });\n\n if (!this.internals.byIndex[indexName]) {\n throw new Error('index does not exist ' + indexName);\n }\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n\n\n let indexOfLower = (queryPlan.inclusiveStart ? boundGE : boundGT)(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n const indexOfUpper = (queryPlan.inclusiveEnd ? boundLE : boundLT)(\n docsWithIndex,\n {\n indexString: upperBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let rows: RxDocumentData[] = [];\n let done = false;\n while (!done) {\n const currentRow = docsWithIndex[indexOfLower];\n if (\n !currentRow ||\n indexOfLower > indexOfUpper\n ) {\n break;\n }\n const currentDoc = currentRow.doc;\n\n if (!queryMatcher || queryMatcher(currentDoc)) {\n rows.push(currentDoc);\n }\n\n if (\n (rows.length >= skipPlusLimit && !mustManuallyResort)\n ) {\n done = true;\n }\n\n indexOfLower++;\n }\n\n if (mustManuallyResort) {\n const sortComparator = getSortComparator(this.schema, preparedQuery.query);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n return Promise.resolve({\n documents: rows\n });\n }\n\n async count(\n preparedQuery: PreparedQuery\n ): Promise {\n this.ensurePersistence();\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n\n cleanup(minimumDeletedTime: number): Promise {\n this.ensurePersistence();\n const maxDeletionTime = now() - minimumDeletedTime;\n const index = ['_deleted', '_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n 0,\n ''\n ]\n );\n\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n if (!currentDoc || currentDoc.doc._meta.lwt > maxDeletionTime) {\n done = true;\n } else {\n removeDocFromState(\n this.primaryPath as any,\n this.schema,\n this.internals,\n currentDoc.doc\n );\n indexOfLower++;\n }\n }\n return PROMISE_RESOLVE_TRUE;\n }\n\n getAttachmentData(\n documentId: string,\n attachmentId: string,\n digest: string\n ): Promise {\n this.ensurePersistence();\n ensureNotRemoved(this);\n const key = attachmentMapKey(documentId, attachmentId);\n const data = this.internals.attachments.get(key);\n\n if (\n !digest ||\n !data ||\n data.digest !== digest\n ) {\n throw new Error('attachment does not exist: ' + key);\n }\n return Promise.resolve(data.writeData.data);\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotRemoved(this);\n return this.internals.changes$.asObservable();\n }\n\n async remove(): Promise {\n if (this.closed) {\n throw new Error('closed');\n }\n this.ensurePersistence();\n ensureNotRemoved(this);\n\n this.internals.removed = true;\n this.storage.collectionStates.delete(\n getMemoryCollectionKey(\n this.databaseName,\n this.collectionName,\n this.schema.version\n )\n );\n await this.close();\n }\n\n close(): Promise {\n OPEN_MEMORY_INSTANCES.delete(this);\n\n this.ensurePersistence();\n if (this.closed) {\n return PROMISE_RESOLVE_VOID;\n }\n this.closed = true;\n\n this.internals.refCount = this.internals.refCount - 1;\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return this.internals.conflictResultionTasks$.asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n}\n\nexport function createMemoryStorageInstance(\n storage: RxStorageMemory,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageMemorySettings\n): Promise> {\n const collectionKey = getMemoryCollectionKey(\n params.databaseName,\n params.collectionName,\n params.schema.version\n );\n\n let internals = storage.collectionStates.get(collectionKey);\n if (!internals) {\n internals = {\n schema: params.schema,\n removed: false,\n refCount: 1,\n documents: new Map(),\n attachments: params.schema.attachments ? new Map() : undefined as any,\n byIndex: {},\n conflictResultionTasks$: new Subject(),\n changes$: new Subject()\n };\n addIndexesToInternalsState(internals, params.schema);\n storage.collectionStates.set(collectionKey, internals);\n } else {\n /**\n * Ensure that the storage was not already\n * created with a different schema.\n * This is very important because if this check\n * does not exist here, we have hard-to-debug problems\n * downstream.\n */\n if (\n params.devMode &&\n !deepEqual(internals.schema, params.schema)\n ) {\n throw new Error('storage was already created with a different schema');\n }\n internals.refCount = internals.refCount + 1;\n }\n\n const instance = new RxStorageInstanceMemory(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":"AAAA,SAEIA,OAAO,QACJ,MAAM;AACb,SACIC,iCAAiC,EACjCC,iCAAiC,QAC9B,uBAAuB;AAC9B,SAASC,2BAA2B,QAAQ,2BAA2B;AACvE,SACIC,uBAAuB,QACpB,4BAA4B;AAmBnC,SACIC,SAAS,EACTC,cAAc,EAEdC,GAAG,EACHC,oBAAoB,EACpBC,oBAAoB,EACpBC,yBAAyB,QAGtB,8BAA8B;AACrC,SACIC,OAAO,EACPC,OAAO,EACPC,OAAO,EACPC,OAAO,QACJ,2BAA2B;AAClC,SACIC,gBAAgB,EAChBC,oBAAoB,EACpBC,gBAAgB,EAChBC,sBAAsB,EACtBC,kBAAkB,EAClBC,kBAAkB,QACf,oBAAoB;AAC3B,SACIC,0BAA0B,EAC1BC,kBAAkB,QACf,qBAAqB;AAO5B,SAASC,eAAe,EAAEC,iBAAiB,QAAQ,0BAA0B;;AAE7E;AACA;AACA;AACA;AACA,OAAO,IAAMC,qBAAqB,GAAG,IAAIC,GAAG,CAA+B,CAAC;AAE5E,WAAaC,uBAAuB;EAUhC,SAAAA,wBACoBC,OAAwB,EACxBC,YAAoB,EACpBC,cAAsB,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;AACA;AACA;AACA;AACA;IACQ,IACIgI,MAAM,CAACG,OAAO,IACd,CAAC9J,SAAS,CAAC2B,SAAS,CAACD,MAAM,EAAEiI,MAAM,CAACjI,MAAM,CAAC,EAC7C;MACE,MAAM,IAAI6F,KAAK,CAAC,qDAAqD,CAAC;IAC1E;IACA5F,SAAS,CAAC0H,QAAQ,GAAG1H,SAAS,CAAC0H,QAAQ,GAAG,CAAC;EAC/C;EAEA,IAAMU,QAAQ,GAAG,IAAIzI,uBAAuB,CACxCC,OAAO,EACPoI,MAAM,CAACnI,YAAY,EACnBmI,MAAM,CAAClI,cAAc,EACrBkI,MAAM,CAACjI,MAAM,EACbC,SAAS,EACTgI,MAAM,CAAC/H,OAAO,EACdC,QACJ,CAAC;EACD,OAAO0C,OAAO,CAACC,OAAO,CAACuF,QAAQ,CAAC;AACpC"} \ No newline at end of file +{"version":3,"file":"rx-storage-instance-memory.js","names":["Subject","getStartIndexStringFromLowerBound","getStartIndexStringFromUpperBound","getPrimaryFieldOfPrimaryKey","categorizeBulkWriteRows","deepEqual","ensureNotFalsy","now","PROMISE_RESOLVE_TRUE","PROMISE_RESOLVE_VOID","randomCouchString","requestIdlePromiseNoQueue","boundGE","boundGT","boundLE","boundLT","attachmentMapKey","compareDocsWithIndex","ensureNotRemoved","getMemoryCollectionKey","putWriteRowToState","removeDocFromState","addIndexesToInternalsState","getMemoryIndexName","getQueryMatcher","getSortComparator","OPEN_MEMORY_INSTANCES","Set","RxStorageInstanceMemory","storage","databaseName","collectionName","schema","internals","options","settings","closed","add","primaryPath","primaryKey","_proto","prototype","bulkWrite","documentWrites","context","ensurePersistence","documentsById","documents","categorized","error","errors","success","Array","bulkInsertDocs","length","i","writeRow","doc","document","bulkUpdateDocs","push","ensurePersistenceTask","ensurePersistenceIdlePromise","then","undefined","eventBulk","events","lastState","newestRow","checkpoint","id","lwt","_meta","endTime","changes$","next","ret","Promise","resolve","stateByIndex","Object","values","byIndex","docId","get","attachments","attachmentsMap","attachmentsAdd","forEach","attachment","set","documentId","attachmentId","writeData","attachmentData","digest","attachmentsUpdate","attachmentsRemove","delete","findDocumentsById","docIds","withDeleted","size","docInDb","_deleted","query","preparedQuery","queryPlan","skip","limit","Infinity","skipPlusLimit","queryMatcher","selectorSatisfiedByIndex","queryPlanFields","index","mustManuallyResort","sortSatisfiedByIndex","lowerBound","startKeys","lowerBoundString","upperBound","endKeys","upperBoundString","indexName","Error","docsWithIndex","indexOfLower","inclusiveStart","indexString","indexOfUpper","inclusiveEnd","rows","done","currentRow","currentDoc","sortComparator","sort","slice","count","result","mode","cleanup","minimumDeletedTime","maxDeletionTime","getAttachmentData","key","data","changeStream","asObservable","remove","removed","collectionStates","version","close","refCount","conflictResultionTasks","conflictResultionTasks$","resolveConflictResultionTask","_taskSolution","createMemoryStorageInstance","params","collectionKey","Map","devMode","instance"],"sources":["../../../../src/plugins/storage-memory/rx-storage-instance-memory.ts"],"sourcesContent":["import {\n Observable,\n Subject\n} from 'rxjs';\nimport {\n getStartIndexStringFromLowerBound,\n getStartIndexStringFromUpperBound\n} from '../../custom-index.ts';\nimport { getPrimaryFieldOfPrimaryKey } from '../../rx-schema-helper.ts';\nimport {\n categorizeBulkWriteRows\n} from '../../rx-storage-helper.ts';\nimport type {\n BulkWriteRow,\n EventBulk,\n PreparedQuery,\n QueryMatcher,\n RxConflictResultionTask,\n RxConflictResultionTaskSolution,\n RxDocumentData,\n RxJsonSchema,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageDefaultCheckpoint,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult,\n StringKeys\n} from '../../types/index.d.ts';\nimport {\n deepEqual,\n ensureNotFalsy,\n now,\n PROMISE_RESOLVE_TRUE,\n PROMISE_RESOLVE_VOID,\n randomCouchString,\n requestIdlePromiseNoQueue\n} from '../../plugins/utils/index.ts';\nimport {\n boundGE,\n boundGT,\n boundLE,\n boundLT\n} from './binary-search-bounds.ts';\nimport {\n attachmentMapKey,\n compareDocsWithIndex,\n ensureNotRemoved,\n getMemoryCollectionKey,\n putWriteRowToState,\n removeDocFromState\n} from './memory-helper.ts';\nimport {\n addIndexesToInternalsState,\n getMemoryIndexName\n} from './memory-indexes.ts';\nimport type {\n MemoryStorageInternals,\n RxStorageMemory,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageMemorySettings\n} from './memory-types.ts';\nimport { getQueryMatcher, getSortComparator } from '../../rx-query-helper.ts';\n\n/**\n * Used in tests to ensure everything\n * is closed correctly\n */\nexport const OPEN_MEMORY_INSTANCES = new Set>();\n\nexport class RxStorageInstanceMemory implements RxStorageInstance<\n RxDocType,\n MemoryStorageInternals,\n RxStorageMemoryInstanceCreationOptions,\n RxStorageDefaultCheckpoint\n> {\n\n public readonly primaryPath: StringKeys>;\n public closed = false;\n\n constructor(\n public readonly storage: RxStorageMemory,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: MemoryStorageInternals,\n public readonly options: Readonly,\n public readonly settings: RxStorageMemorySettings\n ) {\n OPEN_MEMORY_INSTANCES.add(this);\n this.primaryPath = getPrimaryFieldOfPrimaryKey(this.schema.primaryKey);\n }\n\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n this.ensurePersistence();\n ensureNotRemoved(this);\n const internals = this.internals;\n const documentsById = this.internals.documents;\n const primaryPath = this.primaryPath;\n\n const categorized = categorizeBulkWriteRows(\n this,\n primaryPath as any,\n documentsById,\n documentWrites,\n context\n );\n const error = categorized.errors;\n const success: RxDocumentData[] = new Array(categorized.bulkInsertDocs.length);\n const bulkInsertDocs = categorized.bulkInsertDocs;\n for (let i = 0; i < bulkInsertDocs.length; ++i) {\n const writeRow = bulkInsertDocs[i];\n const doc = writeRow.document;\n success[i] = doc;\n }\n const bulkUpdateDocs = categorized.bulkUpdateDocs;\n for (let i = 0; i < bulkUpdateDocs.length; ++i) {\n const writeRow = bulkUpdateDocs[i];\n const doc = writeRow.document;\n success.push(doc);\n }\n\n this.internals.ensurePersistenceTask = categorized;\n if (!this.internals.ensurePersistenceIdlePromise) {\n this.internals.ensurePersistenceIdlePromise = requestIdlePromiseNoQueue().then(() => {\n this.internals.ensurePersistenceIdlePromise = undefined;\n this.ensurePersistence();\n });\n }\n\n /**\n * Important: The events must be emitted AFTER the persistence\n * task has been added.\n */\n if (categorized.eventBulk.events.length > 0) {\n const lastState = ensureNotFalsy(categorized.newestRow).document;\n categorized.eventBulk.checkpoint = {\n id: lastState[primaryPath],\n lwt: lastState._meta.lwt\n };\n categorized.eventBulk.endTime = now();\n PROMISE_RESOLVE_TRUE.then(() => {\n internals.changes$.next(categorized.eventBulk);\n });\n }\n\n const ret = Promise.resolve({ success, error });\n return ret;\n }\n\n /**\n * Instead of directly inserting the documents into all indexes,\n * we do it lazy in the background. This gives the application time\n * to directly work with the write-result and to do stuff like rendering DOM\n * notes and processing RxDB queries.\n * Then in some later time, or just before the next read/write,\n * it is ensured that the indexes have been written.\n */\n public ensurePersistence() {\n if (\n !this.internals.ensurePersistenceTask\n ) {\n return;\n }\n const internals = this.internals;\n const documentsById = this.internals.documents;\n const primaryPath = this.primaryPath;\n\n const categorized = this.internals.ensurePersistenceTask;\n this.internals.ensurePersistenceTask = undefined;\n\n /**\n * Do inserts/updates\n */\n const stateByIndex = Object.values(this.internals.byIndex);\n\n const bulkInsertDocs = categorized.bulkInsertDocs;\n for (let i = 0; i < bulkInsertDocs.length; ++i) {\n const writeRow = bulkInsertDocs[i];\n const doc = writeRow.document;\n const docId = doc[primaryPath];\n putWriteRowToState(\n docId as any,\n internals,\n stateByIndex,\n writeRow,\n undefined\n );\n }\n\n const bulkUpdateDocs = categorized.bulkUpdateDocs;\n for (let i = 0; i < bulkUpdateDocs.length; ++i) {\n const writeRow = bulkUpdateDocs[i];\n const doc = writeRow.document;\n const docId = doc[primaryPath];\n putWriteRowToState(\n docId as any,\n internals,\n stateByIndex,\n writeRow,\n documentsById.get(docId as any)\n );\n }\n\n /**\n * Handle attachments\n */\n if (this.schema.attachments) {\n const attachmentsMap = internals.attachments;\n categorized.attachmentsAdd.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n {\n writeData: attachment.attachmentData,\n digest: attachment.digest\n }\n );\n });\n if (this.schema.attachments) {\n categorized.attachmentsUpdate.forEach(attachment => {\n attachmentsMap.set(\n attachmentMapKey(attachment.documentId, attachment.attachmentId),\n {\n writeData: attachment.attachmentData,\n digest: attachment.digest\n }\n );\n });\n categorized.attachmentsRemove.forEach(attachment => {\n attachmentsMap.delete(\n attachmentMapKey(attachment.documentId, attachment.attachmentId)\n );\n });\n }\n }\n }\n\n findDocumentsById(\n docIds: string[],\n withDeleted: boolean\n ): Promise[]> {\n this.ensurePersistence();\n const documentsById = this.internals.documents;\n const ret: RxDocumentData[] = [];\n if (documentsById.size === 0) {\n return Promise.resolve(ret);\n }\n for (let i = 0; i < docIds.length; ++i) {\n const docId = docIds[i];\n const docInDb = documentsById.get(docId);\n if (\n docInDb &&\n (\n !docInDb._deleted ||\n withDeleted\n )\n ) {\n ret.push(docInDb);\n }\n }\n return Promise.resolve(ret);\n }\n\n query(\n preparedQuery: PreparedQuery\n ): Promise> {\n this.ensurePersistence();\n\n const queryPlan = preparedQuery.queryPlan;\n const query = preparedQuery.query;\n\n const skip = query.skip ? query.skip : 0;\n const limit = query.limit ? query.limit : Infinity;\n const skipPlusLimit = skip + limit;\n\n let queryMatcher: QueryMatcher> | false = false;\n if (!queryPlan.selectorSatisfiedByIndex) {\n queryMatcher = getQueryMatcher(\n this.schema,\n preparedQuery.query\n );\n }\n\n const queryPlanFields: string[] = queryPlan.index;\n const mustManuallyResort = !queryPlan.sortSatisfiedByIndex;\n const index: string[] | undefined = queryPlanFields;\n const lowerBound: any[] = queryPlan.startKeys;\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n lowerBound\n );\n\n let upperBound: any[] = queryPlan.endKeys;\n upperBound = upperBound;\n const upperBoundString = getStartIndexStringFromUpperBound(\n this.schema,\n index,\n upperBound\n );\n const indexName = getMemoryIndexName(index);\n\n if (!this.internals.byIndex[indexName]) {\n throw new Error('index does not exist ' + indexName);\n }\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n\n\n let indexOfLower = (queryPlan.inclusiveStart ? boundGE : boundGT)(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n const indexOfUpper = (queryPlan.inclusiveEnd ? boundLE : boundLT)(\n docsWithIndex,\n {\n indexString: upperBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let rows: RxDocumentData[] = [];\n let done = false;\n while (!done) {\n const currentRow = docsWithIndex[indexOfLower];\n if (\n !currentRow ||\n indexOfLower > indexOfUpper\n ) {\n break;\n }\n const currentDoc = currentRow.doc;\n\n if (!queryMatcher || queryMatcher(currentDoc)) {\n rows.push(currentDoc);\n }\n\n if (\n (rows.length >= skipPlusLimit && !mustManuallyResort)\n ) {\n done = true;\n }\n\n indexOfLower++;\n }\n\n if (mustManuallyResort) {\n const sortComparator = getSortComparator(this.schema, preparedQuery.query);\n rows = rows.sort(sortComparator);\n }\n\n // apply skip and limit boundaries.\n rows = rows.slice(skip, skipPlusLimit);\n return Promise.resolve({\n documents: rows\n });\n }\n\n async count(\n preparedQuery: PreparedQuery\n ): Promise {\n this.ensurePersistence();\n const result = await this.query(preparedQuery);\n return {\n count: result.documents.length,\n mode: 'fast'\n };\n }\n\n cleanup(minimumDeletedTime: number): Promise {\n this.ensurePersistence();\n const maxDeletionTime = now() - minimumDeletedTime;\n const index = ['_deleted', '_meta.lwt', this.primaryPath as any];\n const indexName = getMemoryIndexName(index);\n const docsWithIndex = this.internals.byIndex[indexName].docsWithIndex;\n\n const lowerBoundString = getStartIndexStringFromLowerBound(\n this.schema,\n index,\n [\n true,\n 0,\n ''\n ]\n );\n\n let indexOfLower = boundGT(\n docsWithIndex,\n {\n indexString: lowerBoundString\n } as any,\n compareDocsWithIndex\n );\n\n let done = false;\n while (!done) {\n const currentDoc = docsWithIndex[indexOfLower];\n if (!currentDoc || currentDoc.doc._meta.lwt > maxDeletionTime) {\n done = true;\n } else {\n removeDocFromState(\n this.primaryPath as any,\n this.schema,\n this.internals,\n currentDoc.doc\n );\n indexOfLower++;\n }\n }\n return PROMISE_RESOLVE_TRUE;\n }\n\n getAttachmentData(\n documentId: string,\n attachmentId: string,\n digest: string\n ): Promise {\n this.ensurePersistence();\n ensureNotRemoved(this);\n const key = attachmentMapKey(documentId, attachmentId);\n const data = this.internals.attachments.get(key);\n\n if (\n !digest ||\n !data ||\n data.digest !== digest\n ) {\n throw new Error('attachment does not exist: ' + key);\n }\n return Promise.resolve(data.writeData.data);\n }\n\n changeStream(): Observable>, RxStorageDefaultCheckpoint>> {\n ensureNotRemoved(this);\n return this.internals.changes$.asObservable();\n }\n\n async remove(): Promise {\n if (this.closed) {\n throw new Error('closed');\n }\n this.ensurePersistence();\n ensureNotRemoved(this);\n\n this.internals.removed = true;\n this.storage.collectionStates.delete(\n getMemoryCollectionKey(\n this.databaseName,\n this.collectionName,\n this.schema.version\n )\n );\n await this.close();\n }\n\n close(): Promise {\n OPEN_MEMORY_INSTANCES.delete(this);\n\n this.ensurePersistence();\n if (this.closed) {\n return PROMISE_RESOLVE_VOID;\n }\n this.closed = true;\n\n this.internals.refCount = this.internals.refCount - 1;\n return PROMISE_RESOLVE_VOID;\n }\n\n conflictResultionTasks(): Observable> {\n return this.internals.conflictResultionTasks$.asObservable();\n }\n resolveConflictResultionTask(_taskSolution: RxConflictResultionTaskSolution): Promise {\n return PROMISE_RESOLVE_VOID;\n }\n}\n\nexport function createMemoryStorageInstance(\n storage: RxStorageMemory,\n params: RxStorageInstanceCreationParams,\n settings: RxStorageMemorySettings\n): Promise> {\n const collectionKey = getMemoryCollectionKey(\n params.databaseName,\n params.collectionName,\n params.schema.version\n );\n\n let internals = storage.collectionStates.get(collectionKey);\n if (!internals) {\n internals = {\n id: randomCouchString(5),\n schema: params.schema,\n removed: false,\n refCount: 1,\n documents: new Map(),\n attachments: params.schema.attachments ? new Map() : undefined as any,\n byIndex: {},\n conflictResultionTasks$: new Subject(),\n changes$: new Subject()\n };\n addIndexesToInternalsState(internals, params.schema);\n storage.collectionStates.set(collectionKey, internals);\n } else {\n /**\n * Ensure that the storage was not already\n * created with a different schema.\n * This is very important because if this check\n * does not exist here, we have hard-to-debug problems\n * downstream.\n */\n if (\n params.devMode &&\n !deepEqual(internals.schema, params.schema)\n ) {\n throw new Error('storage was already created with a different schema');\n }\n internals.refCount = internals.refCount + 1;\n }\n\n const instance = new RxStorageInstanceMemory(\n storage,\n params.databaseName,\n params.collectionName,\n params.schema,\n internals,\n params.options,\n settings\n );\n return Promise.resolve(instance);\n}\n"],"mappings":"AAAA,SAEIA,OAAO,QACJ,MAAM;AACb,SACIC,iCAAiC,EACjCC,iCAAiC,QAC9B,uBAAuB;AAC9B,SAASC,2BAA2B,QAAQ,2BAA2B;AACvE,SACIC,uBAAuB,QACpB,4BAA4B;AAmBnC,SACIC,SAAS,EACTC,cAAc,EACdC,GAAG,EACHC,oBAAoB,EACpBC,oBAAoB,EACpBC,iBAAiB,EACjBC,yBAAyB,QACtB,8BAA8B;AACrC,SACIC,OAAO,EACPC,OAAO,EACPC,OAAO,EACPC,OAAO,QACJ,2BAA2B;AAClC,SACIC,gBAAgB,EAChBC,oBAAoB,EACpBC,gBAAgB,EAChBC,sBAAsB,EACtBC,kBAAkB,EAClBC,kBAAkB,QACf,oBAAoB;AAC3B,SACIC,0BAA0B,EAC1BC,kBAAkB,QACf,qBAAqB;AAO5B,SAASC,eAAe,EAAEC,iBAAiB,QAAQ,0BAA0B;;AAE7E;AACA;AACA;AACA;AACA,OAAO,IAAMC,qBAAqB,GAAG,IAAIC,GAAG,CAA+B,CAAC;AAE5E,WAAaC,uBAAuB;EAUhC,SAAAA,wBACoBC,OAAwB,EACxBC,YAAoB,EACpBC,cAAsB,EACtBC,M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ACA;AACA;AACA;AACA;AACA;IACQ,IACIgI,MAAM,CAACG,OAAO,IACd,CAAC/J,SAAS,CAAC4B,SAAS,CAACD,MAAM,EAAEiI,MAAM,CAACjI,MAAM,CAAC,EAC7C;MACE,MAAM,IAAI6F,KAAK,CAAC,qDAAqD,CAAC;IAC1E;IACA5F,SAAS,CAAC0H,QAAQ,GAAG1H,SAAS,CAAC0H,QAAQ,GAAG,CAAC;EAC/C;EAEA,IAAMU,QAAQ,GAAG,IAAIzI,uBAAuB,CACxCC,OAAO,EACPoI,MAAM,CAACnI,YAAY,EACnBmI,MAAM,CAAClI,cAAc,EACrBkI,MAAM,CAACjI,MAAM,EACbC,SAAS,EACTgI,MAAM,CAAC/H,OAAO,EACdC,QACJ,CAAC;EACD,OAAO0C,OAAO,CAACC,OAAO,CAACuF,QAAQ,CAAC;AACpC"} \ No newline at end of file diff --git a/dist/esm/plugins/storage-remote-websocket/index.js b/dist/esm/plugins/storage-remote-websocket/index.js index b66d8495684..bc68ecc115f 100644 --- a/dist/esm/plugins/storage-remote-websocket/index.js +++ b/dist/esm/plugins/storage-remote-websocket/index.js @@ -53,7 +53,7 @@ export function getRxStorageRemoteWebsocket(options) { mode: options.mode, async messageChannelCreator() { var messages$ = new Subject(); - var websocketClient = await createWebSocketClient(options.url); + var websocketClient = await createWebSocketClient(options); websocketClient.message$.subscribe(msg => messages$.next(msg)); return { messages$, diff --git a/dist/esm/plugins/storage-remote-websocket/index.js.map b/dist/esm/plugins/storage-remote-websocket/index.js.map index 34ac954fb62..4b288729022 100644 --- a/dist/esm/plugins/storage-remote-websocket/index.js.map +++ b/dist/esm/plugins/storage-remote-websocket/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["Subject","PROMISE_RESOLVE_VOID","getFromMapOrThrow","createWebSocketClient","startSocketServer","exposeRxStorageRemote","getRxStorageRemote","createErrorAnswer","startRxStorageRemoteWebsocketServer","options","serverState","websocketByConnectionId","Map","messages$","exposeSettings","asObservable","storage","database","customRequestHandler","send","msg","ws","connectionId","JSON","stringify","exposeState","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","Error","set","next","getRxStorageRemoteWebsocket","identifier","url","join","mode","messageChannelCreator","websocketClient","message$","socket","close"],"sources":["../../../../src/plugins/storage-remote-websocket/index.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport {\n PROMISE_RESOLVE_VOID,\n getFromMapOrThrow\n} from '../../plugins/utils/index.ts';\nimport {\n createWebSocketClient,\n startSocketServer\n} from '../replication-websocket/index.ts';\nimport { exposeRxStorageRemote } from '../storage-remote/remote.ts';\nimport { getRxStorageRemote } from '../storage-remote/rx-storage-remote.ts';\nimport { createErrorAnswer } from '../storage-remote/storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport type {\n RxStorageRemoteWebsocketClient,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './types.ts';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage as any,\n database: options.database as any,\n customRequestHandler: options.customRequestHandler,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n }\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (\n message.method !== 'create' &&\n message.method !== 'custom'\n ) {\n ws.send(\n JSON.stringify(\n createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))\n )\n );\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\nexport function getRxStorageRemoteWebsocket(\n options: RxStorageRemoteWebsocketClientOptions\n): RxStorageRemoteWebsocketClient {\n const identifier = [\n options.url,\n 'rx-remote-storage-websocket'\n ].join('');\n const storage = getRxStorageRemote({\n identifier,\n mode: options.mode,\n async messageChannelCreator() {\n const messages$ = new Subject();\n const websocketClient = await createWebSocketClient(options.url);\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n return {\n messages$,\n send(msg) {\n return websocketClient.socket.send(JSON.stringify(msg));\n },\n close() {\n websocketClient.socket.close();\n return PROMISE_RESOLVE_VOID;\n }\n };\n\n }\n });\n return storage;\n}\n\n\nexport * from './types.ts';\n\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,MAAM;AAI9B,SACIC,oBAAoB,EACpBC,iBAAiB,QACd,8BAA8B;AACrC,SACIC,qBAAqB,EACrBC,iBAAiB,QACd,mCAAmC;AAC1C,SAASC,qBAAqB,QAAQ,6BAA6B;AACnE,SAASC,kBAAkB,QAAQ,wCAAwC;AAC3E,SAASC,iBAAiB,QAAQ,6CAA6C;AAY/E,OAAO,SAASC,mCAAmCA,CAC/CC,OAA8C,EACX;EACnC,IAAMC,WAAW,GAAGN,iBAAiB,CAACK,OAAO,CAAC;EAE9C,IAAME,uBAAuB,GAAG,IAAIC,GAAG,CAAoB,CAAC;EAC5D,IAAMC,SAAS,GAAG,IAAIb,OAAO,CAAkB,CAAC;EAChD,IAAMc,cAA6C,GAAG;IAClDD,SAAS,EAAEA,SAAS,CAACE,YAAY,CAAC,CAAC;IACnCC,OAAO,EAAEP,OAAO,CAACO,OAAc;IAC/B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OAAO;IACHxB,WAAW;IACXe;EACJ,CAAC;AACL;AAEA,OAAO,SAASgB,2BAA2BA,CACvChC,OAA8C,EAChB;EAC9B,IAAMiC,UAAU,GAAG,CACfjC,OAAO,CAACkC,GAAG,EACX,6BAA6B,CAChC,CAACC,IAAI,CAAC,EAAE,CAAC;EACV,IAAM5B,OAAO,GAAGV,kBAAkB,CAAC;IAC/BoC,UAAU;IACVG,IAAI,EAAEpC,OAAO,CAACoC,IAAI;IAClB,MAAMC,qBAAqBA,CAAA,EAAG;MAC1B,IAAMjC,SAAS,GAAG,IAAIb,OAAO,CAAoB,CAAC;MAClD,IAAM+C,eAAe,GAAG,MAAM5C,qBAAqB,CAACM,OAAO,CAACkC,GAAG,CAAC;MAChEI,eAAe,CAACC,QAAQ,CAACrB,SAAS,CAACP,GAAG,IAAIP,SAAS,CAAC2B,IAAI,CAACpB,GAAG,CAAC,CAAC;MAC9D,OAAO;QACHP,SAAS;QACTM,IAAIA,CAACC,GAAG,EAAE;UACN,OAAO2B,eAAe,CAACE,MAAM,CAAC9B,IAAI,CAACI,IAAI,CAACC,SAAS,CAACJ,GAAG,CAAC,CAAC;QAC3D,CAAC;QACD8B,KAAKA,CAAA,EAAG;UACJH,eAAe,CAACE,MAAM,CAACC,KAAK,CAAC,CAAC;UAC9B,OAAOjD,oBAAoB;QAC/B;MACJ,CAAC;IAEL;EACJ,CAAC,CAAC;EACF,OAAOe,OAAO;AAClB;AAGA,cAAc,YAAY"} \ No newline at end of file +{"version":3,"file":"index.js","names":["Subject","PROMISE_RESOLVE_VOID","getFromMapOrThrow","createWebSocketClient","startSocketServer","exposeRxStorageRemote","getRxStorageRemote","createErrorAnswer","startRxStorageRemoteWebsocketServer","options","serverState","websocketByConnectionId","Map","messages$","exposeSettings","asObservable","storage","database","customRequestHandler","send","msg","ws","connectionId","JSON","stringify","exposeState","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","Error","set","next","getRxStorageRemoteWebsocket","identifier","url","join","mode","messageChannelCreator","websocketClient","message$","socket","close"],"sources":["../../../../src/plugins/storage-remote-websocket/index.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport {\n PROMISE_RESOLVE_VOID,\n getFromMapOrThrow\n} from '../../plugins/utils/index.ts';\nimport {\n createWebSocketClient,\n startSocketServer\n} from '../replication-websocket/index.ts';\nimport { exposeRxStorageRemote } from '../storage-remote/remote.ts';\nimport { getRxStorageRemote } from '../storage-remote/rx-storage-remote.ts';\nimport { createErrorAnswer } from '../storage-remote/storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport type {\n RxStorageRemoteWebsocketClient,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './types.ts';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage as any,\n database: options.database as any,\n customRequestHandler: options.customRequestHandler,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n }\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (\n message.method !== 'create' &&\n message.method !== 'custom'\n ) {\n ws.send(\n JSON.stringify(\n createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))\n )\n );\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\nexport function getRxStorageRemoteWebsocket(\n options: RxStorageRemoteWebsocketClientOptions\n): RxStorageRemoteWebsocketClient {\n const identifier = [\n options.url,\n 'rx-remote-storage-websocket'\n ].join('');\n const storage = getRxStorageRemote({\n identifier,\n mode: options.mode,\n async messageChannelCreator() {\n const messages$ = new Subject();\n const websocketClient = await createWebSocketClient(options as any);\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n return {\n messages$,\n send(msg) {\n return websocketClient.socket.send(JSON.stringify(msg));\n },\n close() {\n websocketClient.socket.close();\n return PROMISE_RESOLVE_VOID;\n }\n };\n\n }\n });\n return storage;\n}\n\n\nexport * from './types.ts';\n\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,MAAM;AAI9B,SACIC,oBAAoB,EACpBC,iBAAiB,QACd,8BAA8B;AACrC,SACIC,qBAAqB,EACrBC,iBAAiB,QACd,mCAAmC;AAC1C,SAASC,qBAAqB,QAAQ,6BAA6B;AACnE,SAASC,kBAAkB,QAAQ,wCAAwC;AAC3E,SAASC,iBAAiB,QAAQ,6CAA6C;AAY/E,OAAO,SAASC,mCAAmCA,CAC/CC,OAA8C,EACX;EACnC,IAAMC,WAAW,GAAGN,iBAAiB,CAACK,OAAO,CAAC;EAE9C,IAAME,uBAAuB,GAAG,IAAIC,GAAG,CAAoB,CAAC;EAC5D,IAAMC,SAAS,GAAG,IAAIb,OAAO,CAAkB,CAAC;EAChD,IAAMc,cAA6C,GAAG;IAClDD,SAAS,EAAEA,SAAS,CAACE,YAAY,CAAC,CAAC;IACnCC,OAAO,EAAEP,OAAO,CAACO,OAAc;IAC/BC,QAAQ,EAAER,OAAO,CAACQ,QAAe;IACjCC,oBAAoB,EAAET,OAAO,CAACS,oBAAoB;IAClDC,IAAIA,CAACC,GAAG,EAAE;MACN,IAAMC,E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jC,OAAO,CAACkC,GAAG,EACX,6BAA6B,CAChC,CAACC,IAAI,CAAC,EAAE,CAAC;EACV,IAAM5B,OAAO,GAAGV,kBAAkB,CAAC;IAC/BoC,UAAU;IACVG,IAAI,EAAEpC,OAAO,CAACoC,IAAI;IAClB,MAAMC,qBAAqBA,CAAA,EAAG;MAC1B,IAAMjC,SAAS,GAAG,IAAIb,OAAO,CAAoB,CAAC;MAClD,IAAM+C,eAAe,GAAG,MAAM5C,qBAAqB,CAACM,OAAc,CAAC;MACnEsC,eAAe,CAACC,QAAQ,CAACrB,SAAS,CAACP,GAAG,IAAIP,SAAS,CAAC2B,IAAI,CAACpB,GAAG,CAAC,CAAC;MAC9D,OAAO;QACHP,SAAS;QACTM,IAAIA,CAACC,GAAG,EAAE;UACN,OAAO2B,eAAe,CAACE,MAAM,CAAC9B,IAAI,CAACI,IAAI,CAACC,SAAS,CAACJ,GAAG,CAAC,CAAC;QAC3D,CAAC;QACD8B,KAAKA,CAAA,EAAG;UACJH,eAAe,CAACE,MAAM,CAACC,KAAK,CAAC,CAAC;UAC9B,OAAOjD,oBAAoB;QAC/B;MACJ,CAAC;IAEL;EACJ,CAAC,CAAC;EACF,OAAOe,OAAO;AAClB;AAGA,cAAc,YAAY"} \ No newline at end of file diff --git a/dist/esm/plugins/utils/utils-other.js b/dist/esm/plugins/utils/utils-other.js index 523e3038cd1..d397f6c3af7 100644 --- a/dist/esm/plugins/utils/utils-other.js +++ b/dist/esm/plugins/utils/utils-other.js @@ -1,9 +1,12 @@ export function runXTimes(xTimes, fn) { new Array(xTimes).fill(0).forEach((_v, idx) => fn(idx)); } -export function ensureNotFalsy(obj) { +export function ensureNotFalsy(obj, message) { if (!obj) { - throw new Error('ensureNotFalsy() is falsy'); + if (!message) { + message = ''; + } + throw new Error('ensureNotFalsy() is falsy: ' + message); } return obj; } diff --git a/dist/esm/plugins/utils/utils-other.js.map b/dist/esm/plugins/utils/utils-other.js.map index 5bf1d5e2163..e909d5d2ffa 100644 --- a/dist/esm/plugins/utils/utils-other.js.map +++ b/dist/esm/plugins/utils/utils-other.js.map @@ -1 +1 @@ -{"version":3,"file":"utils-other.js","names":["runXTimes","xTimes","fn","Array","fill","forEach","_v","idx","ensureNotFalsy","obj","Error","ensureInteger","Number","isInteger","RXJS_SHARE_REPLAY_DEFAULTS","bufferSize","refCount"],"sources":["../../../../src/plugins/utils/utils-other.ts"],"sourcesContent":["export function runXTimes(xTimes: number, fn: (idx: number) => void) {\n new Array(xTimes).fill(0).forEach((_v, idx) => fn(idx));\n}\n\nexport function ensureNotFalsy(obj: T | false | undefined | null): T {\n if (!obj) {\n throw new Error('ensureNotFalsy() is falsy');\n }\n return obj;\n}\n\nexport function ensureInteger(obj: unknown): number {\n if (!Number.isInteger(obj)) {\n throw new Error('ensureInteger() is falsy');\n }\n return obj as number;\n}\n\n/**\n * Using shareReplay() without settings will not unsubscribe\n * if there are no more subscribers.\n * So we use these defaults.\n * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95\n */\nexport const RXJS_SHARE_REPLAY_DEFAULTS = {\n bufferSize: 1,\n refCount: true\n};\n"],"mappings":"AAAA,OAAO,SAASA,SAASA,CAACC,MAAc,EAAEC,EAAyB,EAAE;EACjE,IAAIC,KAAK,CAACF,MAAM,CAAC,CAACG,IAAI,CAAC,CAAC,CAAC,CAACC,OAAO,CAAC,CAACC,EAAE,EAAEC,GAAG,KAAKL,EAAE,CAACK,GAAG,CAAC,CAAC;AAC3D;AAEA,OAAO,SAASC,cAAcA,CAAIC,GAAiC,EAAK;EACpE,IAAI,CAACA,GAAG,EAAE;IACN,MAAM,IAAIC,KAAK,CAAC,2BAA2B,CAAC;EAChD;EACA,OAAOD,GAAG;AACd;AAEA,OAAO,SAASE,aAAaA,CAACF,GAAY,EAAU;EAChD,IAAI,CAACG,MAAM,CAACC,SAAS,CAACJ,GAAG,CAAC,EAAE;IACxB,MAAM,IAAIC,KAAK,CAAC,0BAA0B,CAAC;EAC/C;EACA,OAAOD,GAAG;AACd;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMK,0BAA0B,GAAG;EACtCC,UAAU,EAAE,CAAC;EACbC,QAAQ,EAAE;AACd,CAAC"} \ No newline at end of file +{"version":3,"file":"utils-other.js","names":["runXTimes","xTimes","fn","Array","fill","forEach","_v","idx","ensureNotFalsy","obj","message","Error","ensureInteger","Number","isInteger","RXJS_SHARE_REPLAY_DEFAULTS","bufferSize","refCount"],"sources":["../../../../src/plugins/utils/utils-other.ts"],"sourcesContent":["export function runXTimes(xTimes: number, fn: (idx: number) => void) {\n new Array(xTimes).fill(0).forEach((_v, idx) => fn(idx));\n}\n\nexport function ensureNotFalsy(obj: T | false | undefined | null, message?: string): T {\n if (!obj) {\n if (!message) {\n message = '';\n }\n throw new Error('ensureNotFalsy() is falsy: ' + message);\n }\n return obj;\n}\n\nexport function ensureInteger(obj: unknown): number {\n if (!Number.isInteger(obj)) {\n throw new Error('ensureInteger() is falsy');\n }\n return obj as number;\n}\n\n/**\n * Using shareReplay() without settings will not unsubscribe\n * if there are no more subscribers.\n * So we use these defaults.\n * @link https://cartant.medium.com/rxjs-whats-changed-with-sharereplay-65c098843e95\n */\nexport const RXJS_SHARE_REPLAY_DEFAULTS = {\n bufferSize: 1,\n refCount: true\n};\n"],"mappings":"AAAA,OAAO,SAASA,SAASA,CAACC,MAAc,EAAEC,EAAyB,EAAE;EACjE,IAAIC,KAAK,CAACF,MAAM,CAAC,CAACG,IAAI,CAAC,CAAC,CAAC,CAACC,OAAO,CAAC,CAACC,EAAE,EAAEC,GAAG,KAAKL,EAAE,CAACK,GAAG,CAAC,CAAC;AAC3D;AAEA,OAAO,SAASC,cAAcA,CAAIC,GAAiC,EAAEC,OAAgB,EAAK;EACtF,IAAI,CAACD,GAAG,EAAE;IACN,IAAI,CAACC,OAAO,EAAE;MACVA,OAAO,GAAG,EAAE;IAChB;IACA,MAAM,IAAIC,KAAK,CAAC,6BAA6B,GAAGD,OAAO,CAAC;EAC5D;EACA,OAAOD,GAAG;AACd;AAEA,OAAO,SAASG,aAAaA,CAACH,GAAY,EAAU;EAChD,IAAI,CAACI,MAAM,CAACC,SAAS,CAACL,GAAG,CAAC,EAAE;IACxB,MAAM,IAAIE,KAAK,CAAC,0BAA0B,CAAC;EAC/C;EACA,OAAOF,GAAG;AACd;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,IAAMM,0BAA0B,GAAG;EACtCC,UAAU,EAAE,CAAC;EACbC,QAAQ,EAAE;AACd,CAAC"} \ No newline at end of file diff --git a/dist/esm/plugins/utils/utils-rxdb-version.js b/dist/esm/plugins/utils/utils-rxdb-version.js index a9d556ee885..962a0a9a53d 100644 --- a/dist/esm/plugins/utils/utils-rxdb-version.js +++ b/dist/esm/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 = '15.3.0'; +export var RXDB_VERSION = '15.4.0'; //# sourceMappingURL=utils-rxdb-version.js.map \ No newline at end of file diff --git a/dist/esm/plugins/utils/utils-rxdb-version.js.map b/dist/esm/plugins/utils/utils-rxdb-version.js.map index dbdf11187e7..5ae44fba6ea 100644 --- a/dist/esm/plugins/utils/utils-rxdb-version.js.map +++ b/dist/esm/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 = '15.3.0';\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 = '15.4.0';\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAO,IAAMA,YAAY,GAAG,QAAQ"} \ No newline at end of file diff --git a/dist/esm/replication-protocol/index.js.map b/dist/esm/replication-protocol/index.js.map index 66f54b4a844..ace8331349b 100644 --- a/dist/esm/replication-protocol/index.js.map +++ b/dist/esm/replication-protocol/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["BehaviorSubject","combineLatest","filter","firstValueFrom","mergeMap","Subject","getPrimaryFieldOfPrimaryKey","clone","ensureNotFalsy","flatClone","PROMISE_RESOLVE_VOID","getCheckpointKey","startReplicationDownstream","docStateToWriteDoc","getUnderlyingPersistentStorage","writeDocToDocState","startReplicationUpstream","fillWriteDataForAttachmentsChange","getChangedDocumentsSince","replicateRxStorageInstance","input","forkInstance","metaInstance","checkpointKeyPromise","state","primaryPath","schema","primaryKey","hasAttachments","attachments","checkpointKey","downstreamBulkWriteFlag","then","events","canceled","active","down","up","processed","resolvedConflicts","error","stats","addNewTask","downstreamProcessChanges","downstreamResyncOnce","masterChangeStreamEmit","persistFromMaster","forkChangeStreamEmit","persistToMaster","persistToMasterConflictWrites","persistToMasterHadConflicts","processTasks","upstreamInitialSync","firstSyncDone","streamQueue","checkpointQueue","lastCheckpointDoc","awaitRxStorageReplicationFirstInSync","pipe","v","awaitRxStorageReplicationInSync","replicationState","Promise","all","awaitRxStorageReplicationIdle","rxStorageInstanceToReplicationHandler","instance","conflictHandler","databaseInstanceToken","keepMeta","replicationHandler","masterChangeStream$","changeStream","eventBulk","ret","checkpoint","documents","map","event","docData","documentData","undefined","masterChangesSince","batchSize","result","length","plainDocumentData","masterWrite","rows","rowById","forEach","row","docId","newDocumentState","ids","Object","keys","masterDocsStateList","findDocumentsById","masterDocsState","Map","doc","set","conflicts","writeRows","entries","id","masterState","get","push","document","assumedMasterState","realMasterState","isEqual","previous","bulkWrite","err","status","Error","documentInDb","cancelRxStorageReplication","next","complete"],"sources":["../../../src/replication-protocol/index.ts"],"sourcesContent":["/**\n * These files contain the replication protocol.\n * It can be used to replicated RxStorageInstances or RxCollections\n * or even to do a client(s)-server replication.\n */\n\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n firstValueFrom,\n mergeMap,\n Subject\n} from 'rxjs';\nimport {\n getPrimaryFieldOfPrimaryKey\n} from '../rx-schema-helper.ts';\nimport type {\n BulkWriteRow,\n ById,\n DocumentsWithCheckpoint,\n RxConflictHandler,\n RxDocumentData,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n WithDeleted\n} from '../types/index.d.ts';\nimport {\n clone,\n ensureNotFalsy,\n flatClone,\n PROMISE_RESOLVE_VOID\n} from '../plugins/utils/index.ts';\nimport {\n getCheckpointKey\n} from './checkpoint.ts';\nimport { startReplicationDownstream } from './downstream.ts';\nimport { docStateToWriteDoc, getUnderlyingPersistentStorage, writeDocToDocState } from './helper.ts';\nimport { startReplicationUpstream } from './upstream.ts';\nimport { fillWriteDataForAttachmentsChange } from '../plugins/attachments/index.ts';\nimport { getChangedDocumentsSince } from '../rx-storage-helper.ts';\n\n\nexport * from './checkpoint.ts';\nexport * from './downstream.ts';\nexport * from './upstream.ts';\nexport * from './meta-instance.ts';\nexport * from './conflicts.ts';\nexport * from './helper.ts';\n\n\nexport function replicateRxStorageInstance(\n input: RxStorageInstanceReplicationInput\n): RxStorageInstanceReplicationState {\n input = flatClone(input);\n input.forkInstance = getUnderlyingPersistentStorage(input.forkInstance);\n input.metaInstance = getUnderlyingPersistentStorage(input.metaInstance);\n const checkpointKeyPromise = getCheckpointKey(input);\n const state: RxStorageInstanceReplicationState = {\n primaryPath: getPrimaryFieldOfPrimaryKey(input.forkInstance.schema.primaryKey),\n hasAttachments: !!input.forkInstance.schema.attachments,\n input,\n checkpointKey: checkpointKeyPromise,\n downstreamBulkWriteFlag: checkpointKeyPromise.then(checkpointKey => 'replication-downstream-' + checkpointKey),\n events: {\n canceled: new BehaviorSubject(false),\n active: {\n down: new BehaviorSubject(true),\n up: new BehaviorSubject(true)\n },\n processed: {\n down: new Subject(),\n up: new Subject()\n },\n resolvedConflicts: new Subject(),\n error: new Subject()\n },\n stats: {\n down: {\n addNewTask: 0,\n downstreamProcessChanges: 0,\n downstreamResyncOnce: 0,\n masterChangeStreamEmit: 0,\n persistFromMaster: 0\n },\n up: {\n forkChangeStreamEmit: 0,\n persistToMaster: 0,\n persistToMasterConflictWrites: 0,\n persistToMasterHadConflicts: 0,\n processTasks: 0,\n upstreamInitialSync: 0\n }\n },\n firstSyncDone: {\n down: new BehaviorSubject(false),\n up: new BehaviorSubject(false)\n },\n streamQueue: {\n down: PROMISE_RESOLVE_VOID,\n up: PROMISE_RESOLVE_VOID\n },\n checkpointQueue: PROMISE_RESOLVE_VOID,\n lastCheckpointDoc: {}\n };\n\n startReplicationDownstream(state);\n startReplicationUpstream(state);\n return state;\n}\n\nexport function awaitRxStorageReplicationFirstInSync(\n state: RxStorageInstanceReplicationState\n): Promise {\n return firstValueFrom(\n combineLatest([\n state.firstSyncDone.down.pipe(\n filter(v => !!v)\n ),\n state.firstSyncDone.up.pipe(\n filter(v => !!v)\n )\n ])\n ).then(() => { });\n}\n\nexport function awaitRxStorageReplicationInSync(\n replicationState: RxStorageInstanceReplicationState\n) {\n return Promise.all([\n replicationState.streamQueue.up,\n replicationState.streamQueue.down,\n replicationState.checkpointQueue\n ]);\n}\n\n\nexport async function awaitRxStorageReplicationIdle(\n state: RxStorageInstanceReplicationState\n) {\n await awaitRxStorageReplicationFirstInSync(state);\n while (true) {\n const { down, up } = state.streamQueue;\n await Promise.all([\n up,\n down\n ]);\n /**\n * If the Promises have not been reassigned\n * after awaiting them, we know that the replication\n * is in idle state at this point in time.\n */\n if (\n down === state.streamQueue.down &&\n up === state.streamQueue.up\n ) {\n return;\n }\n }\n}\n\n\nexport function rxStorageInstanceToReplicationHandler(\n instance: RxStorageInstance,\n conflictHandler: RxConflictHandler,\n databaseInstanceToken: string,\n /**\n * If set to true,\n * the _meta.lwt from the pushed documents is kept.\n * (Used in the migration to ensure checkpoints are still valid)\n */\n keepMeta: boolean = false\n): RxReplicationHandler {\n instance = getUnderlyingPersistentStorage(instance);\n\n const hasAttachments = !!instance.schema.attachments;\n const primaryPath = getPrimaryFieldOfPrimaryKey(instance.schema.primaryKey);\n const replicationHandler: RxReplicationHandler = {\n masterChangeStream$: instance.changeStream().pipe(\n mergeMap(async (eventBulk) => {\n const ret: DocumentsWithCheckpoint = {\n checkpoint: eventBulk.checkpoint,\n documents: await Promise.all(\n eventBulk.events.map(async (event) => {\n let docData = writeDocToDocState(event.documentData, hasAttachments, keepMeta);\n if (hasAttachments) {\n docData = await fillWriteDataForAttachmentsChange(\n primaryPath,\n instance,\n clone(docData),\n /**\n * Notice that the master never knows\n * the client state of the document.\n * Therefore we always send all attachments data.\n */\n undefined\n );\n }\n\n return docData;\n })\n )\n };\n return ret;\n })\n ),\n masterChangesSince(\n checkpoint,\n batchSize\n ) {\n return getChangedDocumentsSince(\n instance,\n batchSize,\n checkpoint\n ).then(async (result) => {\n return {\n checkpoint: result.documents.length > 0 ? result.checkpoint : checkpoint,\n documents: await Promise.all(\n result.documents.map(async (plainDocumentData) => {\n let docData = writeDocToDocState(plainDocumentData, hasAttachments, keepMeta);\n if (hasAttachments) {\n docData = await fillWriteDataForAttachmentsChange(\n primaryPath,\n instance,\n clone(docData),\n /**\n * Notice the the master never knows\n * the client state of the document.\n * Therefore we always send all attachments data.\n */\n undefined\n );\n }\n return docData;\n })\n )\n };\n });\n },\n async masterWrite(\n rows\n ) {\n const rowById: ById> = {};\n rows.forEach(row => {\n const docId: string = (row.newDocumentState as any)[primaryPath];\n rowById[docId] = row;\n });\n const ids = Object.keys(rowById);\n\n const masterDocsStateList = await instance.findDocumentsById(\n ids,\n true\n );\n const masterDocsState = new Map>();\n masterDocsStateList.forEach(doc => masterDocsState.set((doc as any)[primaryPath], doc));\n const conflicts: WithDeleted[] = [];\n const writeRows: BulkWriteRow[] = [];\n await Promise.all(\n Object.entries(rowById)\n .map(async ([id, row]) => {\n const masterState = masterDocsState.get(id);\n if (!masterState) {\n writeRows.push({\n document: docStateToWriteDoc(databaseInstanceToken, hasAttachments, keepMeta, row.newDocumentState)\n });\n } else if (\n masterState &&\n !row.assumedMasterState\n ) {\n conflicts.push(writeDocToDocState(masterState, hasAttachments, keepMeta));\n } else if (\n (await conflictHandler({\n realMasterState: writeDocToDocState(masterState, hasAttachments, keepMeta),\n newDocumentState: ensureNotFalsy(row.assumedMasterState)\n }, 'rxStorageInstanceToReplicationHandler-masterWrite')).isEqual === true\n ) {\n writeRows.push({\n previous: masterState,\n document: docStateToWriteDoc(databaseInstanceToken, hasAttachments, keepMeta, row.newDocumentState, masterState)\n });\n } else {\n conflicts.push(writeDocToDocState(masterState, hasAttachments, keepMeta));\n }\n })\n );\n\n if (writeRows.length > 0) {\n const result = await instance.bulkWrite(\n writeRows,\n 'replication-master-write'\n );\n result.error.forEach(err => {\n if (err.status !== 409) {\n throw new Error('non conflict error');\n } else {\n conflicts.push(\n writeDocToDocState(ensureNotFalsy(err.documentInDb), hasAttachments, keepMeta)\n );\n }\n });\n }\n return conflicts;\n }\n };\n\n return replicationHandler;\n}\n\n\nexport async function cancelRxStorageReplication(\n replicationState: RxStorageInstanceReplicationState\n) {\n replicationState.events.canceled.next(true);\n replicationState.events.active.up.complete();\n replicationState.events.active.down.complete();\n replicationState.events.processed.up.complete();\n replicationState.events.processed.down.complete();\n replicationState.events.resolvedConflicts.complete();\n replicationState.events.canceled.complete();\n await replicationState.checkpointQueue;\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAGA,SACIA,eAAe,EACfC,aAAa,EACbC,MAAM,EACNC,cAAc,EACdC,QAAQ,EACRC,OAAO,QACJ,MAAM;AACb,SACIC,2BAA2B,QACxB,wBAAwB;AAc/B,SACIC,KAAK,EACLC,cAAc,EACdC,SAAS,EACTC,oBAAoB,QACjB,2BAA2B;AAClC,SACIC,gBAAgB,QACb,iBAAiB;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,EAAE,CAACqF,QAAQ,CAAC,CAAC;EAC5C7D,gBAAgB,CAAC5B,MAAM,CAACE,MAAM,CAACC,IAAI,CAACsF,QAAQ,CAAC,CAAC;EAC9C7D,gBAAgB,CAAC5B,MAAM,CAACK,SAAS,CAACD,EAAE,CAACqF,QAAQ,CAAC,CAAC;EAC/C7D,gBAAgB,CAAC5B,MAAM,CAACK,SAAS,CAACF,IAAI,CAACsF,QAAQ,CAAC,CAAC;EACjD7D,gBAAgB,CAAC5B,MAAM,CAACM,iBAAiB,CAACmF,QAAQ,CAAC,CAAC;EACpD7D,gBAAgB,CAAC5B,MAAM,CAACC,QAAQ,CAACwF,QAAQ,CAAC,CAAC;EAC3C,MAAM7D,gBAAgB,CAACN,eAAe;AAC1C"} \ No newline at end of file +{"version":3,"file":"index.js","names":["BehaviorSubject","combineLatest","filter","firstValueFrom","mergeMap","Subject","getPrimaryFieldOfPrimaryKey","clone","ensureNotFalsy","flatClone","PROMISE_RESOLVE_VOID","getCheckpointKey","startReplicationDownstream","docStateToWriteDoc","getUnderlyingPersistentStorage","writeDocToDocState","startReplicationUpstream","fillWriteDataForAttachmentsChange","getChangedDocumentsSince","replicateRxStorageInstance","input","forkInstance","metaInstance","checkpointKeyPromise","state","primaryPath","schema","primaryKey","hasAttachments","attachments","checkpointKey","downstreamBulkWriteFlag","then","events","canceled","active","down","up","processed","resolvedConflicts","error","stats","addNewTask","downstreamProcessChanges","downstreamResyncOnce","masterChangeStreamEmit","persistFromMaster","forkChangeStreamEmit","persistToMaster","persistToMasterConflictWrites","persistToMasterHadConflicts","processTasks","upstreamInitialSync","firstSyncDone","streamQueue","checkpointQueue","lastCheckpointDoc","awaitRxStorageReplicationFirstInSync","pipe","v","awaitRxStorageReplicationInSync","replicationState","Promise","all","awaitRxStorageReplicationIdle","rxStorageInstanceToReplicationHandler","instance","conflictHandler","databaseInstanceToken","keepMeta","replicationHandler","masterChangeStream$","changeStream","eventBulk","ret","checkpoint","documents","map","event","docData","documentData","undefined","masterChangesSince","batchSize","result","length","plainDocumentData","masterWrite","rows","rowById","forEach","row","docId","newDocumentState","ids","Object","keys","masterDocsStateList","findDocumentsById","masterDocsState","Map","doc","set","conflicts","writeRows","entries","id","masterState","get","push","document","assumedMasterState","realMasterState","isEqual","previous","bulkWrite","err","status","Error","documentInDb","cancelRxStorageReplication","next","complete"],"sources":["../../../src/replication-protocol/index.ts"],"sourcesContent":["/**\n * These files contain the replication protocol.\n * It can be used to replicated RxStorageInstances or RxCollections\n * or even to do a client(s)-server replication.\n */\n\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n firstValueFrom,\n mergeMap,\n Subject\n} from 'rxjs';\nimport {\n getPrimaryFieldOfPrimaryKey\n} from '../rx-schema-helper.ts';\nimport type {\n BulkWriteRow,\n ById,\n DocumentsWithCheckpoint,\n RxConflictHandler,\n RxDocumentData,\n RxReplicationHandler,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationInput,\n RxStorageInstanceReplicationState,\n WithDeleted\n} from '../types/index.d.ts';\nimport {\n clone,\n ensureNotFalsy,\n flatClone,\n PROMISE_RESOLVE_VOID\n} from '../plugins/utils/index.ts';\nimport {\n getCheckpointKey\n} from './checkpoint.ts';\nimport { startReplicationDownstream } from './downstream.ts';\nimport { docStateToWriteDoc, getUnderlyingPersistentStorage, writeDocToDocState } from './helper.ts';\nimport { startReplicationUpstream } from './upstream.ts';\nimport { fillWriteDataForAttachmentsChange } from '../plugins/attachments/index.ts';\nimport { getChangedDocumentsSince } from '../rx-storage-helper.ts';\n\n\nexport * from './checkpoint.ts';\nexport * from './downstream.ts';\nexport * from './upstream.ts';\nexport * from './meta-instance.ts';\nexport * from './conflicts.ts';\nexport * from './helper.ts';\n\n\nexport function replicateRxStorageInstance(\n input: RxStorageInstanceReplicationInput\n): RxStorageInstanceReplicationState {\n input = flatClone(input);\n input.forkInstance = getUnderlyingPersistentStorage(input.forkInstance);\n input.metaInstance = getUnderlyingPersistentStorage(input.metaInstance);\n const checkpointKeyPromise = getCheckpointKey(input);\n const state: RxStorageInstanceReplicationState = {\n primaryPath: getPrimaryFieldOfPrimaryKey(input.forkInstance.schema.primaryKey),\n hasAttachments: !!input.forkInstance.schema.attachments,\n input,\n checkpointKey: checkpointKeyPromise,\n downstreamBulkWriteFlag: checkpointKeyPromise.then(checkpointKey => 'replication-downstream-' + checkpointKey),\n events: {\n canceled: new BehaviorSubject(false),\n active: {\n down: new BehaviorSubject(true),\n up: new BehaviorSubject(true)\n },\n processed: {\n down: new Subject(),\n up: new Subject()\n },\n resolvedConflicts: new Subject(),\n error: new Subject()\n },\n stats: {\n down: {\n addNewTask: 0,\n downstreamProcessChanges: 0,\n downstreamResyncOnce: 0,\n masterChangeStreamEmit: 0,\n persistFromMaster: 0\n },\n up: {\n forkChangeStreamEmit: 0,\n persistToMaster: 0,\n persistToMasterConflictWrites: 0,\n persistToMasterHadConflicts: 0,\n processTasks: 0,\n upstreamInitialSync: 0\n }\n },\n firstSyncDone: {\n down: new BehaviorSubject(false),\n up: new BehaviorSubject(false)\n },\n streamQueue: {\n down: PROMISE_RESOLVE_VOID,\n up: PROMISE_RESOLVE_VOID\n },\n checkpointQueue: PROMISE_RESOLVE_VOID,\n lastCheckpointDoc: {}\n };\n\n startReplicationDownstream(state);\n startReplicationUpstream(state);\n return state;\n}\n\nexport function awaitRxStorageReplicationFirstInSync(\n state: RxStorageInstanceReplicationState\n): Promise {\n return firstValueFrom(\n combineLatest([\n state.firstSyncDone.down.pipe(\n filter(v => !!v)\n ),\n state.firstSyncDone.up.pipe(\n filter(v => !!v)\n )\n ])\n ).then(() => { });\n}\n\nexport function awaitRxStorageReplicationInSync(\n replicationState: RxStorageInstanceReplicationState\n) {\n return Promise.all([\n replicationState.streamQueue.up,\n replicationState.streamQueue.down,\n replicationState.checkpointQueue\n ]);\n}\n\n\nexport async function awaitRxStorageReplicationIdle(\n state: RxStorageInstanceReplicationState\n) {\n await awaitRxStorageReplicationFirstInSync(state);\n while (true) {\n const { down, up } = state.streamQueue;\n await Promise.all([\n up,\n down\n ]);\n /**\n * If the Promises have not been reassigned\n * after awaiting them, we know that the replication\n * is in idle state at this point in time.\n */\n if (\n down === state.streamQueue.down &&\n up === state.streamQueue.up\n ) {\n return;\n }\n }\n}\n\n\nexport function rxStorageInstanceToReplicationHandler(\n instance: RxStorageInstance,\n conflictHandler: RxConflictHandler,\n databaseInstanceToken: string,\n /**\n * If set to true,\n * the _meta.lwt from the pushed documents is kept.\n * (Used in the migration to ensure checkpoints are still valid)\n */\n keepMeta: boolean = false\n): RxReplicationHandler {\n instance = getUnderlyingPersistentStorage(instance);\n\n const hasAttachments = !!instance.schema.attachments;\n const primaryPath = getPrimaryFieldOfPrimaryKey(instance.schema.primaryKey);\n const replicationHandler: RxReplicationHandler = {\n masterChangeStream$: instance.changeStream().pipe(\n mergeMap(async (eventBulk) => {\n const ret: DocumentsWithCheckpoint = {\n checkpoint: eventBulk.checkpoint,\n documents: await Promise.all(\n eventBulk.events.map(async (event) => {\n let docData = writeDocToDocState(event.documentData, hasAttachments, keepMeta);\n if (hasAttachments) {\n docData = await fillWriteDataForAttachmentsChange(\n primaryPath,\n instance,\n clone(docData),\n /**\n * Notice that the master never knows\n * the client state of the document.\n * Therefore we always send all attachments data.\n */\n undefined\n );\n }\n\n return docData;\n })\n )\n };\n return ret;\n })\n ),\n masterChangesSince(\n checkpoint,\n batchSize\n ) {\n return getChangedDocumentsSince(\n instance,\n batchSize,\n checkpoint\n ).then(async (result) => {\n return {\n checkpoint: result.documents.length > 0 ? result.checkpoint : checkpoint,\n documents: await Promise.all(\n result.documents.map(async (plainDocumentData) => {\n let docData = writeDocToDocState(plainDocumentData, hasAttachments, keepMeta);\n if (hasAttachments) {\n docData = await fillWriteDataForAttachmentsChange(\n primaryPath,\n instance,\n clone(docData),\n /**\n * Notice the the master never knows\n * the client state of the document.\n * Therefore we always send all attachments data.\n */\n undefined\n );\n }\n return docData;\n })\n )\n };\n });\n },\n async masterWrite(\n rows\n ) {\n const rowById: ById> = {};\n rows.forEach(row => {\n const docId: string = (row.newDocumentState as any)[primaryPath];\n rowById[docId] = row;\n });\n const ids = Object.keys(rowById);\n\n const masterDocsStateList = await instance.findDocumentsById(\n ids,\n true\n );\n const masterDocsState = new Map>();\n masterDocsStateList.forEach(doc => masterDocsState.set((doc as any)[primaryPath], doc));\n const conflicts: WithDeleted[] = [];\n const writeRows: BulkWriteRow[] = [];\n await Promise.all(\n Object.entries(rowById)\n .map(async ([id, row]) => {\n const masterState = masterDocsState.get(id);\n if (!masterState) {\n writeRows.push({\n document: docStateToWriteDoc(databaseInstanceToken, hasAttachments, keepMeta, row.newDocumentState)\n });\n } else if (\n masterState &&\n !row.assumedMasterState\n ) {\n conflicts.push(writeDocToDocState(masterState, hasAttachments, keepMeta));\n } else if (\n (await conflictHandler({\n realMasterState: writeDocToDocState(masterState, hasAttachments, keepMeta),\n newDocumentState: ensureNotFalsy(row.assumedMasterState)\n }, 'rxStorageInstanceToReplicationHandler-masterWrite')).isEqual === true\n ) {\n writeRows.push({\n previous: masterState,\n document: docStateToWriteDoc(databaseInstanceToken, hasAttachments, keepMeta, row.newDocumentState, masterState)\n });\n } else {\n conflicts.push(writeDocToDocState(masterState, hasAttachments, keepMeta));\n }\n })\n );\n\n if (writeRows.length > 0) {\n const result = await instance.bulkWrite(\n writeRows,\n 'replication-master-write'\n );\n\n result.error.forEach(err => {\n if (err.status !== 409) {\n throw new Error('non conflict error');\n } else {\n conflicts.push(\n writeDocToDocState(ensureNotFalsy(err.documentInDb), hasAttachments, keepMeta)\n );\n }\n });\n }\n return conflicts;\n }\n };\n\n return replicationHandler;\n}\n\n\nexport async function cancelRxStorageReplication(\n replicationState: RxStorageInstanceReplicationState\n) {\n replicationState.events.canceled.next(true);\n replicationState.events.active.up.complete();\n replicationState.events.active.down.complete();\n replicationState.events.processed.up.complete();\n replicationState.events.processed.down.complete();\n replicationState.events.resolvedConflicts.complete();\n replicationState.events.canceled.complete();\n await replicationState.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,CACjF,CAAC;UACL;QACJ,CAAC,CAAC;MACN;MACA,OAAOkC,SAAS;IACpB;EACJ,CAAC;EAED,OAAOjC,kBAAkB;AAC7B;AAGA,OAAO,eAAekD,0BAA0BA,CAC5C3D,gBAAwD,EAC1D;EACEA,gBAAgB,CAAC5B,MAAM,CAACC,QAAQ,CAACuF,IAAI,CAAC,IAAI,CAAC;EAC3C5D,gBAAgB,CAAC5B,MAAM,CAACE,MAAM,CAACE,EAAE,CAACqF,QAAQ,CAAC,CAAC;EAC5C7D,gBAAgB,CAAC5B,MAAM,CAACE,MAAM,CAACC,IAAI,CAACsF,QAAQ,CAAC,CAAC;EAC9C7D,gBAAgB,CAAC5B,MAAM,CAACK,SAAS,CAACD,EAAE,CAACqF,QAAQ,CAAC,CAAC;EAC/C7D,gBAAgB,CAAC5B,MAAM,CAACK,SAAS,CAACF,IAAI,CAACsF,QAAQ,CAAC,CAAC;EACjD7D,gBAAgB,CAAC5B,MAAM,CAACM,iBAAiB,CAACmF,QAAQ,CAAC,CAAC;EACpD7D,gBAAgB,CAAC5B,MAAM,CAACC,QAAQ,CAACwF,QAAQ,CAAC,CAAC;EAC3C,MAAM7D,gBAAgB,CAACN,eAAe;AAC1C"} \ No newline at end of file diff --git a/dist/esm/rx-collection.js b/dist/esm/rx-collection.js index a40351ba077..8fa8c1e8920 100644 --- a/dist/esm/rx-collection.js +++ b/dist/esm/rx-collection.js @@ -110,10 +110,10 @@ export var RxCollectionBase = /*#__PURE__*/function () { // overwritten by migration-plugin ; _proto.migrationNeeded = function migrationNeeded() { - throw pluginMissing('migration'); + throw pluginMissing('migration-schema'); }; _proto.getMigrationState = function getMigrationState() { - throw pluginMissing('migration'); + throw pluginMissing('migration-schema'); }; _proto.startMigration = function startMigration(batchSize = 10) { return this.getMigrationState().startMigration(batchSize); diff --git a/dist/esm/rx-collection.js.map b/dist/esm/rx-collection.js.map index d082fe62ce8..f2f17767a56 100644 --- a/dist/esm/rx-collection.js.map +++ b/dist/esm/rx-collection.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-collection.js","names":["filter","map","mergeMap","ucfirst","flatClone","promiseSeries","pluginMissing","ensureNotFalsy","getFromMapOrThrow","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_VOID","fillObjectDataBeforeInsert","createRxCollectionStorageInstance","removeCollectionStorages","createRxQuery","_getDefaultQuery","newRxError","newRxTypeError","DocumentCache","mapDocumentsDataToCacheDocs","createQueryCache","defaultCacheReplacementPolicy","createChangeEventBuffer","runAsyncPluginHooks","runPluginHooks","createNewRxDocument","getWrappedStorageInstance","storageChangeEventToRxChangeEvent","throwIfIsStorageWriteError","defaultConflictHandler","IncrementalWriteQueue","beforeDocumentUpdateWrite","overwritable","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","statics","conflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","_incrementalUpsertQueues","Map","synced","hooks","_subs","_docCache","_queryCache","$","checkpoint$","_changeEventBuffer","onDestroy","destroyed","_applyHookFunctions","asRxCollection","_proto","prototype","prepare","jsonSchema","primaryPath","newData","oldData","result","_runHooks","collectionEventBulks$","eventBulks$","pipe","changeEventBulk","collectionName","events","checkpoint","cE","isLocal","docData","databaseStorageToken","storageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","ev","databaseToken","token","context","endTime","startTime","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","cleanup","_minimumDeletedTime","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","insertResult","success","docsData","length","useDocs","useDocData","docs","hasHooks","Promise","all","doc","insertRows","row","document","results","bulkWrite","rxDocuments","docsMap","forEach","set","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","_deleted","previous","successIds","d","bulkUpsert","insertData","useJsonByDocId","useJson","slice","err","status","documentId","writeData","docDataInDb","documentInDb","getCachedRxDocument","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","query","findOne","isArray","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addHook","when","key","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","_runHooksSync","promiseWait","time","ret","res","timeout","setTimeout","delete","add","destroy","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","remove","storage","internalStore","password","hashFunction","_createClass","operation","collection","colProto","Object","getPrototypeOf","fnName","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","isDevMode","entries","funName","defineProperty","version","creator","catch","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from './plugins/utils/index.ts';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper.ts';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query.ts';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error.ts';\nimport type {\n RxMigrationState\n} from './plugins/migration-schema/index.ts';\nimport {\n DocumentCache, mapDocumentsDataToCacheDocs\n} from './doc-cache.ts';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache.ts';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer.ts';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks.ts';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageWriteError,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex,\n MigrationStrategies\n} from './types/index.d.ts';\n\nimport {\n RxSchema\n} from './rx-schema.ts';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { defaultConflictHandler } from './replication-protocol/index.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; }\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: MigrationStrategies = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _incrementalUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocumentCache = {} as any;\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public checkpoint$: Observable = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n this.incrementalWriteQueue = new IncrementalWriteQueue(\n this.storageInstance,\n this.schema.primaryPath,\n (newData, oldData) => beforeDocumentUpdateWrite(this as any, newData, oldData),\n result => this._runHooks('post', 'save', result)\n );\n\n const collectionEventBulks$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n );\n this.$ = collectionEventBulks$.pipe(\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this.checkpoint$ = collectionEventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.$.pipe(filter(cE => !cE.isLocal)),\n docData => createNewRxDocument(this.asRxCollection, docData)\n );\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context,\n endTime: eventBulk.endTime,\n startTime: eventBulk.startTime\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n /**\n * Manually call the cleanup function of the storage.\n * @link https://rxdb.info/cleanup.html\n */\n cleanup(_minimumDeletedTime?: number): Promise {\n throw pluginMissing('cleanup');\n }\n\n // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration');\n }\n getMigrationState(): RxMigrationState {\n throw pluginMissing('migration');\n }\n startMigration(batchSize: number = 10): Promise {\n return this.getMigrationState().startMigration(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getMigrationState().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n const writeResult = await this.bulkInsert([json as any]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, (json as any)[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const primaryPath = this.schema.primaryPath;\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n const row: BulkWriteRow = { document: doc };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const rxDocuments = mapDocumentsDataToCacheDocs(this._docCache, results.success);\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n docs.forEach(doc => {\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids).exec();\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = rxDocument.toMutableJSON(true) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = results.success.map(d => d[primaryPath] as string);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments = successIds.map(id => getFromMapOrThrow(rxDocumentMap, id));\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n const success = insertResult.success.slice(0);\n const error: RxStorageWriteError[] = [];\n\n // update the ones that existed already\n await Promise.all(\n insertResult.error.map(async (err) => {\n if (err.status !== 409) {\n error.push(err);\n } else {\n const id = err.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(err.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n success.push(newDoc);\n }\n })\n );\n return {\n error,\n success\n };\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n async upsert(json: Partial): Promise> {\n const bulkResult = await this.bulkUpsert([json]);\n throwIfIsStorageWriteError(\n this.asRxCollection,\n (json as any)[this.schema.primaryPath],\n json as any,\n bulkResult.error[0]\n );\n return bulkResult.success[0];\n }\n\n /**\n * upserts to a RxDocument, uses incrementalModify if document already exists\n */\n incrementalUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[]\n > {\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\n // TODO move this check to dev-mode plugin\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n\n // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\n > {\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.password,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _incrementalUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.incrementalModify((_innerDoc) => {\n return json;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _incrementalUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary);\n if (docDataFromCache) {\n return Promise.resolve({\n doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache),\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password,\n devMode: overwritable.isDevMode()\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxColl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OAAO,CAAC,CAAC,CACToC,IAAI,CAAC,MAAM;MACR;MACAoI,MAAM,CACDiB,OAAO,CAAC/M,OAAO,CAAC,CAChB4F,OAAO,CAAC,CAAC,CAACoH,OAAO,EAAEvD,GAAG,CAAC,KAAK;QACzBqC,MAAM,CAACmB,cAAc,CAACrB,UAAU,EAAEoB,OAAO,EAAE;UACvClH,GAAG,EAAEA,CAAA,KAAO2D,GAAG,CAASI,IAAI,CAAC+B,UAAU;QAC3C,CAAC,CAAC;MACN,CAAC,CAAC;MAEN,IAAIrB,GAAG,GAAG5M,oBAAoB;MAC9B,IAAI4O,WAAW,IAAIX,UAAU,CAACpM,MAAM,CAAC0N,OAAO,KAAK,CAAC,EAAE;QAChD3C,GAAG,GAAGqB,UAAU,CAACzH,cAAc,CAAC,CAAC;MACrC;MACA,OAAOoG,GAAG;IACd,CAAC,CAAC,CACD7G,IAAI,CAAC,MAAM;MACRjF,cAAc,CAAC,oBAAoB,EAAE;QACjCmN,UAAU;QACVuB,OAAO,EAAE;UACL5N,IAAI;UACJC,MAAM;UACNU,eAAe;UACfR,uBAAuB;UACvBC,mBAAmB;UACnBC,OAAO;UACPC,WAAW;UACXC,OAAO;UACPC,sBAAsB;UACtByM,cAAc;UACdxM;QACJ;MACJ,CAAC,CAAC;MACF,OAAO4L,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAICwB,KAAK,CAAC9F,GAAG,IAAI;MACV,OAAOpH,eAAe,CAAC+K,KAAK,CAAC,CAAC,CACzBvH,IAAI,CAAC,MAAMwB,OAAO,CAACmI,MAAM,CAAC/F,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEA,OAAO,SAASgG,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYlO,gBAAgB;AAC1C"} \ No newline at end of file +{"version":3,"file":"rx-collection.js","names":["filter","map","mergeMap","ucfirst","flatClone","promiseSeries","pluginMissing","ensureNotFalsy","getFromMapOrThrow","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_VOID","fillObjectDataBeforeInsert","createRxCollectionStorageInstance","removeCollectionStorages","createRxQuery","_getDefaultQuery","newRxError","newRxTypeError","DocumentCache","mapDocumentsDataToCacheDocs","createQueryCache","defaultCacheReplacementPolicy","createChangeEventBuffer","runAsyncPluginHooks","runPluginHooks","createNewRxDocument","getWrappedStorageInstance","storageChangeEventToRxChangeEvent","throwIfIsStorageWriteError","defaultConflictHandler","IncrementalWriteQueue","beforeDocumentUpdateWrite","overwritable","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","statics","conflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","_incrementalUpsertQueues","Map","synced","hooks","_subs","_docCache","_queryCache","$","checkpoint$","_changeEventBuffer","onDestroy","destroyed","_applyHookFunctions","asRxCollection","_proto","prototype","prepare","jsonSchema","primaryPath","newData","oldData","result","_runHooks","collectionEventBulks$","eventBulks$","pipe","changeEventBulk","collectionName","events","checkpoint","cE","isLocal","docData","databaseStorageToken","storageToken","subDocs","changeStream","subscribe","eventBulk","id","internal","ev","databaseToken","token","context","endTime","startTime","$emit","push","conflictResultionTasks","task","input","then","output","resolveConflictResultionTask","cleanup","_minimumDeletedTime","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","insertResult","success","docsData","length","useDocs","useDocData","docs","hasHooks","Promise","all","doc","insertRows","row","document","results","bulkWrite","rxDocuments","docsMap","forEach","set","get","primary","bulkRemove","ids","rxDocumentMap","findByIds","exec","Array","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","_deleted","previous","successIds","d","bulkUpsert","insertData","useJsonByDocId","useJson","slice","err","status","documentId","writeData","docDataInDb","documentInDb","getCachedRxDocument","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","find","queryObj","query","findOne","isArray","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addHook","when","key","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","_runHooksSync","promiseWait","time","ret","res","timeout","setTimeout","delete","add","destroy","clearTimeout","requestIdlePromise","fn","close","sub","unsubscribe","collections","remove","storage","internalStore","password","hashFunction","_createClass","operation","collection","colProto","Object","getPrototypeOf","fnName","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","isDevMode","entries","funName","defineProperty","version","creator","catch","reject","isRxCollection","obj"],"sources":["../../src/rx-collection.ts"],"sourcesContent":["import {\n filter,\n map,\n mergeMap\n} from 'rxjs';\n\nimport {\n ucfirst,\n flatClone,\n promiseSeries,\n pluginMissing,\n ensureNotFalsy,\n getFromMapOrThrow,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_VOID\n} from './plugins/utils/index.ts';\nimport {\n fillObjectDataBeforeInsert,\n createRxCollectionStorageInstance,\n removeCollectionStorages\n} from './rx-collection-helper.ts';\nimport {\n createRxQuery,\n _getDefaultQuery\n} from './rx-query.ts';\nimport {\n newRxError,\n newRxTypeError\n} from './rx-error.ts';\nimport type {\n RxMigrationState\n} from './plugins/migration-schema/index.ts';\nimport {\n DocumentCache, mapDocumentsDataToCacheDocs\n} from './doc-cache.ts';\nimport {\n QueryCache,\n createQueryCache,\n defaultCacheReplacementPolicy\n} from './query-cache.ts';\nimport {\n ChangeEventBuffer,\n createChangeEventBuffer\n} from './change-event-buffer.ts';\nimport {\n runAsyncPluginHooks,\n runPluginHooks\n} from './hooks.ts';\n\nimport {\n Subscription,\n Observable\n} from 'rxjs';\n\nimport type {\n KeyFunctionMap,\n RxCollection,\n RxDatabase,\n RxQuery,\n RxDocument,\n RxDumpCollection,\n RxDumpCollectionAny,\n MangoQuery,\n MangoQueryNoLimit,\n RxCacheReplacementPolicy,\n RxStorageWriteError,\n RxDocumentData,\n RxStorageInstanceCreationParams,\n BulkWriteRow,\n RxChangeEvent,\n RxChangeEventInsert,\n RxChangeEventUpdate,\n RxChangeEventDelete,\n RxStorageInstance,\n CollectionsOfDatabase,\n RxChangeEventBulk,\n RxLocalDocumentData,\n RxDocumentBase,\n RxConflictHandler,\n MaybePromise,\n CRDTEntry,\n MangoQuerySelectorAndIndex,\n MigrationStrategies\n} from './types/index.d.ts';\n\nimport {\n RxSchema\n} from './rx-schema.ts';\n\nimport {\n createNewRxDocument\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n storageChangeEventToRxChangeEvent,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { defaultConflictHandler } from './replication-protocol/index.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; }\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n constructor(\n public database: RxDatabase,\n public name: string,\n public schema: RxSchema,\n public internalStorageInstance: RxStorageInstance,\n public instanceCreationOptions: InstanceCreationOptions = {} as any,\n public migrationStrategies: MigrationStrategies = {},\n public methods: KeyFunctionMap = {},\n public attachments: KeyFunctionMap = {},\n public options: any = {},\n public cacheReplacementPolicy: RxCacheReplacementPolicy = defaultCacheReplacementPolicy,\n public statics: KeyFunctionMap = {},\n public conflictHandler: RxConflictHandler = defaultConflictHandler\n ) {\n _applyHookFunctions(this.asRxCollection);\n }\n\n get insert$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'INSERT')\n ) as any;\n }\n get update$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'UPDATE')\n ) as any;\n }\n get remove$(): Observable> {\n return this.$.pipe(\n filter(cE => cE.operation === 'DELETE')\n ) as any;\n }\n\n public _incrementalUpsertQueues: Map> = new Map();\n // defaults\n public synced: boolean = false;\n public hooks: {\n [key in HookKeyType]: {\n [when in HookWhenType]: {\n series: Function[];\n parallel: Function[];\n };\n }\n } = {} as any;\n public _subs: Subscription[] = [];\n\n public _docCache: DocumentCache = {} as any;\n\n public _queryCache: QueryCache = createQueryCache();\n public $: Observable> = {} as any;\n public checkpoint$: Observable = {} as any;\n public _changeEventBuffer: ChangeEventBuffer = {} as ChangeEventBuffer;\n\n\n\n /**\n * When the collection is destroyed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onDestroy: (() => MaybePromise)[] = [];\n public destroyed = false;\n\n public async prepare(): Promise {\n this.storageInstance = getWrappedStorageInstance(\n this.database,\n this.internalStorageInstance,\n this.schema.jsonSchema\n );\n this.incrementalWriteQueue = new IncrementalWriteQueue(\n this.storageInstance,\n this.schema.primaryPath,\n (newData, oldData) => beforeDocumentUpdateWrite(this as any, newData, oldData),\n result => this._runHooks('post', 'save', result)\n );\n\n const collectionEventBulks$ = this.database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name),\n );\n this.$ = collectionEventBulks$.pipe(\n mergeMap(changeEventBulk => changeEventBulk.events),\n );\n this.checkpoint$ = collectionEventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.$.pipe(filter(cE => !cE.isLocal)),\n docData => createNewRxDocument(this.asRxCollection, docData)\n );\n\n /**\n * Instead of resolving the EventBulk array here and spit it into\n * single events, we should fully work with event bulks internally\n * to save performance.\n */\n const databaseStorageToken = await this.database.storageToken;\n const subDocs = this.storageInstance.changeStream().subscribe(eventBulk => {\n const changeEventBulk: RxChangeEventBulk = {\n id: eventBulk.id,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events.map(ev => storageChangeEventToRxChangeEvent(\n false,\n ev,\n this as any\n )),\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context,\n endTime: eventBulk.endTime,\n startTime: eventBulk.startTime\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n /**\n * Resolve the conflict tasks\n * of the RxStorageInstance\n */\n this._subs.push(\n this.storageInstance\n .conflictResultionTasks()\n .subscribe(task => {\n this\n .conflictHandler(task.input, task.context)\n .then(output => {\n this.storageInstance.resolveConflictResultionTask({\n id: task.id,\n output\n });\n });\n })\n );\n\n return PROMISE_RESOLVE_VOID;\n }\n\n\n /**\n * Manually call the cleanup function of the storage.\n * @link https://rxdb.info/cleanup.html\n */\n cleanup(_minimumDeletedTime?: number): Promise {\n throw pluginMissing('cleanup');\n }\n\n // overwritten by migration-plugin\n migrationNeeded(): Promise {\n throw pluginMissing('migration-schema');\n }\n getMigrationState(): RxMigrationState {\n throw pluginMissing('migration-schema');\n }\n startMigration(batchSize: number = 10): Promise {\n return this.getMigrationState().startMigration(batchSize);\n }\n migratePromise(batchSize: number = 10): Promise {\n return this.getMigrationState().migratePromise(batchSize);\n }\n\n async insert(\n json: RxDocumentType | RxDocument\n ): Promise> {\n const writeResult = await this.bulkInsert([json as any]);\n\n const isError = writeResult.error[0];\n throwIfIsStorageWriteError(this as any, (json as any)[this.schema.primaryPath] as any, json, isError);\n const insertResult = ensureNotFalsy(writeResult.success[0]);\n return insertResult;\n }\n\n async bulkInsert(\n docsData: RxDocumentType[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (docsData.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const primaryPath = this.schema.primaryPath;\n const useDocs = docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return useDocData;\n });\n const docs = this.hasHooks('pre', 'insert') ?\n await Promise.all(\n useDocs.map(doc => {\n return this._runHooks('pre', 'insert', doc)\n .then(() => {\n return doc;\n });\n })\n ) : useDocs;\n const insertRows: BulkWriteRow[] = docs.map(doc => {\n const row: BulkWriteRow = { document: doc };\n return row;\n });\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n // create documents\n const rxDocuments = mapDocumentsDataToCacheDocs(this._docCache, results.success);\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n docs.forEach(doc => {\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n rxDocuments.map(doc => {\n return this._runHooks(\n 'post', 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n async bulkRemove(\n ids: string[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (ids.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n const rxDocumentMap = await this.findByIds(ids).exec();\n const docsData: RxDocumentData[] = [];\n const docsMap: Map> = new Map();\n Array.from(rxDocumentMap.values()).forEach(rxDocument => {\n const data: RxDocumentData = rxDocument.toMutableJSON(true) as any;\n docsData.push(data);\n docsMap.set(rxDocument.primary, data);\n });\n\n await Promise.all(\n docsData.map(doc => {\n const primary = (doc as any)[this.schema.primaryPath];\n return this._runHooks('pre', 'remove', doc, rxDocumentMap.get(primary));\n })\n );\n const removeDocs: BulkWriteRow[] = docsData.map(doc => {\n const writeDoc = flatClone(doc);\n writeDoc._deleted = true;\n return {\n previous: doc,\n document: writeDoc\n };\n });\n const results = await this.storageInstance.bulkWrite(\n removeDocs,\n 'rx-collection-bulk-remove'\n );\n\n const successIds: string[] = results.success.map(d => d[primaryPath] as string);\n\n // run hooks\n await Promise.all(\n successIds.map(id => {\n return this._runHooks(\n 'post',\n 'remove',\n docsMap.get(id),\n rxDocumentMap.get(id)\n );\n })\n );\n\n const rxDocuments = successIds.map(id => getFromMapOrThrow(rxDocumentMap, id));\n\n return {\n success: rxDocuments,\n error: results.error\n };\n }\n\n /**\n * same as bulkInsert but overwrites existing document with same primary\n */\n async bulkUpsert(docsData: Partial[]): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n const insertData: RxDocumentType[] = [];\n const useJsonByDocId: Map = new Map();\n docsData.forEach(docData => {\n const useJson = fillObjectDataBeforeInsert(this.schema, docData);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL3', {\n primaryPath: this.schema.primaryPath as string,\n data: useJson,\n schema: this.schema.jsonSchema\n });\n }\n useJsonByDocId.set(primary, useJson);\n insertData.push(useJson);\n });\n\n const insertResult = await this.bulkInsert(insertData);\n const success = insertResult.success.slice(0);\n const error: RxStorageWriteError[] = [];\n\n // update the ones that existed already\n await Promise.all(\n insertResult.error.map(async (err) => {\n if (err.status !== 409) {\n error.push(err);\n } else {\n const id = err.documentId;\n const writeData = getFromMapOrThrow(useJsonByDocId, id);\n const docDataInDb = ensureNotFalsy(err.documentInDb);\n const doc = this._docCache.getCachedRxDocument(docDataInDb);\n const newDoc = await doc.incrementalModify(() => writeData);\n success.push(newDoc);\n }\n })\n );\n return {\n error,\n success\n };\n }\n\n /**\n * same as insert but overwrites existing document with same primary\n */\n async upsert(json: Partial): Promise> {\n const bulkResult = await this.bulkUpsert([json]);\n throwIfIsStorageWriteError(\n this.asRxCollection,\n (json as any)[this.schema.primaryPath],\n json as any,\n bulkResult.error[0]\n );\n return bulkResult.success[0];\n }\n\n /**\n * upserts to a RxDocument, uses incrementalModify if document already exists\n */\n incrementalUpsert(json: Partial): Promise> {\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[]\n > {\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\n // TODO move this check to dev-mode plugin\n if (\n typeof queryObj === 'number' ||\n Array.isArray(queryObj)\n ) {\n throw newRxTypeError('COL6', {\n queryObj\n });\n }\n\n let query;\n\n if (typeof queryObj === 'string') {\n query = createRxQuery('findOne', {\n selector: {\n [this.schema.primaryPath]: queryObj\n },\n limit: 1\n }, this as any);\n } else {\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n\n // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number\n > {\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.password,\n this.database.hashFunction\n );\n }\n\n get asRxCollection(): RxCollection {\n return this as any;\n }\n}\n\n/**\n * adds the hook-functions to the collections prototype\n * this runs only once\n */\nfunction _applyHookFunctions(\n collection: RxCollection\n) {\n if (hooksApplied) return; // already run\n hooksApplied = true;\n const colProto = Object.getPrototypeOf(collection);\n HOOKS_KEYS.forEach(key => {\n HOOKS_WHEN.map(when => {\n const fnName = when + ucfirst(key);\n colProto[fnName] = function (fun: string, parallel: boolean) {\n return this.addHook(when, key, fun, parallel);\n };\n });\n });\n}\n\nfunction _incrementalUpsertUpdate(\n doc: RxDocumentBase,\n json: RxDocumentData\n): Promise> {\n return doc.incrementalModify((_innerDoc) => {\n return json;\n });\n}\n\n/**\n * ensures that the given document exists\n * @return promise that resolves with new doc and flag if inserted\n */\nfunction _incrementalUpsertEnsureRxDocumentExists(\n rxCollection: RxCollection,\n primary: string,\n json: any\n): Promise<\n {\n doc: RxDocument;\n inserted: boolean;\n }\n> {\n /**\n * Optimisation shortcut,\n * first try to find the document in the doc-cache\n */\n const docDataFromCache = rxCollection._docCache.getLatestDocumentDataIfExists(primary);\n if (docDataFromCache) {\n return Promise.resolve({\n doc: rxCollection._docCache.getCachedRxDocument(docDataFromCache),\n inserted: false\n });\n }\n return rxCollection.findOne(primary).exec()\n .then(doc => {\n if (!doc) {\n return rxCollection.insert(json).then(newDoc => ({\n doc: newDoc,\n inserted: true\n }));\n } else {\n return {\n doc,\n inserted: false\n };\n }\n });\n}\n\n/**\n * creates and prepares a new collection\n */\nexport function createRxCollection(\n {\n database,\n name,\n schema,\n instanceCreationOptions = {},\n migrationStrategies = {},\n autoMigrate = true,\n statics = {},\n methods = {},\n attachments = {},\n options = {},\n localDocuments = false,\n cacheReplacementPolicy = defaultCacheReplacementPolicy,\n conflictHandler = defaultConflictHandler\n }: any\n): Promise {\n const storageInstanceCreationParams: RxStorageInstanceCreationParams = {\n databaseInstanceToken: database.token,\n databaseName: database.name,\n collectionName: name,\n schema: schema.jsonSchema,\n options: instanceCreationOptions,\n multiInstance: database.multiInstance,\n password: database.password,\n devMode: overwritable.isDevMode()\n };\n\n runPluginHooks(\n 'preCreateRxStorageInstance',\n storageInstanceCreationParams\n );\n\n return createRxCollectionStorageInstance(\n database,\n storageInstanceCreationParams\n ).then(storageInstance => {\n const collection = new RxCollectionBase(\n database,\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n statics,\n conflictHandler\n );\n\n return collection\n .prepare()\n .then(() => {\n // ORM add statics\n Object\n .entries(statics)\n .forEach(([funName, fun]) => {\n Object.defineProperty(collection, funName, {\n get: () => (fun as any).bind(collection)\n });\n });\n\n let ret = PROMISE_RESOLVE_VOID;\n if (autoMigrate && collection.schema.version !== 0) {\n ret = collection.migratePromise();\n }\n return ret;\n })\n .then(() => {\n runPluginHooks('createRxCollection', {\n collection,\n creator: {\n name,\n schema,\n storageInstance,\n instanceCreationOptions,\n migrationStrategies,\n methods,\n attachments,\n options,\n cacheReplacementPolicy,\n localDocuments,\n statics\n }\n });\n return collection as any;\n })\n /**\n * If the collection creation fails,\n * we yet have to close the storage instances.\n */\n .catch(err => {\n return storageInstance.close()\n .then(() => Promise.reject(err));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";AAAA,SACIA,MAAM,EACNC,GAAG,EACHC,QAAQ,QACL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AC,CAChB4F,OAAO,CAAC,CAAC,CAACoH,OAAO,EAAEvD,GAAG,CAAC,KAAK;QACzBqC,MAAM,CAACmB,cAAc,CAACrB,UAAU,EAAEoB,OAAO,EAAE;UACvClH,GAAG,EAAEA,CAAA,KAAO2D,GAAG,CAASI,IAAI,CAAC+B,UAAU;QAC3C,CAAC,CAAC;MACN,CAAC,CAAC;MAEN,IAAIrB,GAAG,GAAG5M,oBAAoB;MAC9B,IAAI4O,WAAW,IAAIX,UAAU,CAACpM,MAAM,CAAC0N,OAAO,KAAK,CAAC,EAAE;QAChD3C,GAAG,GAAGqB,UAAU,CAACzH,cAAc,CAAC,CAAC;MACrC;MACA,OAAOoG,GAAG;IACd,CAAC,CAAC,CACD7G,IAAI,CAAC,MAAM;MACRjF,cAAc,CAAC,oBAAoB,EAAE;QACjCmN,UAAU;QACVuB,OAAO,EAAE;UACL5N,IAAI;UACJC,MAAM;UACNU,eAAe;UACfR,uBAAuB;UACvBC,mBAAmB;UACnBC,OAAO;UACPC,WAAW;UACXC,OAAO;UACPC,sBAAsB;UACtByM,cAAc;UACdxM;QACJ;MACJ,CAAC,CAAC;MACF,OAAO4L,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAICwB,KAAK,CAAC9F,GAAG,IAAI;MACV,OAAOpH,eAAe,CAAC+K,KAAK,CAAC,CAAC,CACzBvH,IAAI,CAAC,MAAMwB,OAAO,CAACmI,MAAM,CAAC/F,GAAG,CAAC,CAAC;IACxC,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEA,OAAO,SAASgG,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYlO,gBAAgB;AAC1C"} \ No newline at end of file diff --git a/dist/esm/rx-database.js b/dist/esm/rx-database.js index 3c9bcb79e3c..88215ca50ba 100644 --- a/dist/esm/rx-database.js +++ b/dist/esm/rx-database.js @@ -270,7 +270,7 @@ export var RxDatabaseBase = /*#__PURE__*/function () { throw pluginMissing('leader-election'); }; _proto.migrationStates = function migrationStates() { - throw pluginMissing('migration'); + throw pluginMissing('migration-schema'); } /** diff --git a/dist/esm/rx-database.js.map b/dist/esm/rx-database.js.map index f68127d1e65..aed210bb4f8 100644 --- a/dist/esm/rx-database.js.map +++ b/dist/esm/rx-database.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-database.js","names":["IdleQueue","pluginMissing","flatClone","PROMISE_RESOLVE_FALSE","randomCouchString","ensureNotFalsy","getDefaultRevision","getDefaultRxDocumentMeta","defaultHashSha256","RXDB_VERSION","newRxError","createRxSchema","runPluginHooks","runAsyncPluginHooks","Subject","mergeMap","createRxCollection","flatCloneDocWithMeta","getSingleDocument","getWrappedStorageInstance","INTERNAL_STORAGE_NAME","ObliviousSet","ensureStorageTokenDocumentExists","getAllCollectionDocuments","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","INTERNAL_STORE_SCHEMA","_collectionNamePrimary","removeCollectionStorages","overwritable","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","idleQueue","rxdbVersion","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","Promise","all","Object","entries","map","args","collectionName","rxJsonSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","_rev","_attachments","useArgs","assign","database","hookData","conflictHandler","putDocsResult","ensureNoStartupErrors","error","status","writeError","docInDb","documentInDb","collection","previousSchemaHash","previousSchema","ret","keys","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","collectionNames","forEach","removedCollectionNames","Array","from","isRxDatabase","obj","dbCount","isRxDatabaseFirstTimeInstantiated","tokenDoc","instanceToken"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise\n} from './types/index.d.ts';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256,\n RXDB_VERSION\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema.ts';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks.ts';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection.ts';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport type { RxBackupState } from './plugins/backup/index.ts';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store.ts';\nimport { removeCollectionStorages } from './rx-collection-helper.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxMigrationState } from './plugins/migration-schema/index.ts';\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 public readonly rxdbVersion = RXDB_VERSION;\n\n /**\n * Contains all known non-closed storage instances\n * that belong to this database.\n * Used in plugins and unit tests.\n */\n public readonly storageInstances = new Set>();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean\n ) {\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 await Promise.all(\n Object.entries(collectionCreators).map(async ([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema, this.hashFunction);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: await schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n })\n );\n\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n await Promise.all(\n putDocsResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('DB12', {\n database: this.name,\n writeError: error\n });\n }\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== await schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: await schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n })\n );\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\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, this.password));\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 = true,\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 password?: string\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false,\n password\n );\n\n const collectionDocs = await getAllCollectionDocuments(dbInternalsStorageInstance);\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 password\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";AAAA,SAASA,SAAS,QAAQ,mBAAmB;AA8B7C,SACIC,aAAa,EACbC,SAAS,EACTC,qBAAqB,EACrBC,iBAAiB,EACjBC,cAAc,EACdC,kBAAkB,EAClBC,wBAAwB,EACxBC,iBAAiB,EACjBC,YAAY,QACT,0BAA0B;AACjC,SACIC,UAAU,QACP,eAAe;AACtB,SACIC,cAAc,QAEX,gBAAgB;AACvB,SACIC,cAAc,EACdC,mBAAmB,QAChB,YAAY;AACnB,SACIC,OAAO,QAGJ,MAAM;AACb,SACIC,QAAQ,QACL,gBAAgB;AACvB,SACIC,kBAAkB,QACf,oBAAoB;AAC3B,SACIC,oBAAoB,EACpBC,iBAAiB,EACjBC,yBAAyB,EACzBC,qBAAqB,QAElB,wBAAwB;AAE/B,SAASC,YAAY,QAAQ,eAAe;AAC5C,SACIC,gCAAgC,EAChCC,yBAAyB,EACzBC,+BAA+B,EAC/BC,2BAA2B,EAC3BC,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MAAMA,UAAU,CAACzG,YAAY;EAC7B,IAAIyG,UAAU,CAAClH,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAMkH,UAAU,CAAClH,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","RXDB_VERSION","newRxError","createRxSchema","runPluginHooks","runAsyncPluginHooks","Subject","mergeMap","createRxCollection","flatCloneDocWithMeta","getSingleDocument","getWrappedStorageInstance","INTERNAL_STORAGE_NAME","ObliviousSet","ensureStorageTokenDocumentExists","getAllCollectionDocuments","getPrimaryKeyOfInternalDocument","INTERNAL_CONTEXT_COLLECTION","INTERNAL_STORE_SCHEMA","_collectionNamePrimary","removeCollectionStorages","overwritable","USED_DATABASE_NAMES","Set","DB_COUNT","RxDatabaseBase","name","token","storage","instanceCreationOptions","password","multiInstance","eventReduce","options","internalStore","hashFunction","cleanupPolicy","allowSlowCount","idleQueue","rxdbVersion","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","Promise","all","Object","entries","map","args","collectionName","rxJsonSchema","collectionNameWithVersion","collectionDocData","key","context","schemaHash","hash","jsonSchema","version","connectedStorages","_meta","_rev","_attachments","useArgs","assign","database","hookData","conflictHandler","putDocsResult","ensureNoStartupErrors","error","status","writeError","docInDb","documentInDb","collection","previousSchemaHash","previousSchema","ret","keys","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","collectionNames","forEach","removedCollectionNames","Array","from","isRxDatabase","obj","dbCount","isRxDatabaseFirstTimeInstantiated","tokenDoc","instanceToken"],"sources":["../../src/rx-database.ts"],"sourcesContent":["import { IdleQueue } from 'custom-idle-queue';\nimport type {\n LeaderElector\n} from 'broadcast-channel';\nimport type {\n CollectionsOfDatabase,\n RxDatabase,\n RxCollectionCreator,\n RxJsonSchema,\n RxCollection,\n RxDumpDatabase,\n RxDumpDatabaseAny,\n BackupOptions,\n RxStorage,\n RxStorageInstance,\n BulkWriteRow,\n RxChangeEvent,\n RxDatabaseCreator,\n RxChangeEventBulk,\n RxDocumentData,\n RxCleanupPolicy,\n InternalStoreDocType,\n InternalStoreStorageTokenDocType,\n InternalStoreCollectionDocType,\n RxTypeError,\n RxError,\n HashFunction,\n MaybePromise\n} from './types/index.d.ts';\n\nimport {\n pluginMissing,\n flatClone,\n PROMISE_RESOLVE_FALSE,\n randomCouchString,\n ensureNotFalsy,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n defaultHashSha256,\n RXDB_VERSION\n} from './plugins/utils/index.ts';\nimport {\n newRxError\n} from './rx-error.ts';\nimport {\n createRxSchema,\n RxSchema\n} from './rx-schema.ts';\nimport {\n runPluginHooks,\n runAsyncPluginHooks\n} from './hooks.ts';\nimport {\n Subject,\n Subscription,\n Observable\n} from 'rxjs';\nimport {\n mergeMap\n} from 'rxjs/operators';\nimport {\n createRxCollection\n} from './rx-collection.ts';\nimport {\n flatCloneDocWithMeta,\n getSingleDocument,\n getWrappedStorageInstance,\n INTERNAL_STORAGE_NAME,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport type { RxBackupState } from './plugins/backup/index.ts';\nimport { ObliviousSet } from 'oblivious-set';\nimport {\n ensureStorageTokenDocumentExists,\n getAllCollectionDocuments,\n getPrimaryKeyOfInternalDocument,\n INTERNAL_CONTEXT_COLLECTION,\n INTERNAL_STORE_SCHEMA,\n _collectionNamePrimary\n} from './rx-database-internal-store.ts';\nimport { removeCollectionStorages } from './rx-collection-helper.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxMigrationState } from './plugins/migration-schema/index.ts';\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 public readonly rxdbVersion = RXDB_VERSION;\n\n /**\n * Contains all known non-closed storage instances\n * that belong to this database.\n * Used in plugins and unit tests.\n */\n public readonly storageInstances = new Set>();\n\n constructor(\n public readonly name: string,\n /**\n * Uniquely identifies the instance\n * of this RxDatabase.\n */\n public readonly token: string,\n public readonly storage: RxStorage,\n public readonly instanceCreationOptions: InstanceCreationOptions,\n public readonly password: any,\n public readonly multiInstance: boolean,\n public readonly eventReduce: boolean = false,\n public options: any = {},\n /**\n * Stores information documents about the collections of the database\n */\n public readonly internalStore: RxStorageInstance,\n public readonly hashFunction: HashFunction,\n public readonly cleanupPolicy?: Partial,\n public readonly allowSlowCount?: boolean\n ) {\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 await Promise.all(\n Object.entries(collectionCreators).map(async ([name, args]) => {\n const collectionName: keyof CreatedCollections = name as any;\n const rxJsonSchema = (args as RxCollectionCreator).schema;\n jsonSchemas[collectionName] = rxJsonSchema;\n const schema = createRxSchema(rxJsonSchema, this.hashFunction);\n schemas[collectionName] = schema;\n\n // collection already exists\n if ((this.collections as any)[name]) {\n throw newRxError('DB3', {\n name\n });\n }\n\n const collectionNameWithVersion = _collectionNamePrimary(name, rxJsonSchema);\n const collectionDocData: RxDocumentData = {\n id: getPrimaryKeyOfInternalDocument(\n collectionNameWithVersion,\n INTERNAL_CONTEXT_COLLECTION\n ),\n key: collectionNameWithVersion,\n context: INTERNAL_CONTEXT_COLLECTION,\n data: {\n name: collectionName as any,\n schemaHash: await schema.hash,\n schema: schema.jsonSchema,\n version: schema.version,\n connectedStorages: []\n },\n _deleted: false,\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n };\n bulkPutDocs.push({\n document: collectionDocData\n });\n\n const useArgs: any = Object.assign(\n {},\n args,\n {\n name: collectionName,\n schema,\n database: this\n }\n );\n\n // run hooks\n const hookData: RxCollectionCreator & { name: string; } = flatClone(args) as any;\n (hookData as any).database = this;\n hookData.name = name;\n runPluginHooks('preCreateRxCollection', hookData);\n useArgs.conflictHandler = hookData.conflictHandler;\n\n useArgsByCollectionName[collectionName] = useArgs;\n })\n );\n\n\n const putDocsResult = await this.internalStore.bulkWrite(\n bulkPutDocs,\n 'rx-database-add-collection'\n );\n\n await ensureNoStartupErrors(this);\n\n await Promise.all(\n putDocsResult.error.map(async (error) => {\n if (error.status !== 409) {\n throw newRxError('DB12', {\n database: this.name,\n writeError: error\n });\n }\n const docInDb: RxDocumentData = ensureNotFalsy(error.documentInDb);\n const collectionName = docInDb.data.name;\n const schema = (schemas as any)[collectionName];\n // collection already exists but has different schema\n if (docInDb.data.schemaHash !== await schema.hash) {\n throw newRxError('DB6', {\n database: this.name,\n collection: collectionName,\n previousSchemaHash: docInDb.data.schemaHash,\n schemaHash: await schema.hash,\n previousSchema: docInDb.data.schema,\n schema: ensureNotFalsy((jsonSchemas as any)[collectionName])\n });\n }\n })\n );\n\n const ret: { [key in keyof CreatedCollections]: RxCollection } = {} as any;\n await Promise.all(\n Object.keys(collectionCreators).map(async (collectionName) => {\n const useArgs = useArgsByCollectionName[collectionName];\n const collection = await createRxCollection(useArgs);\n (ret as any)[collectionName] = collection;\n\n // set as getter to the database\n (this.collections as any)[collectionName] = collection;\n if (!(this as any)[collectionName]) {\n Object.defineProperty(this, collectionName, {\n get: () => (this.collections as any)[collectionName]\n });\n }\n })\n );\n\n return ret;\n }\n\n /**\n * runs the given function between idleQueue-locking\n */\n lockedRun(fn: (...args: any[]) => T): T extends Promise ? T : Promise {\n return this.idleQueue.wrapCall(fn) as any;\n }\n\n requestIdlePromise() {\n return this.idleQueue.requestIdlePromise();\n }\n\n /**\n * Export database to a JSON friendly format.\n */\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise>;\n exportJSON(_collections?: string[]): Promise {\n throw pluginMissing('json-dump');\n }\n\n /**\n * Import the parsed JSON export into the collection.\n * @param _exportedJSON The previously exported data from the `.exportJSON()` method.\n * @note When an interface is loaded in this collection all base properties of the type are typed as `any`\n * since data could be encrypted.\n */\n importJSON(_exportedJSON: RxDumpDatabaseAny): Promise {\n throw pluginMissing('json-dump');\n }\n\n backup(_options: BackupOptions): RxBackupState {\n throw pluginMissing('backup');\n }\n\n public leaderElector(): LeaderElector {\n throw pluginMissing('leader-election');\n }\n\n public isLeader(): boolean {\n throw pluginMissing('leader-election');\n }\n /**\n * returns a promise which resolves when the instance becomes leader\n */\n public waitForLeadership(): Promise {\n throw pluginMissing('leader-election');\n }\n\n public migrationStates(): Observable {\n throw pluginMissing('migration-schema');\n }\n\n /**\n * destroys the database-instance and all collections\n */\n public async destroy(): Promise {\n if (this.destroyed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n // settings destroyed = true must be the first thing to do.\n this.destroyed = true;\n\n await runAsyncPluginHooks('preDestroyRxDatabase', this);\n /**\n * Complete the event stream\n * to stop all subscribers who forgot to unsubscribe.\n */\n this.eventBulks$.complete();\n\n DB_COUNT--;\n this._subs.map(sub => sub.unsubscribe());\n\n /**\n * Destroying the pseudo instance will throw\n * because stuff is missing\n * TODO we should not need the pseudo instance on runtime.\n * we should generate the property list on build time.\n */\n if (this.name === 'pseudoInstance') {\n return PROMISE_RESOLVE_FALSE;\n }\n\n /**\n * First wait until the database is idle\n */\n return this.requestIdlePromise()\n .then(() => Promise.all(this.onDestroy.map(fn => fn())))\n // destroy all collections\n .then(() => Promise.all(\n Object.keys(this.collections as any)\n .map(key => (this.collections as any)[key])\n .map(col => col.destroy())\n ))\n // destroy internal storage instances\n .then(() => this.internalStore.close())\n // remove combination from USED_COMBINATIONS-map\n .then(() => USED_DATABASE_NAMES.delete(this.name))\n .then(() => true);\n }\n\n /**\n * deletes the database and its stored data.\n * Returns the names of all removed collections.\n */\n remove(): Promise {\n return this\n .destroy()\n .then(() => removeRxDatabase(this.name, this.storage, this.password));\n }\n\n get asRxDatabase(): RxDatabase<\n {},\n Internals,\n InstanceCreationOptions\n > {\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 = true,\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 password?: string\n): Promise {\n const databaseInstanceToken = randomCouchString(10);\n const dbInternalsStorageInstance = await createRxDatabaseStorageInstance(\n databaseInstanceToken,\n storage,\n databaseName,\n {},\n false,\n password\n );\n\n const collectionDocs = await getAllCollectionDocuments(dbInternalsStorageInstance);\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 password\n ))\n );\n\n await runAsyncPluginHooks('postRemoveRxDatabase', {\n databaseName,\n storage\n });\n\n await dbInternalsStorageInstance.remove();\n return removedCollectionNames;\n}\n\nexport function isRxDatabase(obj: any) {\n return obj instanceof RxDatabaseBase;\n}\n\nexport function dbCount(): number {\n return DB_COUNT;\n}\n\n\n/**\n * Returns true if the given RxDatabase was the first\n * instance that was created on the storage with this name.\n *\n * Can be used for some optimizations because on the first instantiation,\n * we can assume that no data was written before.\n */\nexport async function isRxDatabaseFirstTimeInstantiated(\n database: RxDatabase\n): Promise {\n const tokenDoc = await database.storageTokenDocument;\n return tokenDoc.data.instanceToken === database.token;\n}\n\n\n/**\n * For better performance some tasks run async\n * and are awaited later.\n * But we still have to ensure that there have been no errors\n * on database creation.\n */\nexport async function ensureNoStartupErrors(\n rxDatabase: RxDatabaseBase\n) {\n await rxDatabase.storageToken;\n if (rxDatabase.startupErrors[0]) {\n throw rxDatabase.startupErrors[0];\n }\n}\n"],"mappings":";AAAA,SAASA,SAAS,QAAQ,mBAAmB;AA8B7C,SACIC,aAAa,EACbC,SAAS,EACTC,qBAAqB,EACrBC,iBAAiB,EACjBC,cAAc,EACdC,kBAAkB,EAClBC,wBAAwB,EACxBC,iBAAiB,EACjBC,YAAY,QACT,0BAA0B;AACjC,SACIC,UAAU,QACP,eAAe;AACtB,SACIC,cAAc,QAEX,gBAAgB;AACvB,SACIC,cAAc,EACdC,mBAAmB,QAChB,YAAY;AACnB,SACIC,OAAO,QAGJ,MAAM;AACb,SACIC,QAAQ,QACL,gBAAgB;AACvB,SACIC,kBAAkB,QACf,oBAAoB;AAC3B,SACIC,oBAAoB,EACpBC,iBAAiB,EACjBC,yBAAyB,EACzBC,qBAAqB,QAElB,wBAAwB;AAE/B,SAASC,YAAY,QAAQ,eAAe;AAC5C,SACIC,gCAAgC,EAChCC,yBAAyB,EACzBC,+BAA+B,EAC/BC,2BAA2B,EAC3BC,qBAAqB,EACrBC,sBAAsB,QACn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Y;EAC7B,IAAIyG,UAAU,CAAClH,aAAa,CAAC,CAAC,CAAC,EAAE;IAC7B,MAAMkH,UAAU,CAAClH,aAAa,CAAC,CAAC,CAAC;EACrC;AACJ"} \ No newline at end of file diff --git a/dist/esm/rx-schema-helper.js b/dist/esm/rx-schema-helper.js index 67ff570f782..1d4b5dbbb72 100644 --- a/dist/esm/rx-schema-helper.js +++ b/dist/esm/rx-schema-helper.js @@ -198,6 +198,13 @@ export function fillWithDefaultSettings(schemaObj) { // we need this index for the getChangedDocumentsSince() method useIndexes.push(['_meta.lwt', primaryPath]); + // also add the internalIndexes + if (schemaObj.internalIndexes) { + schemaObj.internalIndexes.map(idx => { + useIndexes.push(idx); + }); + } + // make indexes unique var hasIndex = new Set(); useIndexes.filter(index => { diff --git a/dist/esm/rx-schema-helper.js.map b/dist/esm/rx-schema-helper.js.map index ef69e054a25..4345b152304 100644 --- a/dist/esm/rx-schema-helper.js.map +++ b/dist/esm/rx-schema-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-schema-helper.js","names":["newRxError","appendToArray","ensureNotFalsy","flatClone","getProperty","isMaybeReadonlyArray","REGEX_ALL_DOTS","RX_META_LWT_MINIMUM","sortObject","trimDots","getPseudoSchemaForVersion","version","primaryKey","pseudoSchema","fillWithDefaultSettings","type","properties","maxLength","indexes","required","getSchemaByObjectPath","rxJsonSchema","path","usePath","replace","ret","fillPrimaryKey","primaryPath","jsonSchema","documentData","newPrimary","getComposedPrimaryKeyOfDocumentData","existingPrimary","args","schema","getPrimaryFieldOfPrimaryKey","key","getLengthOfPrimaryKey","schemaPart","compositePrimary","fields","map","field","value","join","separator","normalizeRxJsonSchema","normalizedSchema","getDefaultIndex","schemaObj","additionalProperties","Object","prototype","hasOwnProperty","call","keyCompression","slice","encrypted","_rev","minLength","_attachments","_deleted","_meta","RX_META_SCHEMA","push","finalFields","getFinalFields","filter","includes","elem","pos","arr","indexOf","useIndexes","index","arIndex","unshift","length","hasIndex","Set","indexStr","has","add","lwt","minimum","maximum","multipleOf","keys","final","forEach","fillObjectWithDefaults","rxSchema","obj","defaultKeys","defaultValues","i","DEFAULT_CHECKPOINT_SCHEMA","id"],"sources":["../../src/rx-schema-helper.ts"],"sourcesContent":["import { newRxError } from './rx-error.ts';\nimport type {\n CompositePrimaryKey,\n DeepReadonly,\n JsonSchema,\n PrimaryKey,\n RxDocumentData,\n RxJsonSchema,\n RxStorageDefaultCheckpoint,\n StringKeys\n} from './types/index.d.ts';\nimport {\n appendToArray,\n ensureNotFalsy,\n flatClone,\n getProperty,\n isMaybeReadonlyArray,\n REGEX_ALL_DOTS,\n RX_META_LWT_MINIMUM,\n sortObject,\n trimDots\n} from './plugins/utils/index.ts';\nimport type { RxSchema } from './rx-schema.ts';\n\n/**\n * Helper function to create a valid RxJsonSchema\n * with a given version.\n */\nexport function getPseudoSchemaForVersion(\n version: number,\n primaryKey: StringKeys\n): RxJsonSchema> {\n const pseudoSchema: RxJsonSchema> = fillWithDefaultSettings({\n version,\n type: 'object',\n primaryKey: primaryKey as any,\n properties: {\n [primaryKey]: {\n type: 'string',\n maxLength: 100\n }\n } as any,\n indexes: [\n [primaryKey]\n ],\n required: [primaryKey]\n });\n return pseudoSchema;\n}\n\n/**\n * Returns the sub-schema for a given path\n */\nexport function getSchemaByObjectPath(\n rxJsonSchema: RxJsonSchema,\n path: keyof T | string\n): JsonSchema {\n let usePath: string = path as string;\n usePath = usePath.replace(REGEX_ALL_DOTS, '.properties.');\n usePath = 'properties.' + usePath;\n usePath = trimDots(usePath);\n\n const ret = getProperty(rxJsonSchema, usePath);\n return ret;\n}\n\nexport function fillPrimaryKey(\n primaryPath: keyof T,\n jsonSchema: RxJsonSchema,\n documentData: RxDocumentData\n): RxDocumentData {\n // optimization shortcut.\n if (typeof jsonSchema.primaryKey === 'string') {\n return documentData;\n }\n\n const newPrimary = getComposedPrimaryKeyOfDocumentData(\n jsonSchema,\n documentData\n );\n const existingPrimary: string | undefined = documentData[primaryPath] as any;\n if (\n existingPrimary &&\n existingPrimary !== newPrimary\n ) {\n throw newRxError(\n 'DOC19',\n {\n args: {\n documentData,\n existingPrimary,\n newPrimary,\n },\n schema: jsonSchema\n });\n }\n\n (documentData as any)[primaryPath] = newPrimary;\n return documentData;\n}\n\nexport function getPrimaryFieldOfPrimaryKey(\n primaryKey: PrimaryKey\n): StringKeys {\n if (typeof primaryKey === 'string') {\n return primaryKey as any;\n } else {\n return (primaryKey as CompositePrimaryKey).key;\n }\n}\n\nexport function getLengthOfPrimaryKey(\n schema: RxJsonSchema>\n): number {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const schemaPart = getSchemaByObjectPath(schema, primaryPath);\n return ensureNotFalsy(schemaPart.maxLength);\n}\n\n/**\n * Returns the composed primaryKey of a document by its data.\n */\nexport function getComposedPrimaryKeyOfDocumentData(\n jsonSchema: RxJsonSchema | RxJsonSchema>,\n documentData: Partial\n): string {\n if (typeof jsonSchema.primaryKey === 'string') {\n return (documentData as any)[jsonSchema.primaryKey];\n }\n\n const compositePrimary: CompositePrimaryKey = jsonSchema.primaryKey as any;\n return compositePrimary.fields.map(field => {\n const value = getProperty(documentData as any, field as string);\n if (typeof value === 'undefined') {\n throw newRxError('DOC18', { args: { field, documentData } });\n }\n return value;\n }).join(compositePrimary.separator);\n}\n\n\n/**\n * Normalize the RxJsonSchema.\n * We need this to ensure everything is set up properly\n * and we have the same hash on schemas that represent the same value but\n * have different json.\n *\n * - Orders the schemas attributes by alphabetical order\n * - Adds the primaryKey to all indexes that do not contain the primaryKey\n * - We need this for deterministic sort order on all queries, which is required for event-reduce to work.\n *\n * @return RxJsonSchema - ordered and filled\n */\nexport function normalizeRxJsonSchema(jsonSchema: RxJsonSchema): RxJsonSchema {\n const normalizedSchema: RxJsonSchema = sortObject(jsonSchema, true);\n return normalizedSchema;\n}\n\n/**\n * If the schema does not specify any index,\n * we add this index so we at least can run RxQuery()\n * and only select non-deleted fields.\n */\nexport function getDefaultIndex(primaryPath: string) {\n return ['_deleted', primaryPath];\n}\n\n/**\n * fills the schema-json with default-settings\n * @return cloned schemaObj\n */\nexport function fillWithDefaultSettings(\n schemaObj: RxJsonSchema\n): RxJsonSchema> {\n schemaObj = flatClone(schemaObj);\n const primaryPath: string = getPrimaryFieldOfPrimaryKey(schemaObj.primaryKey);\n schemaObj.properties = flatClone(schemaObj.properties);\n\n // additionalProperties is always false\n schemaObj.additionalProperties = false;\n\n // fill with key-compression-state ()\n if (!Object.prototype.hasOwnProperty.call(schemaObj, 'keyCompression')) {\n schemaObj.keyCompression = false;\n }\n\n // indexes must be array\n schemaObj.indexes = schemaObj.indexes ? schemaObj.indexes.slice(0) : [];\n\n // required must be array\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n\n // encrypted must be array\n schemaObj.encrypted = schemaObj.encrypted ? schemaObj.encrypted.slice(0) : [];\n\n // add _rev\n (schemaObj.properties as any)._rev = {\n type: 'string',\n minLength: 1\n };\n\n // add attachments\n (schemaObj.properties as any)._attachments = {\n type: 'object'\n };\n\n // add deleted flag\n (schemaObj.properties as any)._deleted = {\n type: 'boolean'\n };\n\n // add meta property\n (schemaObj.properties as any)._meta = RX_META_SCHEMA;\n\n /**\n * meta fields are all required\n */\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n (schemaObj.required as string[]).push('_deleted');\n (schemaObj.required as string[]).push('_rev');\n (schemaObj.required as string[]).push('_meta');\n (schemaObj.required as string[]).push('_attachments');\n\n // final fields are always required\n const finalFields = getFinalFields(schemaObj);\n appendToArray(schemaObj.required as any, finalFields);\n schemaObj.required = schemaObj.required\n .filter((field: string) => !field.includes('.'))\n .filter((elem: any, pos: any, arr: any) => arr.indexOf(elem) === pos); // unique;\n\n // version is 0 by default\n schemaObj.version = schemaObj.version || 0;\n\n const useIndexes: string[][] = schemaObj.indexes.map(index => {\n const arIndex = isMaybeReadonlyArray(index) ? index.slice(0) : [index];\n /**\n * Append primary key to indexes that do not contain the primaryKey.\n * All indexes must have the primaryKey to ensure a deterministic sort order.\n */\n if (!arIndex.includes(primaryPath)) {\n arIndex.push(primaryPath);\n }\n\n // add _deleted flag to all indexes so we can query only non-deleted fields\n // in RxDB itself\n if (arIndex[0] !== '_deleted') {\n arIndex.unshift('_deleted');\n }\n\n return arIndex;\n });\n\n if (useIndexes.length === 0) {\n useIndexes.push(getDefaultIndex(primaryPath));\n }\n\n // we need this index for the getChangedDocumentsSince() method\n useIndexes.push(['_meta.lwt', primaryPath]);\n\n // make indexes unique\n const hasIndex = new Set();\n useIndexes.filter(index => {\n const indexStr = index.join(',');\n if (hasIndex.has(indexStr)) {\n return false;\n } else {\n hasIndex.add(indexStr);\n return true;\n }\n });\n\n schemaObj.indexes = useIndexes;\n\n return schemaObj as any;\n}\n\n\nexport const RX_META_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n /**\n * The last-write time.\n * Unix time in milliseconds.\n */\n lwt: {\n type: 'number',\n /**\n * We use 1 as minimum so that the value is never falsy.\n */\n minimum: RX_META_LWT_MINIMUM,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n /**\n * Additional properties are allowed\n * and can be used by plugins to set various flags.\n */\n additionalProperties: true as any,\n required: [\n 'lwt'\n ]\n};\n\n\n/**\n * returns the final-fields of the schema\n * @return field-names of the final-fields\n */\nexport function getFinalFields(\n jsonSchema: RxJsonSchema\n): string[] {\n const ret = Object.keys(jsonSchema.properties)\n .filter(key => (jsonSchema as any).properties[key].final);\n\n // primary is also final\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n ret.push(primaryPath);\n\n // fields of composite primary are final\n if (typeof jsonSchema.primaryKey !== 'string') {\n (jsonSchema.primaryKey as CompositePrimaryKey).fields\n .forEach(field => ret.push(field as string));\n }\n\n return ret;\n}\n\n/**\n * fills all unset fields with default-values if set\n * @hotPath\n */\nexport function fillObjectWithDefaults(rxSchema: RxSchema, obj: any): any {\n const defaultKeys = Object.keys(rxSchema.defaultValues);\n for (let i = 0; i < defaultKeys.length; ++i) {\n const key = defaultKeys[i];\n if (!Object.prototype.hasOwnProperty.call(obj, key) || typeof obj[key] === 'undefined') {\n obj[key] = rxSchema.defaultValues[key];\n }\n }\n return obj;\n}\n\nexport const DEFAULT_CHECKPOINT_SCHEMA: DeepReadonly> = {\n type: 'object',\n properties: {\n id: {\n type: 'string'\n },\n lwt: {\n type: 'number'\n }\n },\n required: [\n 'id',\n 'lwt'\n ],\n additionalProperties: false\n} as const;\n"],"mappings":"AAAA,SAASA,UAAU,QAAQ,eAAe;AAW1C,SACIC,aAAa,EACbC,cAAc,EACdC,SAAS,EACTC,WAAW,EACXC,oBAAoB,EACpBC,cAAc,EACdC,mBAAmB,EACnBC,UAAU,EACVC,QAAQ,QACL,0BAA0B;AAGjC;AACA;AACA;AACA;AACA,OAAO,SAASC,yBAAyBA,CACrCC,OAAe,EACfC,UAAyB,EACM;EAC/B,IAAMC,YAA6C,GAAGC,uBAAuB,CAAC;IAC1EH,OAAO;IACPI,IAAI,EAAE,QAAQ;IACdH,UAAU,EAAEA,UAAiB;IAC7BI,UAAU,EAAE;MACR,CAACJ,UAAU,GAAG;QACVG,IAAI,EAAE,QAAQ;QACdE,SAAS,EAAE;MACf;IACJ,CAAQ;IACRC,OAAO,EAAE,CACL,CAACN,UAAU,CAAC,CACf;IACDO,QAAQ,EAAE,CAACP,UAAU;EACzB,CAAC,CAAC;EACF,OAAOC,YAAY;AACvB;;AAEA;AACA;AACA;AACA,OAAO,SAASO,qBAAqBA,CACjCC,YAA6B,EAC7BC,IAAsB,EACZ;EACV,IAAIC,OAAe,GAAGD,IAAc;EACpCC,OAAO,GAAGA,OAAO,CAACC,OAAO,CAAClB,cAAc,EAAE,cAAc,CAAC;EACzDiB,OAAO,GAAG,aAAa,GAAGA,OAAO;EACjCA,OAAO,GAAGd,QAAQ,CAACc,OAAO,CAAC;EAE3B,IAAME,GAAG,GAAGrB,WAAW,CAACiB,YAAY,EAAEE,OAAO,CAAC;EAC9C,OAAOE,GA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AW,GAAG1C,MAAM,CAACoC,IAAI,CAACI,QAAQ,CAACG,aAAa,CAAC;EACvD,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGF,WAAW,CAAChB,MAAM,EAAE,EAAEkB,CAAC,EAAE;IACzC,IAAM3D,GAAG,GAAGyD,WAAW,CAACE,CAAC,CAAC;IAC1B,IAAI,CAAC5C,MAAM,CAACC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACsC,GAAG,EAAExD,GAAG,CAAC,IAAI,OAAOwD,GAAG,CAACxD,GAAG,CAAC,KAAK,WAAW,EAAE;MACpFwD,GAAG,CAACxD,GAAG,CAAC,GAAGuD,QAAQ,CAACG,aAAa,CAAC1D,GAAG,CAAC;IAC1C;EACJ;EACA,OAAOwD,GAAG;AACd;AAEA,OAAO,IAAMI,yBAA+E,GAAG;EAC3FjF,IAAI,EAAE,QAAQ;EACdC,UAAU,EAAE;IACRiF,EAAE,EAAE;MACAlF,IAAI,EAAE;IACV,CAAC;IACDoE,GAAG,EAAE;MACDpE,IAAI,EAAE;IACV;EACJ,CAAC;EACDI,QAAQ,EAAE,CACN,IAAI,EACJ,KAAK,CACR;EACD+B,oBAAoB,EAAE;AAC1B,CAAU"} \ No newline at end of file +{"version":3,"file":"rx-schema-helper.js","names":["newRxError","appendToArray","ensureNotFalsy","flatClone","getProperty","isMaybeReadonlyArray","REGEX_ALL_DOTS","RX_META_LWT_MINIMUM","sortObject","trimDots","getPseudoSchemaForVersion","version","primaryKey","pseudoSchema","fillWithDefaultSettings","type","properties","maxLength","indexes","required","getSchemaByObjectPath","rxJsonSchema","path","usePath","replace","ret","fillPrimaryKey","primaryPath","jsonSchema","documentData","newPrimary","getComposedPrimaryKeyOfDocumentData","existingPrimary","args","schema","getPrimaryFieldOfPrimaryKey","key","getLengthOfPrimaryKey","schemaPart","compositePrimary","fields","map","field","value","join","separator","normalizeRxJsonSchema","normalizedSchema","getDefaultIndex","schemaObj","additionalProperties","Object","prototype","hasOwnProperty","call","keyCompression","slice","encrypted","_rev","minLength","_attachments","_deleted","_meta","RX_META_SCHEMA","push","finalFields","getFinalFields","filter","includes","elem","pos","arr","indexOf","useIndexes","index","arIndex","unshift","length","internalIndexes","idx","hasIndex","Set","indexStr","has","add","lwt","minimum","maximum","multipleOf","keys","final","forEach","fillObjectWithDefaults","rxSchema","obj","defaultKeys","defaultValues","i","DEFAULT_CHECKPOINT_SCHEMA","id"],"sources":["../../src/rx-schema-helper.ts"],"sourcesContent":["import { newRxError } from './rx-error.ts';\nimport type {\n CompositePrimaryKey,\n DeepReadonly,\n JsonSchema,\n PrimaryKey,\n RxDocumentData,\n RxJsonSchema,\n RxStorageDefaultCheckpoint,\n StringKeys\n} from './types/index.d.ts';\nimport {\n appendToArray,\n ensureNotFalsy,\n flatClone,\n getProperty,\n isMaybeReadonlyArray,\n REGEX_ALL_DOTS,\n RX_META_LWT_MINIMUM,\n sortObject,\n trimDots\n} from './plugins/utils/index.ts';\nimport type { RxSchema } from './rx-schema.ts';\n\n/**\n * Helper function to create a valid RxJsonSchema\n * with a given version.\n */\nexport function getPseudoSchemaForVersion(\n version: number,\n primaryKey: StringKeys\n): RxJsonSchema> {\n const pseudoSchema: RxJsonSchema> = fillWithDefaultSettings({\n version,\n type: 'object',\n primaryKey: primaryKey as any,\n properties: {\n [primaryKey]: {\n type: 'string',\n maxLength: 100\n }\n } as any,\n indexes: [\n [primaryKey]\n ],\n required: [primaryKey]\n });\n return pseudoSchema;\n}\n\n/**\n * Returns the sub-schema for a given path\n */\nexport function getSchemaByObjectPath(\n rxJsonSchema: RxJsonSchema,\n path: keyof T | string\n): JsonSchema {\n let usePath: string = path as string;\n usePath = usePath.replace(REGEX_ALL_DOTS, '.properties.');\n usePath = 'properties.' + usePath;\n usePath = trimDots(usePath);\n\n const ret = getProperty(rxJsonSchema, usePath);\n return ret;\n}\n\nexport function fillPrimaryKey(\n primaryPath: keyof T,\n jsonSchema: RxJsonSchema,\n documentData: RxDocumentData\n): RxDocumentData {\n // optimization shortcut.\n if (typeof jsonSchema.primaryKey === 'string') {\n return documentData;\n }\n\n const newPrimary = getComposedPrimaryKeyOfDocumentData(\n jsonSchema,\n documentData\n );\n const existingPrimary: string | undefined = documentData[primaryPath] as any;\n if (\n existingPrimary &&\n existingPrimary !== newPrimary\n ) {\n throw newRxError(\n 'DOC19',\n {\n args: {\n documentData,\n existingPrimary,\n newPrimary,\n },\n schema: jsonSchema\n });\n }\n\n (documentData as any)[primaryPath] = newPrimary;\n return documentData;\n}\n\nexport function getPrimaryFieldOfPrimaryKey(\n primaryKey: PrimaryKey\n): StringKeys {\n if (typeof primaryKey === 'string') {\n return primaryKey as any;\n } else {\n return (primaryKey as CompositePrimaryKey).key;\n }\n}\n\nexport function getLengthOfPrimaryKey(\n schema: RxJsonSchema>\n): number {\n const primaryPath = getPrimaryFieldOfPrimaryKey(schema.primaryKey);\n const schemaPart = getSchemaByObjectPath(schema, primaryPath);\n return ensureNotFalsy(schemaPart.maxLength);\n}\n\n/**\n * Returns the composed primaryKey of a document by its data.\n */\nexport function getComposedPrimaryKeyOfDocumentData(\n jsonSchema: RxJsonSchema | RxJsonSchema>,\n documentData: Partial\n): string {\n if (typeof jsonSchema.primaryKey === 'string') {\n return (documentData as any)[jsonSchema.primaryKey];\n }\n\n const compositePrimary: CompositePrimaryKey = jsonSchema.primaryKey as any;\n return compositePrimary.fields.map(field => {\n const value = getProperty(documentData as any, field as string);\n if (typeof value === 'undefined') {\n throw newRxError('DOC18', { args: { field, documentData } });\n }\n return value;\n }).join(compositePrimary.separator);\n}\n\n\n/**\n * Normalize the RxJsonSchema.\n * We need this to ensure everything is set up properly\n * and we have the same hash on schemas that represent the same value but\n * have different json.\n *\n * - Orders the schemas attributes by alphabetical order\n * - Adds the primaryKey to all indexes that do not contain the primaryKey\n * - We need this for deterministic sort order on all queries, which is required for event-reduce to work.\n *\n * @return RxJsonSchema - ordered and filled\n */\nexport function normalizeRxJsonSchema(jsonSchema: RxJsonSchema): RxJsonSchema {\n const normalizedSchema: RxJsonSchema = sortObject(jsonSchema, true);\n return normalizedSchema;\n}\n\n/**\n * If the schema does not specify any index,\n * we add this index so we at least can run RxQuery()\n * and only select non-deleted fields.\n */\nexport function getDefaultIndex(primaryPath: string) {\n return ['_deleted', primaryPath];\n}\n\n/**\n * fills the schema-json with default-settings\n * @return cloned schemaObj\n */\nexport function fillWithDefaultSettings(\n schemaObj: RxJsonSchema\n): RxJsonSchema> {\n schemaObj = flatClone(schemaObj);\n const primaryPath: string = getPrimaryFieldOfPrimaryKey(schemaObj.primaryKey);\n schemaObj.properties = flatClone(schemaObj.properties);\n\n // additionalProperties is always false\n schemaObj.additionalProperties = false;\n\n // fill with key-compression-state ()\n if (!Object.prototype.hasOwnProperty.call(schemaObj, 'keyCompression')) {\n schemaObj.keyCompression = false;\n }\n\n // indexes must be array\n schemaObj.indexes = schemaObj.indexes ? schemaObj.indexes.slice(0) : [];\n\n // required must be array\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n\n // encrypted must be array\n schemaObj.encrypted = schemaObj.encrypted ? schemaObj.encrypted.slice(0) : [];\n\n // add _rev\n (schemaObj.properties as any)._rev = {\n type: 'string',\n minLength: 1\n };\n\n // add attachments\n (schemaObj.properties as any)._attachments = {\n type: 'object'\n };\n\n // add deleted flag\n (schemaObj.properties as any)._deleted = {\n type: 'boolean'\n };\n\n // add meta property\n (schemaObj.properties as any)._meta = RX_META_SCHEMA;\n\n /**\n * meta fields are all required\n */\n schemaObj.required = schemaObj.required ? schemaObj.required.slice(0) : [];\n (schemaObj.required as string[]).push('_deleted');\n (schemaObj.required as string[]).push('_rev');\n (schemaObj.required as string[]).push('_meta');\n (schemaObj.required as string[]).push('_attachments');\n\n // final fields are always required\n const finalFields = getFinalFields(schemaObj);\n appendToArray(schemaObj.required as any, finalFields);\n schemaObj.required = schemaObj.required\n .filter((field: string) => !field.includes('.'))\n .filter((elem: any, pos: any, arr: any) => arr.indexOf(elem) === pos); // unique;\n\n // version is 0 by default\n schemaObj.version = schemaObj.version || 0;\n\n const useIndexes: string[][] = schemaObj.indexes.map(index => {\n const arIndex = isMaybeReadonlyArray(index) ? index.slice(0) : [index];\n /**\n * Append primary key to indexes that do not contain the primaryKey.\n * All indexes must have the primaryKey to ensure a deterministic sort order.\n */\n if (!arIndex.includes(primaryPath)) {\n arIndex.push(primaryPath);\n }\n\n // add _deleted flag to all indexes so we can query only non-deleted fields\n // in RxDB itself\n if (arIndex[0] !== '_deleted') {\n arIndex.unshift('_deleted');\n }\n\n return arIndex;\n });\n\n if (useIndexes.length === 0) {\n useIndexes.push(getDefaultIndex(primaryPath));\n }\n\n // we need this index for the getChangedDocumentsSince() method\n useIndexes.push(['_meta.lwt', primaryPath]);\n\n // also add the internalIndexes\n if (schemaObj.internalIndexes) {\n schemaObj.internalIndexes.map(idx => {\n useIndexes.push(idx);\n });\n }\n\n // make indexes unique\n const hasIndex = new Set();\n useIndexes.filter(index => {\n const indexStr = index.join(',');\n if (hasIndex.has(indexStr)) {\n return false;\n } else {\n hasIndex.add(indexStr);\n return true;\n }\n });\n\n schemaObj.indexes = useIndexes;\n\n return schemaObj as any;\n}\n\n\nexport const RX_META_SCHEMA: JsonSchema = {\n type: 'object',\n properties: {\n /**\n * The last-write time.\n * Unix time in milliseconds.\n */\n lwt: {\n type: 'number',\n /**\n * We use 1 as minimum so that the value is never falsy.\n */\n minimum: RX_META_LWT_MINIMUM,\n maximum: 1000000000000000,\n multipleOf: 0.01\n }\n },\n /**\n * Additional properties are allowed\n * and can be used by plugins to set various flags.\n */\n additionalProperties: true as any,\n required: [\n 'lwt'\n ]\n};\n\n\n/**\n * returns the final-fields of the schema\n * @return field-names of the final-fields\n */\nexport function getFinalFields(\n jsonSchema: RxJsonSchema\n): string[] {\n const ret = Object.keys(jsonSchema.properties)\n .filter(key => (jsonSchema as any).properties[key].final);\n\n // primary is also final\n const primaryPath = getPrimaryFieldOfPrimaryKey(jsonSchema.primaryKey);\n ret.push(primaryPath);\n\n // fields of composite primary are final\n if (typeof jsonSchema.primaryKey !== 'string') {\n (jsonSchema.primaryKey as CompositePrimaryKey).fields\n .forEach(field => ret.push(field as string));\n }\n\n return ret;\n}\n\n/**\n * fills all unset fields with default-values if set\n * @hotPath\n */\nexport function fillObjectWithDefaults(rxSchema: RxSchema, obj: any): any {\n const defaultKeys = Object.keys(rxSchema.defaultValues);\n for (let i = 0; i < defaultKeys.length; ++i) {\n const key = defaultKeys[i];\n if (!Object.prototype.hasOwnProperty.call(obj, key) || typeof obj[key] === 'undefined') {\n obj[key] = rxSchema.defaultValues[key];\n }\n }\n return obj;\n}\n\nexport const DEFAULT_CHECKPOINT_SCHEMA: DeepReadonly> = {\n type: 'object',\n properties: {\n id: {\n type: 'string'\n },\n lwt: {\n type: 'number'\n }\n },\n required: [\n 'id',\n 'lwt'\n ],\n additionalProperties: false\n} as const;\n"],"mappings":"AAAA,SAASA,UAAU,QAAQ,eAAe;AAW1C,SACIC,aAAa,EACbC,cAAc,EACdC,SAAS,EACTC,WAAW,EACXC,oBAAoB,EACpBC,cAAc,EACdC,mBAAmB,EACnBC,UAAU,EACVC,QAAQ,QACL,0BAA0B;AAGjC;AACA;AACA;AACA;AACA,OAAO,SAASC,yBAAyBA,CACrCC,OAAe,EACfC,UAAyB,EACM;EAC/B,IAAMC,YAA6C,GAAGC,uBAAuB,CAAC;IAC1EH,OAAO;IACPI,IAAI,EAAE,QAAQ;IACdH,UAAU,EAAEA,UAAiB;IAC7BI,UAAU,EAAE;MACR,CAACJ,UAAU,GAAG;QACVG,IAAI,EAAE,QAAQ;QACdE,SAAS,EAAE;MACf;IACJ,CAAQ;IACRC,OAAO,EAAE,CACL,CAACN,UAAU,CAAC,CACf;IACDO,QAAQ,EAAE,CAACP,UAAU;EACzB,CAAC,CAAC;EACF,OAAOC,YAAY;AACvB;;AAEA;AACA;AACA;AACA,OAAO,SAASO,qBAAqBA,CACjCC,YAA6B,EAC7BC,IAAsB,EACZ;EACV,IAAIC,OAAe,GA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rx-storage-helper.js index 902241f2e38..7681fc11700 100644 --- a/dist/esm/rx-storage-helper.js +++ b/dist/esm/rx-storage-helper.js @@ -8,6 +8,7 @@ import { fillPrimaryKey, getPrimaryFieldOfPrimaryKey } from "./rx-schema-helper. import { PROMISE_RESOLVE_TRUE, RXDB_VERSION, RX_META_LWT_MINIMUM, appendToArray, createRevision, ensureNotFalsy, flatClone, getDefaultRevision, getDefaultRxDocumentMeta, lastOfArray, now, promiseWait, randomCouchString } from "./plugins/utils/index.js"; import { filter, map, startWith, switchMap } from 'rxjs'; import { prepareQuery } from "./rx-query.js"; +import { normalizeMangoQuery } from "./rx-query-helper.js"; export var INTERNAL_STORAGE_NAME = '_rxdb_internal'; export var RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local'; export async function getSingleDocument(storageInstance, documentId) { @@ -634,14 +635,11 @@ export function hasEncryption(jsonSchema) { return false; } } -export async function getChangedDocumentsSince(storageInstance, limit, checkpoint) { - if (storageInstance.getChangedDocumentsSince) { - return storageInstance.getChangedDocumentsSince(limit, checkpoint); - } +export function getChangedDocumentsSinceQuery(storageInstance, limit, checkpoint) { var primaryPath = getPrimaryFieldOfPrimaryKey(storageInstance.schema.primaryKey); var sinceLwt = checkpoint ? checkpoint.lwt : RX_META_LWT_MINIMUM; var sinceId = checkpoint ? checkpoint.id : ''; - var query = prepareQuery(storageInstance.schema, { + return normalizeMangoQuery(storageInstance.schema, { selector: { $or: [{ '_meta.lwt': { @@ -666,9 +664,23 @@ export async function getChangedDocumentsSince(storageInstance, limit, checkpoin [primaryPath]: 'asc' }], skip: 0, - limit, - index: ['_meta.lwt', primaryPath] + limit + /** + * DO NOT SET A SPECIFIC INDEX HERE! + * The query might be modified by some plugin + * before sending it to the storage. + * We can be sure that in the end the query planner + * will find the best index. + */ + // index: ['_meta.lwt', primaryPath] }); +} +export async function getChangedDocumentsSince(storageInstance, limit, checkpoint) { + if (storageInstance.getChangedDocumentsSince) { + return storageInstance.getChangedDocumentsSince(limit, checkpoint); + } + var primaryPath = getPrimaryFieldOfPrimaryKey(storageInstance.schema.primaryKey); + var query = prepareQuery(storageInstance.schema, getChangedDocumentsSinceQuery(storageInstance, limit, checkpoint)); var result = await storageInstance.query(query); var documents = result.documents; var lastDoc = lastOfArray(documents); diff --git a/dist/esm/rx-storage-helper.js.map b/dist/esm/rx-storage-helper.js.map index feb05d5bd1d..b1f5891ee71 100644 --- a/dist/esm/rx-storage-helper.js.map +++ b/dist/esm/rx-storage-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-helper.js","names":["overwritable","newRxError","fillPrimaryKey","getPrimaryFieldOfPrimaryKey","PROMISE_RESOLVE_TRUE","RXDB_VERSION","RX_META_LWT_MINIMUM","appendToArray","createRevision","ensureNotFalsy","flatClone","getDefaultRevision","getDefaultRxDocumentMeta","lastOfArray","now","promiseWait","randomCouchString","filter","map","startWith","switchMap","prepareQuery","INTERNAL_STORAGE_NAME","RX_DATABASE_LOCAL_DOCS_STORAGE_NAME","getSingleDocument","storageInstance","documentId","results","findDocumentsById","doc","undefined","writeSingle","instance","writeRow","context","writeResult","bulkWrite","error","length","ret","success","observeSingle","firstFindPromise","changeStream","pipe","evBulk","events","find","ev","Promise","resolve","documentData","v","stackCheckpoints","checkpoints","Object","assign","storageChangeEventToRxChangeEvent","isLocal","rxStorageChangeEvent","rxCollection","previousDocumentData","collectionName","name","operation","deepFreezeWhenDevMode","throwIfIsStorageWriteError","collection","writeData","status","id","writeError","data","categorizeBulkWriteRows","primaryPath","docsInDb","bulkWriteRows","onInsert","onUpdate","hasAttachments","schema","attachments","bulkInsertDocs","bulkUpdateDocs","errors","eventBulkId","eventBulk","checkpoint","startTime","endTime","eventBulkEvents","attachmentsAdd","attachmentsRemove","attachmentsUpdate","hasDocsInDb","size","newestRow","rowAmount","_loop","rowId","document","previous","docId","documentDeleted","_deleted","previousDeleted","documentInDb","get","attachmentError","insertedIsDeleted","entries","_attachments","forEach","attachmentId","attachmentData","isError","push","digest","stripAttachmentsDataFromRow","event","stripAttachmentsDataFromDocument","revInDb","_rev","err","updatedRow","keys","previousAttachmentData","newDigest","eventDocumentData","previousEventDocumentData","args","getAttachmentSize","attachmentBase64String","atob","attachmentWriteDataToNormalData","type","useDoc","flatCloneDocWithMeta","_meta","getWrappedStorageInstance","database","rxJsonSchema","primaryKey","transformDocumentDataFromRxDBToRxStorage","isDevMode","structuredClone","JSON","parse","stringify","metaFieldName","prototype","hasOwnProperty","call","dataBefore","dataAfter","lwt","token","originalStorageInstance","internals","databaseName","options","rows","toStorageWriteRows","row","lockedRun","then","useWriteResult","slice","reInsertErrors","reInserts","subResult","query","preparedQuery","count","ids","deleted","getAttachmentData","getChangedDocumentsSince","limit","cleanup","minDeletedTime","remove","storageInstances","delete","close","conflictResultionTasks","resolveConflictResultionTask","taskSolution","output","isEqual","add","ensureRxStorageInstanceParamsAreCorrect","params","keyCompression","hasEncryption","compression","jsonSchema","encrypted","sinceLwt","sinceId","selector","$or","$gt","$eq","$gte","sort","skip","index","result","documents","lastDoc","randomDelayStorage","input","retStorage","storage","rxdbVersion","createStorageInstance","delayTimeBefore","delayTimeAfter","writeQueue","a","b","response","c"],"sources":["../../src/rx-storage-helper.ts"],"sourcesContent":["/**\n * Helper functions for accessing the RxStorage instances.\n */\n\nimport { overwritable } from './overwritable.ts';\nimport { newRxError } from './rx-error.ts';\nimport {\n fillPrimaryKey,\n getPrimaryFieldOfPrimaryKey\n} from './rx-schema-helper.ts';\nimport type {\n BulkWriteRow,\n BulkWriteRowProcessed,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorageWriteError,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n StringKeys,\n RxStorageWriteErrorConflict,\n RxStorageWriteErrorAttachment,\n RxStorage,\n RxStorageDefaultCheckpoint\n} from './types/index.d.ts';\nimport {\n PROMISE_RESOLVE_TRUE,\n RXDB_VERSION,\n RX_META_LWT_MINIMUM,\n appendToArray,\n createRevision,\n ensureNotFalsy,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n lastOfArray,\n now,\n promiseWait,\n randomCouchString\n} from './plugins/utils/index.ts';\nimport { Observable, filter, map, startWith, switchMap } from 'rxjs';\nimport { prepareQuery } from './rx-query.ts';\n\nexport const INTERNAL_STORAGE_NAME = '_rxdb_internal';\nexport const RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local';\n\nexport async function getSingleDocument(\n storageInstance: RxStorageInstance,\n documentId: string\n): Promise | undefined> {\n const results = await storageInstance.findDocumentsById([documentId], false);\n const doc = results[0];\n if (doc) {\n return doc;\n } else {\n return undefined;\n }\n}\n\n/**\n * Writes a single document,\n * throws RxStorageBulkWriteError on failure\n */\nexport async function writeSingle(\n instance: RxStorageInstance,\n writeRow: BulkWriteRow,\n context: string\n): Promise> {\n const writeResult = await instance.bulkWrite(\n [writeRow],\n context\n );\n if (writeResult.error.length > 0) {\n const error = writeResult.error[0];\n throw error;\n } else {\n const ret = writeResult.success[0];\n return ret;\n }\n}\n\n/**\n * Observe the plain document data of a single document.\n * Do not forget to unsubscribe.\n */\nexport function observeSingle(\n storageInstance: RxStorageInstance,\n documentId: string\n): Observable> {\n const firstFindPromise = getSingleDocument(storageInstance, documentId);\n const ret = storageInstance\n .changeStream()\n .pipe(\n map(evBulk => evBulk.events.find(ev => ev.documentId === documentId)),\n filter(ev => !!ev),\n map(ev => Promise.resolve(ensureNotFalsy(ev).documentData)),\n startWith(firstFindPromise),\n switchMap(v => v),\n filter(v => !!v)\n ) as any;\n return ret;\n}\n\n\n/**\n * Checkpoints must be stackable over another.\n * This is required form some RxStorage implementations\n * like the sharding plugin, where a checkpoint only represents\n * the document state from some, but not all shards.\n */\nexport function stackCheckpoints(\n checkpoints: CheckpointType[]\n): CheckpointType {\n return Object.assign(\n {},\n ...checkpoints\n );\n}\n\nexport function storageChangeEventToRxChangeEvent(\n isLocal: boolean,\n rxStorageChangeEvent: RxStorageChangeEvent,\n rxCollection?: RxCollection,\n): RxChangeEvent {\n const documentData = rxStorageChangeEvent.documentData;\n const previousDocumentData = rxStorageChangeEvent.previousDocumentData;\n const ret: RxChangeEvent = {\n documentId: rxStorageChangeEvent.documentId,\n collectionName: rxCollection ? rxCollection.name : undefined,\n isLocal,\n operation: rxStorageChangeEvent.operation,\n documentData: overwritable.deepFreezeWhenDevMode(documentData as any),\n previousDocumentData: overwritable.deepFreezeWhenDevMode(previousDocumentData as any)\n };\n return ret;\n}\n\nexport function throwIfIsStorageWriteError(\n collection: RxCollection,\n documentId: string,\n writeData: RxDocumentWriteData | RxDocType,\n error: RxStorageWriteError | undefined\n) {\n if (error) {\n if (error.status === 409) {\n throw newRxError('CONFLICT', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else if (error.status === 422) {\n throw newRxError('VD2', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else {\n throw error;\n }\n }\n}\n\n\n/**\n * Analyzes a list of BulkWriteRows and determines\n * which documents must be inserted, updated or deleted\n * and which events must be emitted and which documents cause a conflict\n * and must not be written.\n * Used as helper inside of some RxStorage implementations.\n * @hotPath The performance of this function is critical\n */\nexport function categorizeBulkWriteRows(\n storageInstance: RxStorageInstance,\n primaryPath: StringKeys,\n /**\n * Current state of the documents\n * inside of the storage. Used to determine\n * which writes cause conflicts.\n * This must be a Map for better performance.\n */\n docsInDb: Map[StringKeys] | string, RxDocumentData>,\n /**\n * The write rows that are passed to\n * RxStorageInstance().bulkWrite().\n */\n bulkWriteRows: BulkWriteRow[],\n context: string,\n /**\n * Used by some storages for better performance.\n * For example when get-by-id and insert/update can run in parallel.\n */\n onInsert?: (docData: RxDocumentData) => void,\n onUpdate?: (docData: RxDocumentData) => void\n): CategorizeBulkWriteRowsOutput {\n const hasAttachments = !!storageInstance.schema.attachments;\n const bulkInsertDocs: BulkWriteRowProcessed[] = [];\n const bulkUpdateDocs: BulkWriteRowProcessed[] = [];\n const errors: RxStorageWriteError[] = [];\n const eventBulkId = randomCouchString(10);\n const eventBulk: EventBulk>, any> = {\n id: eventBulkId,\n events: [],\n checkpoint: null,\n context,\n startTime: now(),\n endTime: 0\n };\n const eventBulkEvents = eventBulk.events;\n\n const attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n digest: string;\n }[] = [];\n const attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n digest: string;\n }[] = [];\n const attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n digest: string;\n }[] = [];\n\n const hasDocsInDb = docsInDb.size > 0;\n let newestRow: BulkWriteRowProcessed | undefined;\n\n /**\n * @performance is really important in this loop!\n */\n const rowAmount = bulkWriteRows.length;\n for (let rowId = 0; rowId < rowAmount; rowId++) {\n const writeRow = bulkWriteRows[rowId];\n\n // use these variables to have less property accesses\n const document = writeRow.document;\n const previous = writeRow.previous;\n const docId = document[primaryPath] as string;\n const documentDeleted = document._deleted;\n const previousDeleted = previous && previous._deleted;\n\n let documentInDb: RxDocumentData | undefined = undefined as any;\n if (hasDocsInDb) {\n documentInDb = docsInDb.get(docId);\n }\n let attachmentError: RxStorageWriteErrorAttachment | undefined;\n\n if (!documentInDb) {\n /**\n * It is possible to insert already deleted documents,\n * this can happen on replication.\n */\n const insertedIsDeleted = documentDeleted ? true : false;\n if (hasAttachments) {\n Object\n .entries(document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n if (\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: docId,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n errors.push(attachmentError);\n } else {\n attachmentsAdd.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as any,\n digest: attachmentData.digest\n });\n }\n });\n }\n if (!attachmentError) {\n if (hasAttachments) {\n bulkInsertDocs.push(stripAttachmentsDataFromRow(writeRow));\n if (onInsert) {\n onInsert(document);\n }\n } else {\n bulkInsertDocs.push(writeRow as any);\n if (onInsert) {\n onInsert(document);\n }\n }\n\n newestRow = writeRow as any;\n }\n\n if (!insertedIsDeleted) {\n const event = {\n documentId: docId,\n operation: 'INSERT' as const,\n documentData: hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any,\n previousDocumentData: hasAttachments && previous ? stripAttachmentsDataFromDocument(previous) : previous as any\n };\n eventBulkEvents.push(event);\n }\n } else {\n // update existing document\n const revInDb: string = documentInDb._rev;\n\n /**\n * Check for conflict\n */\n if (\n (\n !previous\n ) ||\n (\n !!previous &&\n revInDb !== previous._rev\n )\n ) {\n // is conflict error\n const err: RxStorageWriteError = {\n isError: true,\n status: 409,\n documentId: docId,\n writeRow: writeRow,\n documentInDb\n };\n errors.push(err);\n continue;\n }\n\n // handle attachments data\n\n const updatedRow: BulkWriteRowProcessed = hasAttachments ? stripAttachmentsDataFromRow(writeRow) : writeRow as any;\n if (hasAttachments) {\n if (documentDeleted) {\n /**\n * Deleted documents must have cleared all their attachments.\n */\n if (previous) {\n Object\n .keys(previous._attachments)\n .forEach(attachmentId => {\n attachmentsRemove.push({\n documentId: docId,\n attachmentId,\n digest: ensureNotFalsy(previous)._attachments[attachmentId].digest\n });\n });\n }\n } else {\n // first check for errors\n Object\n .entries(document._attachments)\n .find(([attachmentId, attachmentData]) => {\n const previousAttachmentData = previous ? previous._attachments[attachmentId] : undefined;\n if (\n !previousAttachmentData &&\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: docId,\n documentInDb: documentInDb as any,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n }\n return true;\n });\n if (!attachmentError) {\n Object\n .entries(document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n const previousAttachmentData = previous ? previous._attachments[attachmentId] : undefined;\n if (!previousAttachmentData) {\n attachmentsAdd.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as any,\n digest: attachmentData.digest\n });\n } else {\n const newDigest = updatedRow.document._attachments[attachmentId].digest;\n if (\n (attachmentData as RxAttachmentWriteData).data &&\n /**\n * Performance shortcut,\n * do not update the attachment data if it did not change.\n */\n previousAttachmentData.digest !== newDigest\n ) {\n attachmentsUpdate.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as RxAttachmentWriteData,\n digest: attachmentData.digest\n });\n }\n }\n });\n }\n }\n }\n\n if (attachmentError) {\n errors.push(attachmentError);\n } else {\n if (hasAttachments) {\n bulkUpdateDocs.push(stripAttachmentsDataFromRow(updatedRow));\n if (onUpdate) {\n onUpdate(document);\n }\n } else {\n bulkUpdateDocs.push(updatedRow);\n if (onUpdate) {\n onUpdate(document);\n }\n }\n newestRow = updatedRow as any;\n }\n\n let eventDocumentData: RxDocumentData | undefined = null as any;\n let previousEventDocumentData: RxDocumentData | undefined = null as any;\n let operation: 'INSERT' | 'UPDATE' | 'DELETE' = null as any;\n\n if (previousDeleted && !documentDeleted) {\n operation = 'INSERT';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any;\n } else if (previous && !previousDeleted && !documentDeleted) {\n operation = 'UPDATE';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any;\n previousEventDocumentData = previous;\n } else if (documentDeleted) {\n operation = 'DELETE';\n eventDocumentData = ensureNotFalsy(document) as any;\n previousEventDocumentData = previous;\n } else {\n throw newRxError('SNH', { args: { writeRow } });\n }\n\n const event = {\n documentId: docId,\n documentData: eventDocumentData as RxDocumentData,\n previousDocumentData: previousEventDocumentData,\n operation: operation\n };\n eventBulkEvents.push(event);\n }\n }\n\n return {\n bulkInsertDocs,\n bulkUpdateDocs,\n newestRow,\n errors,\n eventBulk,\n attachmentsAdd,\n attachmentsRemove,\n attachmentsUpdate\n };\n}\n\nexport function stripAttachmentsDataFromRow(writeRow: BulkWriteRow): BulkWriteRowProcessed {\n return {\n previous: writeRow.previous,\n document: stripAttachmentsDataFromDocument(writeRow.document)\n };\n}\n\nexport function getAttachmentSize(\n attachmentBase64String: string\n): number {\n return atob(attachmentBase64String).length;\n}\n\n/**\n * Used in custom RxStorage implementations.\n */\nexport function attachmentWriteDataToNormalData(writeData: RxAttachmentData | RxAttachmentWriteData): RxAttachmentData {\n const data = (writeData as RxAttachmentWriteData).data;\n if (!data) {\n return writeData as any;\n }\n const ret: RxAttachmentData = {\n length: getAttachmentSize(data),\n digest: writeData.digest,\n type: writeData.type\n };\n return ret;\n}\n\nexport function stripAttachmentsDataFromDocument(doc: RxDocumentWriteData): RxDocumentData {\n\n if (!doc._attachments || Object.keys(doc._attachments).length === 0) {\n return doc;\n }\n\n const useDoc: RxDocumentData = flatClone(doc) as any;\n useDoc._attachments = {};\n Object\n .entries(doc._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n useDoc._attachments[attachmentId] = attachmentWriteDataToNormalData(attachmentData);\n });\n return useDoc;\n}\n\n/**\n * Flat clone the document data\n * and also the _meta field.\n * Used many times when we want to change the meta\n * during replication etc.\n */\nexport function flatCloneDocWithMeta(\n doc: RxDocumentData\n): RxDocumentData {\n const ret = flatClone(doc);\n ret._meta = flatClone(doc._meta);\n return ret;\n}\n\nexport type WrappedRxStorageInstance = RxStorageInstance & {\n originalStorageInstance: RxStorageInstance;\n};\n\n/**\n * Wraps the normal storageInstance of a RxCollection\n * to ensure that all access is properly using the hooks\n * and other data transformations and also ensure that database.lockedRun()\n * is used properly.\n */\nexport function getWrappedStorageInstance<\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType\n>(\n database: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstance: RxStorageInstance,\n /**\n * The original RxJsonSchema\n * before it was mutated by hooks.\n */\n rxJsonSchema: RxJsonSchema>\n): WrappedRxStorageInstance {\n overwritable.deepFreezeWhenDevMode(rxJsonSchema);\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function transformDocumentDataFromRxDBToRxStorage(\n writeRow: BulkWriteRow\n ) {\n let data = flatClone(writeRow.document);\n data._meta = flatClone(data._meta);\n\n /**\n * Do some checks in dev-mode\n * that would be too performance expensive\n * in production.\n */\n if (overwritable.isDevMode()) {\n // ensure that the primary key has not been changed\n data = fillPrimaryKey(\n primaryPath,\n rxJsonSchema,\n data as any\n );\n\n\n /**\n * Ensure it can be structured cloned\n */\n try {\n /**\n * Notice that structuredClone() is not available\n * in ReactNative, so we test for JSON.stringify() instead\n * @link https://github.com/pubkey/rxdb/issues/5046#issuecomment-1827374498\n */\n if (typeof structuredClone === 'function') {\n structuredClone(writeRow);\n } else {\n JSON.parse(JSON.stringify(writeRow));\n }\n } catch (err) {\n throw newRxError('DOC24', {\n collection: storageInstance.collectionName,\n document: writeRow.document\n });\n }\n\n /**\n * Ensure that the new revision is higher\n * then the previous one\n */\n if (writeRow.previous) {\n // TODO run this in the dev-mode plugin\n // const prev = parseRevision(writeRow.previous._rev);\n // const current = parseRevision(writeRow.document._rev);\n // if (current.height <= prev.height) {\n // throw newRxError('SNH', {\n // dataBefore: writeRow.previous,\n // dataAfter: writeRow.document,\n // args: {\n // prev,\n // current\n // }\n // });\n // }\n }\n\n /**\n * Ensure that _meta fields have been merged\n * and not replaced.\n * This is important so that when one plugin A\n * sets a _meta field and another plugin B does a write\n * to the document, it must be ensured that the\n * field of plugin A was not removed.\n */\n if (writeRow.previous) {\n Object.keys(writeRow.previous._meta)\n .forEach(metaFieldName => {\n if (!Object.prototype.hasOwnProperty.call(writeRow.document._meta, metaFieldName)) {\n throw newRxError('SNH', {\n dataBefore: writeRow.previous,\n dataAfter: writeRow.document\n });\n }\n });\n }\n }\n data._meta.lwt = now();\n\n /**\n * Yes we really want to set the revision here.\n * If you make a plugin that relies on having its own revision\n * stored into the storage, use this.originalStorageInstance.bulkWrite() instead.\n */\n data._rev = createRevision(\n database.token,\n writeRow.previous\n );\n\n return {\n document: data,\n previous: writeRow.previous\n };\n }\n\n const ret: WrappedRxStorageInstance = {\n originalStorageInstance: storageInstance,\n schema: storageInstance.schema,\n internals: storageInstance.internals,\n collectionName: storageInstance.collectionName,\n databaseName: storageInstance.databaseName,\n options: storageInstance.options,\n bulkWrite(\n rows: BulkWriteRow[],\n context: string\n ) {\n const toStorageWriteRows: BulkWriteRow[] = rows\n .map(row => transformDocumentDataFromRxDBToRxStorage(row));\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n toStorageWriteRows,\n context\n )\n )\n /**\n * The RxStorageInstance MUST NOT allow to insert already _deleted documents,\n * without sending the previous document version.\n * But for better developer experience, RxDB does allow to re-insert deleted documents.\n * We do this by automatically fixing the conflict errors for that case\n * by running another bulkWrite() and merging the results.\n * @link https://github.com/pubkey/rxdb/pull/3839\n */\n .then(writeResult => {\n const useWriteResult: typeof writeResult = {\n error: [],\n success: writeResult.success.slice(0)\n };\n const reInsertErrors: RxStorageWriteErrorConflict[] =\n writeResult.error\n .filter((error) => {\n if (\n error.status === 409 &&\n !error.writeRow.previous &&\n !error.writeRow.document._deleted &&\n ensureNotFalsy(error.documentInDb)._deleted\n ) {\n return true;\n }\n useWriteResult.error.push(error);\n return false;\n }) as any;\n if (reInsertErrors.length > 0) {\n const reInserts: BulkWriteRow[] = reInsertErrors\n .map((error) => {\n return {\n previous: error.documentInDb,\n document: Object.assign(\n {},\n error.writeRow.document,\n {\n _rev: createRevision(\n database.token,\n error.documentInDb\n )\n }\n )\n };\n });\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n reInserts,\n context\n )\n ).then(subResult => {\n appendToArray(useWriteResult.error, subResult.error);\n appendToArray(useWriteResult.success, subResult.success);\n return useWriteResult;\n });\n }\n\n return writeResult;\n });\n },\n query(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.query(preparedQuery)\n );\n },\n count(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.count(preparedQuery)\n );\n },\n findDocumentsById(ids, deleted) {\n return database.lockedRun(\n () => storageInstance.findDocumentsById(ids, deleted)\n );\n },\n getAttachmentData(\n documentId: string,\n attachmentId: string,\n digest: string\n ) {\n return database.lockedRun(\n () => storageInstance.getAttachmentData(documentId, attachmentId, digest)\n );\n },\n getChangedDocumentsSince: !storageInstance.getChangedDocumentsSince ? undefined : (limit: number, checkpoint?: any) => {\n return database.lockedRun(\n () => ((storageInstance as any).getChangedDocumentsSince)(ensureNotFalsy(limit), checkpoint)\n );\n },\n cleanup(minDeletedTime: number) {\n return database.lockedRun(\n () => storageInstance.cleanup(minDeletedTime)\n );\n },\n remove() {\n database.storageInstances.delete(ret);\n return database.lockedRun(\n () => storageInstance.remove()\n );\n },\n close() {\n database.storageInstances.delete(ret);\n return database.lockedRun(\n () => storageInstance.close()\n );\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(taskSolution) {\n if (taskSolution.output.isEqual) {\n return storageInstance.resolveConflictResultionTask(taskSolution);\n }\n\n const doc = Object.assign(\n {},\n taskSolution.output.documentData,\n {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n }\n );\n\n const documentData = flatClone(doc);\n delete (documentData as any)._meta;\n delete (documentData as any)._rev;\n delete (documentData as any)._attachments;\n\n return storageInstance.resolveConflictResultionTask({\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData\n }\n });\n }\n };\n\n database.storageInstances.add(ret);\n return ret;\n}\n\n/**\n * Each RxStorage implementation should\n * run this method at the first step of createStorageInstance()\n * to ensure that the configuration is correct.\n */\nexport function ensureRxStorageInstanceParamsAreCorrect(\n params: RxStorageInstanceCreationParams\n) {\n if (params.schema.keyCompression) {\n throw newRxError('UT5', { args: { params } });\n }\n if (hasEncryption(params.schema)) {\n throw newRxError('UT6', { args: { params } });\n }\n if (\n params.schema.attachments &&\n params.schema.attachments.compression\n ) {\n throw newRxError('UT7', { args: { params } });\n }\n}\n\nexport function hasEncryption(jsonSchema: RxJsonSchema): boolean {\n if (\n (!!jsonSchema.encrypted && jsonSchema.encrypted.length > 0) ||\n (jsonSchema.attachments && jsonSchema.attachments.encrypted)\n ) {\n return true;\n } else {\n return false;\n }\n}\n\n\nexport async function getChangedDocumentsSince(\n storageInstance: RxStorageInstance,\n limit: number,\n checkpoint?: CheckpointType\n): Promise<{\n documents: RxDocumentData[];\n /**\n * The checkpoint contains data so that another\n * call to getChangedDocumentsSince() will continue\n * from exactly the last document that was returned before.\n */\n checkpoint: CheckpointType;\n}> {\n if (storageInstance.getChangedDocumentsSince) {\n return storageInstance.getChangedDocumentsSince(limit, checkpoint);\n }\n\n const primaryPath = getPrimaryFieldOfPrimaryKey(storageInstance.schema.primaryKey);\n const sinceLwt = checkpoint ? (checkpoint as unknown as RxStorageDefaultCheckpoint).lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? (checkpoint as unknown as RxStorageDefaultCheckpoint).id : '';\n const query = prepareQuery>(\n storageInstance.schema,\n {\n selector: {\n $or: [\n {\n '_meta.lwt': {\n $gt: sinceLwt\n }\n },\n {\n '_meta.lwt': {\n $eq: sinceLwt\n },\n [primaryPath]: {\n $gt: checkpoint ? sinceId : ''\n }\n }\n ],\n // add this hint for better index usage\n '_meta.lwt': {\n $gte: sinceLwt\n }\n },\n sort: [\n { '_meta.lwt': 'asc' },\n { [primaryPath]: 'asc' }\n ],\n skip: 0,\n limit,\n index: ['_meta.lwt', primaryPath]\n }\n );\n\n const result = await storageInstance.query(query);\n const documents = result.documents;\n const lastDoc = lastOfArray(documents);\n\n return {\n documents: documents,\n checkpoint: lastDoc ? {\n id: (lastDoc as any)[primaryPath],\n lwt: lastDoc._meta.lwt\n } as any : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n}\n\n\n/**\n * Wraps the storage and simluates\n * delays. Mostly used in tests.\n */\nexport function randomDelayStorage(\n input: {\n storage: RxStorage;\n delayTimeBefore: () => number;\n delayTimeAfter: () => number;\n }\n): RxStorage {\n\n const retStorage: RxStorage = {\n name: 'random-delay-' + input.storage.name,\n rxdbVersion: RXDB_VERSION,\n async createStorageInstance(params) {\n await promiseWait(input.delayTimeBefore());\n const storageInstance = await input.storage.createStorageInstance(params);\n await promiseWait(input.delayTimeAfter());\n\n // write still must be processed in order\n let writeQueue: Promise = PROMISE_RESOLVE_TRUE;\n\n return {\n databaseName: storageInstance.databaseName,\n internals: storageInstance.internals,\n options: storageInstance.options,\n schema: storageInstance.schema,\n collectionName: storageInstance.collectionName,\n async bulkWrite(a, b) {\n writeQueue = writeQueue.then(async () => {\n await promiseWait(input.delayTimeBefore());\n const response = await storageInstance.bulkWrite(a, b);\n await promiseWait(input.delayTimeAfter());\n return response;\n });\n const ret = await writeQueue;\n return ret;\n },\n async findDocumentsById(a, b) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.findDocumentsById(a, b);\n await promiseWait(input.delayTimeAfter());\n return ret;\n },\n async query(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.query(a);\n return ret;\n },\n async count(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.count(a);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async getAttachmentData(a, b, c) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.getAttachmentData(a, b, c);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n getChangedDocumentsSince: !storageInstance.getChangedDocumentsSince ? undefined : async (a, b) => {\n await promiseWait(input.delayTimeBefore());\n const ret = await ensureNotFalsy(storageInstance.getChangedDocumentsSince)(a, b);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(a) {\n return storageInstance.resolveConflictResultionTask(a);\n },\n async cleanup(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.cleanup(a);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async close() {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.close();\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async remove() {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.remove();\n await promiseWait(input.delayTimeAfter());\n return ret;\n },\n };\n\n\n }\n };\n return retStorage;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,mBAAmB;AAChD,SAASC,UAAU,QAAQ,eAAe;AAC1C,SACIC,cAAc,EACdC,2BAA2B,QACxB,uBAAuB;AAwB9B,SACIC,oBAAoB,EACpBC,YAAY,EACZC,mBAAmB,EACnBC,aAAa,EACbC,cAAc,EACdC,cAAc,EACdC,SAAS,EACTC,kBAAkB,EAClBC,wBAAwB,EACxBC,WAAW,EACXC,GAAG,EACHC,WAAW,EACXC,iBAAiB,QACd,0BAA0B;AACjC,SAAqBC,MAAM,EAAEC,GAAG,EAAEC,SAAS,EAAEC,SAAS,QAAQ,MAAM;AACpE,SAASC,YAAY,QAAQ,eAAe;AAE5C,OAAO,IAAMC,qBAAqB,GAAG,gBAAgB;AACrD,OAAO,IAAMC,mCAAmC,GAAG,0BAA0B;AAE7E,OAAO,eAAeC,iBAAiBA,CACnCC,eAAuD,EACvDC,UAAkB,EAC4B;EAC9C,IAAMC,OAAO,GAAG,MAAMF,eAAe,CAACG,iBAAiB,CAAC,CAACF,UAAU,CAAC,EAAE,KAAK,CAAC;EAC5E,IAAMG,GAAG,GAAGF,OAAO,CAAC,CAAC,CAAC;EACtB,IAAIE,GAAG,EAAE;IACL,OAAOA,GAAG;EACd,CAAC,MAAM;IACH,OAAOC,SAAS;EACpB;AACJ;;AAEA;AACA;AACA;AACA;AACA,OAAO,eAAeC,WAAWA,CAC7BC,QAAgD,EAChDC,QAAiC,EACjCC,OAAe,EACmB;EAClC,IAAMC,WAAW,GAAG,MAAMH,QAAQ,CAACI,SAAS,CACxC,CAACH,QAAQ,CAAC,EACVC,OACJ,CAAC;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AAG,MAAMd,eAAe,CAAC0J,OAAO,CAACyC,CAAC,CAAC;UAC5C,MAAM7M,WAAW,CAACqM,KAAK,CAACM,cAAc,CAAC,CAAC,CAAC;UACzC,OAAOnL,GAAG;QAEd,CAAC;QACD,MAAMiJ,KAAKA,CAAA,EAAG;UACV,MAAMzK,WAAW,CAACqM,KAAK,CAACK,eAAe,CAAC,CAAC,CAAC;UAC1C,IAAMlL,GAAG,GAAG,MAAMd,eAAe,CAAC+J,KAAK,CAAC,CAAC;UACzC,MAAMzK,WAAW,CAACqM,KAAK,CAACM,cAAc,CAAC,CAAC,CAAC;UACzC,OAAOnL,GAAG;QAEd,CAAC;QACD,MAAM8I,MAAMA,CAAA,EAAG;UACX,MAAMtK,WAAW,CAACqM,KAAK,CAACK,eAAe,CAAC,CAAC,CAAC;UAC1C,IAAMlL,GAAG,GAAG,MAAMd,eAAe,CAAC4J,MAAM,CAAC,CAAC;UAC1C,MAAMtK,WAAW,CAACqM,KAAK,CAACM,cAAc,CAAC,CAAC,CAAC;UACzC,OAAOnL,GAAG;QACd;MACJ,CAAC;IAGL;EACJ,CAAC;EACD,OAAO8K,UAAU;AACrB"} \ No newline at end of file +{"version":3,"file":"rx-storage-helper.js","names":["overwritable","newRxError","fillPrimaryKey","getPrimaryFieldOfPrimaryKey","PROMISE_RESOLVE_TRUE","RXDB_VERSION","RX_META_LWT_MINIMUM","appendToArray","createRevision","ensureNotFalsy","flatClone","getDefaultRevision","getDefaultRxDocumentMeta","lastOfArray","now","promiseWait","randomCouchString","filter","map","startWith","switchMap","prepareQuery","normalizeMangoQuery","INTERNAL_STORAGE_NAME","RX_DATABASE_LOCAL_DOCS_STORAGE_NAME","getSingleDocument","storageInstance","documentId","results","findDocumentsById","doc","undefined","writeSingle","instance","writeRow","context","writeResult","bulkWrite","error","length","ret","success","observeSingle","firstFindPromise","changeStream","pipe","evBulk","events","find","ev","Promise","resolve","documentData","v","stackCheckpoints","checkpoints","Object","assign","storageChangeEventToRxChangeEvent","isLocal","rxStorageChangeEvent","rxCollection","previousDocumentData","collectionName","name","operation","deepFreezeWhenDevMode","throwIfIsStorageWriteError","collection","writeData","status","id","writeError","data","categorizeBulkWriteRows","primaryPath","docsInDb","bulkWriteRows","onInsert","onUpdate","hasAttachments","schema","attachments","bulkInsertDocs","bulkUpdateDocs","errors","eventBulkId","eventBulk","checkpoint","startTime","endTime","eventBulkEvents","attachmentsAdd","attachmentsRemove","attachmentsUpdate","hasDocsInDb","size","newestRow","rowAmount","_loop","rowId","document","previous","docId","documentDeleted","_deleted","previousDeleted","documentInDb","get","attachmentError","insertedIsDeleted","entries","_attachments","forEach","attachmentId","attachmentData","isError","push","digest","stripAttachmentsDataFromRow","event","stripAttachmentsDataFromDocument","revInDb","_rev","err","updatedRow","keys","previousAttachmentData","newDigest","eventDocumentData","previousEventDocumentData","args","getAttachmentSize","attachmentBase64String","atob","attachmentWriteDataToNormalData","type","useDoc","flatCloneDocWithMeta","_meta","getWrappedStorageInstance","database","rxJsonSchema","primaryKey","transformDocumentDataFromRxDBToRxStorage","isDevMode","structuredClone","JSON","parse","stringify","metaFieldName","prototype","hasOwnProperty","call","dataBefore","dataAfter","lwt","token","originalStorageInstance","internals","databaseName","options","rows","toStorageWriteRows","row","lockedRun","then","useWriteResult","slice","reInsertErrors","reInserts","subResult","query","preparedQuery","count","ids","deleted","getAttachmentData","getChangedDocumentsSince","limit","cleanup","minDeletedTime","remove","storageInstances","delete","close","conflictResultionTasks","resolveConflictResultionTask","taskSolution","output","isEqual","add","ensureRxStorageInstanceParamsAreCorrect","params","keyCompression","hasEncryption","compression","jsonSchema","encrypted","getChangedDocumentsSinceQuery","sinceLwt","sinceId","selector","$or","$gt","$eq","$gte","sort","skip","result","documents","lastDoc","randomDelayStorage","input","retStorage","storage","rxdbVersion","createStorageInstance","delayTimeBefore","delayTimeAfter","writeQueue","a","b","response","c"],"sources":["../../src/rx-storage-helper.ts"],"sourcesContent":["/**\n * Helper functions for accessing the RxStorage instances.\n */\n\nimport { overwritable } from './overwritable.ts';\nimport { newRxError } from './rx-error.ts';\nimport {\n fillPrimaryKey,\n getPrimaryFieldOfPrimaryKey\n} from './rx-schema-helper.ts';\nimport type {\n BulkWriteRow,\n BulkWriteRowProcessed,\n CategorizeBulkWriteRowsOutput,\n EventBulk,\n RxAttachmentData,\n RxAttachmentWriteData,\n RxChangeEvent,\n RxCollection,\n RxDatabase,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorageWriteError,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n StringKeys,\n RxStorageWriteErrorConflict,\n RxStorageWriteErrorAttachment,\n RxStorage,\n RxStorageDefaultCheckpoint,\n FilledMangoQuery\n} from './types/index.d.ts';\nimport {\n PROMISE_RESOLVE_TRUE,\n RXDB_VERSION,\n RX_META_LWT_MINIMUM,\n appendToArray,\n createRevision,\n ensureNotFalsy,\n flatClone,\n getDefaultRevision,\n getDefaultRxDocumentMeta,\n lastOfArray,\n now,\n promiseWait,\n randomCouchString\n} from './plugins/utils/index.ts';\nimport { Observable, filter, map, startWith, switchMap } from 'rxjs';\nimport { prepareQuery } from './rx-query.ts';\nimport { normalizeMangoQuery } from './rx-query-helper.ts';\n\nexport const INTERNAL_STORAGE_NAME = '_rxdb_internal';\nexport const RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = 'rxdatabase_storage_local';\n\nexport async function getSingleDocument(\n storageInstance: RxStorageInstance,\n documentId: string\n): Promise | undefined> {\n const results = await storageInstance.findDocumentsById([documentId], false);\n const doc = results[0];\n if (doc) {\n return doc;\n } else {\n return undefined;\n }\n}\n\n/**\n * Writes a single document,\n * throws RxStorageBulkWriteError on failure\n */\nexport async function writeSingle(\n instance: RxStorageInstance,\n writeRow: BulkWriteRow,\n context: string\n): Promise> {\n const writeResult = await instance.bulkWrite(\n [writeRow],\n context\n );\n if (writeResult.error.length > 0) {\n const error = writeResult.error[0];\n throw error;\n } else {\n const ret = writeResult.success[0];\n return ret;\n }\n}\n\n/**\n * Observe the plain document data of a single document.\n * Do not forget to unsubscribe.\n */\nexport function observeSingle(\n storageInstance: RxStorageInstance,\n documentId: string\n): Observable> {\n const firstFindPromise = getSingleDocument(storageInstance, documentId);\n const ret = storageInstance\n .changeStream()\n .pipe(\n map(evBulk => evBulk.events.find(ev => ev.documentId === documentId)),\n filter(ev => !!ev),\n map(ev => Promise.resolve(ensureNotFalsy(ev).documentData)),\n startWith(firstFindPromise),\n switchMap(v => v),\n filter(v => !!v)\n ) as any;\n return ret;\n}\n\n\n/**\n * Checkpoints must be stackable over another.\n * This is required form some RxStorage implementations\n * like the sharding plugin, where a checkpoint only represents\n * the document state from some, but not all shards.\n */\nexport function stackCheckpoints(\n checkpoints: CheckpointType[]\n): CheckpointType {\n return Object.assign(\n {},\n ...checkpoints\n );\n}\n\nexport function storageChangeEventToRxChangeEvent(\n isLocal: boolean,\n rxStorageChangeEvent: RxStorageChangeEvent,\n rxCollection?: RxCollection,\n): RxChangeEvent {\n const documentData = rxStorageChangeEvent.documentData;\n const previousDocumentData = rxStorageChangeEvent.previousDocumentData;\n const ret: RxChangeEvent = {\n documentId: rxStorageChangeEvent.documentId,\n collectionName: rxCollection ? rxCollection.name : undefined,\n isLocal,\n operation: rxStorageChangeEvent.operation,\n documentData: overwritable.deepFreezeWhenDevMode(documentData as any),\n previousDocumentData: overwritable.deepFreezeWhenDevMode(previousDocumentData as any)\n };\n return ret;\n}\n\nexport function throwIfIsStorageWriteError(\n collection: RxCollection,\n documentId: string,\n writeData: RxDocumentWriteData | RxDocType,\n error: RxStorageWriteError | undefined\n) {\n if (error) {\n if (error.status === 409) {\n throw newRxError('CONFLICT', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else if (error.status === 422) {\n throw newRxError('VD2', {\n collection: collection.name,\n id: documentId,\n writeError: error,\n data: writeData\n });\n } else {\n throw error;\n }\n }\n}\n\n\n/**\n * Analyzes a list of BulkWriteRows and determines\n * which documents must be inserted, updated or deleted\n * and which events must be emitted and which documents cause a conflict\n * and must not be written.\n * Used as helper inside of some RxStorage implementations.\n * @hotPath The performance of this function is critical\n */\nexport function categorizeBulkWriteRows(\n storageInstance: RxStorageInstance,\n primaryPath: StringKeys,\n /**\n * Current state of the documents\n * inside of the storage. Used to determine\n * which writes cause conflicts.\n * This must be a Map for better performance.\n */\n docsInDb: Map[StringKeys] | string, RxDocumentData>,\n /**\n * The write rows that are passed to\n * RxStorageInstance().bulkWrite().\n */\n bulkWriteRows: BulkWriteRow[],\n context: string,\n /**\n * Used by some storages for better performance.\n * For example when get-by-id and insert/update can run in parallel.\n */\n onInsert?: (docData: RxDocumentData) => void,\n onUpdate?: (docData: RxDocumentData) => void\n): CategorizeBulkWriteRowsOutput {\n const hasAttachments = !!storageInstance.schema.attachments;\n const bulkInsertDocs: BulkWriteRowProcessed[] = [];\n const bulkUpdateDocs: BulkWriteRowProcessed[] = [];\n const errors: RxStorageWriteError[] = [];\n const eventBulkId = randomCouchString(10);\n const eventBulk: EventBulk>, any> = {\n id: eventBulkId,\n events: [],\n checkpoint: null,\n context,\n startTime: now(),\n endTime: 0\n };\n const eventBulkEvents = eventBulk.events;\n\n const attachmentsAdd: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n digest: string;\n }[] = [];\n const attachmentsRemove: {\n documentId: string;\n attachmentId: string;\n digest: string;\n }[] = [];\n const attachmentsUpdate: {\n documentId: string;\n attachmentId: string;\n attachmentData: RxAttachmentWriteData;\n digest: string;\n }[] = [];\n\n const hasDocsInDb = docsInDb.size > 0;\n let newestRow: BulkWriteRowProcessed | undefined;\n\n /**\n * @performance is really important in this loop!\n */\n const rowAmount = bulkWriteRows.length;\n for (let rowId = 0; rowId < rowAmount; rowId++) {\n const writeRow = bulkWriteRows[rowId];\n\n // use these variables to have less property accesses\n const document = writeRow.document;\n const previous = writeRow.previous;\n const docId = document[primaryPath] as string;\n const documentDeleted = document._deleted;\n const previousDeleted = previous && previous._deleted;\n\n let documentInDb: RxDocumentData | undefined = undefined as any;\n if (hasDocsInDb) {\n documentInDb = docsInDb.get(docId);\n }\n let attachmentError: RxStorageWriteErrorAttachment | undefined;\n\n if (!documentInDb) {\n /**\n * It is possible to insert already deleted documents,\n * this can happen on replication.\n */\n const insertedIsDeleted = documentDeleted ? true : false;\n if (hasAttachments) {\n Object\n .entries(document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n if (\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: docId,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n errors.push(attachmentError);\n } else {\n attachmentsAdd.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as any,\n digest: attachmentData.digest\n });\n }\n });\n }\n if (!attachmentError) {\n if (hasAttachments) {\n bulkInsertDocs.push(stripAttachmentsDataFromRow(writeRow));\n if (onInsert) {\n onInsert(document);\n }\n } else {\n bulkInsertDocs.push(writeRow as any);\n if (onInsert) {\n onInsert(document);\n }\n }\n\n newestRow = writeRow as any;\n }\n\n if (!insertedIsDeleted) {\n const event = {\n documentId: docId,\n operation: 'INSERT' as const,\n documentData: hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any,\n previousDocumentData: hasAttachments && previous ? stripAttachmentsDataFromDocument(previous) : previous as any\n };\n eventBulkEvents.push(event);\n }\n } else {\n // update existing document\n const revInDb: string = documentInDb._rev;\n\n /**\n * Check for conflict\n */\n if (\n (\n !previous\n ) ||\n (\n !!previous &&\n revInDb !== previous._rev\n )\n ) {\n // is conflict error\n const err: RxStorageWriteError = {\n isError: true,\n status: 409,\n documentId: docId,\n writeRow: writeRow,\n documentInDb\n };\n errors.push(err);\n continue;\n }\n\n // handle attachments data\n\n const updatedRow: BulkWriteRowProcessed = hasAttachments ? stripAttachmentsDataFromRow(writeRow) : writeRow as any;\n if (hasAttachments) {\n if (documentDeleted) {\n /**\n * Deleted documents must have cleared all their attachments.\n */\n if (previous) {\n Object\n .keys(previous._attachments)\n .forEach(attachmentId => {\n attachmentsRemove.push({\n documentId: docId,\n attachmentId,\n digest: ensureNotFalsy(previous)._attachments[attachmentId].digest\n });\n });\n }\n } else {\n // first check for errors\n Object\n .entries(document._attachments)\n .find(([attachmentId, attachmentData]) => {\n const previousAttachmentData = previous ? previous._attachments[attachmentId] : undefined;\n if (\n !previousAttachmentData &&\n !(attachmentData as RxAttachmentWriteData).data\n ) {\n attachmentError = {\n documentId: docId,\n documentInDb: documentInDb as any,\n isError: true,\n status: 510,\n writeRow,\n attachmentId\n };\n }\n return true;\n });\n if (!attachmentError) {\n Object\n .entries(document._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n const previousAttachmentData = previous ? previous._attachments[attachmentId] : undefined;\n if (!previousAttachmentData) {\n attachmentsAdd.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as any,\n digest: attachmentData.digest\n });\n } else {\n const newDigest = updatedRow.document._attachments[attachmentId].digest;\n if (\n (attachmentData as RxAttachmentWriteData).data &&\n /**\n * Performance shortcut,\n * do not update the attachment data if it did not change.\n */\n previousAttachmentData.digest !== newDigest\n ) {\n attachmentsUpdate.push({\n documentId: docId,\n attachmentId,\n attachmentData: attachmentData as RxAttachmentWriteData,\n digest: attachmentData.digest\n });\n }\n }\n });\n }\n }\n }\n\n if (attachmentError) {\n errors.push(attachmentError);\n } else {\n if (hasAttachments) {\n bulkUpdateDocs.push(stripAttachmentsDataFromRow(updatedRow));\n if (onUpdate) {\n onUpdate(document);\n }\n } else {\n bulkUpdateDocs.push(updatedRow);\n if (onUpdate) {\n onUpdate(document);\n }\n }\n newestRow = updatedRow as any;\n }\n\n let eventDocumentData: RxDocumentData | undefined = null as any;\n let previousEventDocumentData: RxDocumentData | undefined = null as any;\n let operation: 'INSERT' | 'UPDATE' | 'DELETE' = null as any;\n\n if (previousDeleted && !documentDeleted) {\n operation = 'INSERT';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any;\n } else if (previous && !previousDeleted && !documentDeleted) {\n operation = 'UPDATE';\n eventDocumentData = hasAttachments ? stripAttachmentsDataFromDocument(document) : document as any;\n previousEventDocumentData = previous;\n } else if (documentDeleted) {\n operation = 'DELETE';\n eventDocumentData = ensureNotFalsy(document) as any;\n previousEventDocumentData = previous;\n } else {\n throw newRxError('SNH', { args: { writeRow } });\n }\n\n const event = {\n documentId: docId,\n documentData: eventDocumentData as RxDocumentData,\n previousDocumentData: previousEventDocumentData,\n operation: operation\n };\n eventBulkEvents.push(event);\n }\n }\n\n return {\n bulkInsertDocs,\n bulkUpdateDocs,\n newestRow,\n errors,\n eventBulk,\n attachmentsAdd,\n attachmentsRemove,\n attachmentsUpdate\n };\n}\n\nexport function stripAttachmentsDataFromRow(writeRow: BulkWriteRow): BulkWriteRowProcessed {\n return {\n previous: writeRow.previous,\n document: stripAttachmentsDataFromDocument(writeRow.document)\n };\n}\n\nexport function getAttachmentSize(\n attachmentBase64String: string\n): number {\n return atob(attachmentBase64String).length;\n}\n\n/**\n * Used in custom RxStorage implementations.\n */\nexport function attachmentWriteDataToNormalData(writeData: RxAttachmentData | RxAttachmentWriteData): RxAttachmentData {\n const data = (writeData as RxAttachmentWriteData).data;\n if (!data) {\n return writeData as any;\n }\n const ret: RxAttachmentData = {\n length: getAttachmentSize(data),\n digest: writeData.digest,\n type: writeData.type\n };\n return ret;\n}\n\nexport function stripAttachmentsDataFromDocument(doc: RxDocumentWriteData): RxDocumentData {\n\n if (!doc._attachments || Object.keys(doc._attachments).length === 0) {\n return doc;\n }\n\n const useDoc: RxDocumentData = flatClone(doc) as any;\n useDoc._attachments = {};\n Object\n .entries(doc._attachments)\n .forEach(([attachmentId, attachmentData]) => {\n useDoc._attachments[attachmentId] = attachmentWriteDataToNormalData(attachmentData);\n });\n return useDoc;\n}\n\n/**\n * Flat clone the document data\n * and also the _meta field.\n * Used many times when we want to change the meta\n * during replication etc.\n */\nexport function flatCloneDocWithMeta(\n doc: RxDocumentData\n): RxDocumentData {\n const ret = flatClone(doc);\n ret._meta = flatClone(doc._meta);\n return ret;\n}\n\nexport type WrappedRxStorageInstance = RxStorageInstance & {\n originalStorageInstance: RxStorageInstance;\n};\n\n/**\n * Wraps the normal storageInstance of a RxCollection\n * to ensure that all access is properly using the hooks\n * and other data transformations and also ensure that database.lockedRun()\n * is used properly.\n */\nexport function getWrappedStorageInstance<\n RxDocType,\n Internals,\n InstanceCreationOptions,\n CheckpointType\n>(\n database: RxDatabase<{}, Internals, InstanceCreationOptions>,\n storageInstance: RxStorageInstance,\n /**\n * The original RxJsonSchema\n * before it was mutated by hooks.\n */\n rxJsonSchema: RxJsonSchema>\n): WrappedRxStorageInstance {\n overwritable.deepFreezeWhenDevMode(rxJsonSchema);\n const primaryPath = getPrimaryFieldOfPrimaryKey(rxJsonSchema.primaryKey);\n\n function transformDocumentDataFromRxDBToRxStorage(\n writeRow: BulkWriteRow\n ) {\n let data = flatClone(writeRow.document);\n data._meta = flatClone(data._meta);\n\n /**\n * Do some checks in dev-mode\n * that would be too performance expensive\n * in production.\n */\n if (overwritable.isDevMode()) {\n // ensure that the primary key has not been changed\n data = fillPrimaryKey(\n primaryPath,\n rxJsonSchema,\n data as any\n );\n\n\n /**\n * Ensure it can be structured cloned\n */\n try {\n /**\n * Notice that structuredClone() is not available\n * in ReactNative, so we test for JSON.stringify() instead\n * @link https://github.com/pubkey/rxdb/issues/5046#issuecomment-1827374498\n */\n if (typeof structuredClone === 'function') {\n structuredClone(writeRow);\n } else {\n JSON.parse(JSON.stringify(writeRow));\n }\n } catch (err) {\n throw newRxError('DOC24', {\n collection: storageInstance.collectionName,\n document: writeRow.document\n });\n }\n\n /**\n * Ensure that the new revision is higher\n * then the previous one\n */\n if (writeRow.previous) {\n // TODO run this in the dev-mode plugin\n // const prev = parseRevision(writeRow.previous._rev);\n // const current = parseRevision(writeRow.document._rev);\n // if (current.height <= prev.height) {\n // throw newRxError('SNH', {\n // dataBefore: writeRow.previous,\n // dataAfter: writeRow.document,\n // args: {\n // prev,\n // current\n // }\n // });\n // }\n }\n\n /**\n * Ensure that _meta fields have been merged\n * and not replaced.\n * This is important so that when one plugin A\n * sets a _meta field and another plugin B does a write\n * to the document, it must be ensured that the\n * field of plugin A was not removed.\n */\n if (writeRow.previous) {\n Object.keys(writeRow.previous._meta)\n .forEach(metaFieldName => {\n if (!Object.prototype.hasOwnProperty.call(writeRow.document._meta, metaFieldName)) {\n throw newRxError('SNH', {\n dataBefore: writeRow.previous,\n dataAfter: writeRow.document\n });\n }\n });\n }\n }\n data._meta.lwt = now();\n\n /**\n * Yes we really want to set the revision here.\n * If you make a plugin that relies on having its own revision\n * stored into the storage, use this.originalStorageInstance.bulkWrite() instead.\n */\n data._rev = createRevision(\n database.token,\n writeRow.previous\n );\n\n return {\n document: data,\n previous: writeRow.previous\n };\n }\n\n const ret: WrappedRxStorageInstance = {\n originalStorageInstance: storageInstance,\n schema: storageInstance.schema,\n internals: storageInstance.internals,\n collectionName: storageInstance.collectionName,\n databaseName: storageInstance.databaseName,\n options: storageInstance.options,\n bulkWrite(\n rows: BulkWriteRow[],\n context: string\n ) {\n const toStorageWriteRows: BulkWriteRow[] = rows\n .map(row => transformDocumentDataFromRxDBToRxStorage(row));\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n toStorageWriteRows,\n context\n )\n )\n /**\n * The RxStorageInstance MUST NOT allow to insert already _deleted documents,\n * without sending the previous document version.\n * But for better developer experience, RxDB does allow to re-insert deleted documents.\n * We do this by automatically fixing the conflict errors for that case\n * by running another bulkWrite() and merging the results.\n * @link https://github.com/pubkey/rxdb/pull/3839\n */\n .then(writeResult => {\n const useWriteResult: typeof writeResult = {\n error: [],\n success: writeResult.success.slice(0)\n };\n const reInsertErrors: RxStorageWriteErrorConflict[] =\n writeResult.error\n .filter((error) => {\n if (\n error.status === 409 &&\n !error.writeRow.previous &&\n !error.writeRow.document._deleted &&\n ensureNotFalsy(error.documentInDb)._deleted\n ) {\n return true;\n }\n useWriteResult.error.push(error);\n return false;\n }) as any;\n if (reInsertErrors.length > 0) {\n const reInserts: BulkWriteRow[] = reInsertErrors\n .map((error) => {\n return {\n previous: error.documentInDb,\n document: Object.assign(\n {},\n error.writeRow.document,\n {\n _rev: createRevision(\n database.token,\n error.documentInDb\n )\n }\n )\n };\n });\n\n return database.lockedRun(\n () => storageInstance.bulkWrite(\n reInserts,\n context\n )\n ).then(subResult => {\n appendToArray(useWriteResult.error, subResult.error);\n appendToArray(useWriteResult.success, subResult.success);\n return useWriteResult;\n });\n }\n\n return writeResult;\n });\n },\n query(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.query(preparedQuery)\n );\n },\n count(preparedQuery) {\n return database.lockedRun(\n () => storageInstance.count(preparedQuery)\n );\n },\n findDocumentsById(ids, deleted) {\n return database.lockedRun(\n () => storageInstance.findDocumentsById(ids, deleted)\n );\n },\n getAttachmentData(\n documentId: string,\n attachmentId: string,\n digest: string\n ) {\n return database.lockedRun(\n () => storageInstance.getAttachmentData(documentId, attachmentId, digest)\n );\n },\n getChangedDocumentsSince: !storageInstance.getChangedDocumentsSince ? undefined : (limit: number, checkpoint?: any) => {\n return database.lockedRun(\n () => ((storageInstance as any).getChangedDocumentsSince)(ensureNotFalsy(limit), checkpoint)\n );\n },\n cleanup(minDeletedTime: number) {\n return database.lockedRun(\n () => storageInstance.cleanup(minDeletedTime)\n );\n },\n remove() {\n database.storageInstances.delete(ret);\n return database.lockedRun(\n () => storageInstance.remove()\n );\n },\n close() {\n database.storageInstances.delete(ret);\n return database.lockedRun(\n () => storageInstance.close()\n );\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(taskSolution) {\n if (taskSolution.output.isEqual) {\n return storageInstance.resolveConflictResultionTask(taskSolution);\n }\n\n const doc = Object.assign(\n {},\n taskSolution.output.documentData,\n {\n _meta: getDefaultRxDocumentMeta(),\n _rev: getDefaultRevision(),\n _attachments: {}\n }\n );\n\n const documentData = flatClone(doc);\n delete (documentData as any)._meta;\n delete (documentData as any)._rev;\n delete (documentData as any)._attachments;\n\n return storageInstance.resolveConflictResultionTask({\n id: taskSolution.id,\n output: {\n isEqual: false,\n documentData\n }\n });\n }\n };\n\n database.storageInstances.add(ret);\n return ret;\n}\n\n/**\n * Each RxStorage implementation should\n * run this method at the first step of createStorageInstance()\n * to ensure that the configuration is correct.\n */\nexport function ensureRxStorageInstanceParamsAreCorrect(\n params: RxStorageInstanceCreationParams\n) {\n if (params.schema.keyCompression) {\n throw newRxError('UT5', { args: { params } });\n }\n if (hasEncryption(params.schema)) {\n throw newRxError('UT6', { args: { params } });\n }\n if (\n params.schema.attachments &&\n params.schema.attachments.compression\n ) {\n throw newRxError('UT7', { args: { params } });\n }\n}\n\nexport function hasEncryption(jsonSchema: RxJsonSchema): boolean {\n if (\n (!!jsonSchema.encrypted && jsonSchema.encrypted.length > 0) ||\n (jsonSchema.attachments && jsonSchema.attachments.encrypted)\n ) {\n return true;\n } else {\n return false;\n }\n}\n\nexport function getChangedDocumentsSinceQuery(\n storageInstance: RxStorageInstance,\n limit: number,\n checkpoint?: CheckpointType\n): FilledMangoQuery {\n const primaryPath = getPrimaryFieldOfPrimaryKey(storageInstance.schema.primaryKey);\n const sinceLwt = checkpoint ? (checkpoint as unknown as RxStorageDefaultCheckpoint).lwt : RX_META_LWT_MINIMUM;\n const sinceId = checkpoint ? (checkpoint as unknown as RxStorageDefaultCheckpoint).id : '';\n return normalizeMangoQuery(storageInstance.schema, {\n selector: {\n $or: [\n {\n '_meta.lwt': {\n $gt: sinceLwt\n }\n },\n {\n '_meta.lwt': {\n $eq: sinceLwt\n },\n [primaryPath]: {\n $gt: checkpoint ? sinceId : ''\n }\n }\n ],\n // add this hint for better index usage\n '_meta.lwt': {\n $gte: sinceLwt\n }\n } as any,\n sort: [\n { '_meta.lwt': 'asc' },\n { [primaryPath]: 'asc' }\n ] as any,\n skip: 0,\n limit,\n /**\n * DO NOT SET A SPECIFIC INDEX HERE!\n * The query might be modified by some plugin\n * before sending it to the storage.\n * We can be sure that in the end the query planner\n * will find the best index.\n */\n // index: ['_meta.lwt', primaryPath]\n });\n}\n\nexport async function getChangedDocumentsSince(\n storageInstance: RxStorageInstance,\n limit: number,\n checkpoint?: CheckpointType\n): Promise<{\n documents: RxDocumentData[];\n /**\n * The checkpoint contains data so that another\n * call to getChangedDocumentsSince() will continue\n * from exactly the last document that was returned before.\n */\n checkpoint: CheckpointType;\n}> {\n if (storageInstance.getChangedDocumentsSince) {\n return storageInstance.getChangedDocumentsSince(limit, checkpoint);\n }\n\n const primaryPath = getPrimaryFieldOfPrimaryKey(storageInstance.schema.primaryKey);\n const query = prepareQuery>(\n storageInstance.schema,\n getChangedDocumentsSinceQuery(\n storageInstance,\n limit,\n checkpoint\n )\n );\n\n const result = await storageInstance.query(query);\n const documents = result.documents;\n const lastDoc = lastOfArray(documents);\n\n return {\n documents: documents,\n checkpoint: lastDoc ? {\n id: (lastDoc as any)[primaryPath],\n lwt: lastDoc._meta.lwt\n } as any : checkpoint ? checkpoint : {\n id: '',\n lwt: 0\n }\n };\n}\n\n\n/**\n * Wraps the storage and simluates\n * delays. Mostly used in tests.\n */\nexport function randomDelayStorage(\n input: {\n storage: RxStorage;\n delayTimeBefore: () => number;\n delayTimeAfter: () => number;\n }\n): RxStorage {\n\n const retStorage: RxStorage = {\n name: 'random-delay-' + input.storage.name,\n rxdbVersion: RXDB_VERSION,\n async createStorageInstance(params) {\n await promiseWait(input.delayTimeBefore());\n const storageInstance = await input.storage.createStorageInstance(params);\n await promiseWait(input.delayTimeAfter());\n\n // write still must be processed in order\n let writeQueue: Promise = PROMISE_RESOLVE_TRUE;\n\n return {\n databaseName: storageInstance.databaseName,\n internals: storageInstance.internals,\n options: storageInstance.options,\n schema: storageInstance.schema,\n collectionName: storageInstance.collectionName,\n async bulkWrite(a, b) {\n writeQueue = writeQueue.then(async () => {\n await promiseWait(input.delayTimeBefore());\n const response = await storageInstance.bulkWrite(a, b);\n await promiseWait(input.delayTimeAfter());\n return response;\n });\n const ret = await writeQueue;\n return ret;\n },\n async findDocumentsById(a, b) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.findDocumentsById(a, b);\n await promiseWait(input.delayTimeAfter());\n return ret;\n },\n async query(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.query(a);\n return ret;\n },\n async count(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.count(a);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async getAttachmentData(a, b, c) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.getAttachmentData(a, b, c);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n getChangedDocumentsSince: !storageInstance.getChangedDocumentsSince ? undefined : async (a, b) => {\n await promiseWait(input.delayTimeBefore());\n const ret = await ensureNotFalsy(storageInstance.getChangedDocumentsSince)(a, b);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n changeStream() {\n return storageInstance.changeStream();\n },\n conflictResultionTasks() {\n return storageInstance.conflictResultionTasks();\n },\n resolveConflictResultionTask(a) {\n return storageInstance.resolveConflictResultionTask(a);\n },\n async cleanup(a) {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.cleanup(a);\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async close() {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.close();\n await promiseWait(input.delayTimeAfter());\n return ret;\n\n },\n async remove() {\n await promiseWait(input.delayTimeBefore());\n const ret = await storageInstance.remove();\n await promiseWait(input.delayTimeAfter());\n return ret;\n },\n };\n\n\n }\n };\n return retStorage;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,YAAY,QAAQ,mBAAmB;AAChD,SAASC,UAAU,QAAQ,eAAe;AAC1C,SACIC,cAAc,EACdC,2BAA2B,QACxB,uBAAuB;AAyB9B,SACIC,oBAAoB,EACpBC,YAAY,EACZC,mBAAmB,EACnBC,aAAa,EACbC,cAAc,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CAAC;UACzC,OAAOnL,GAAG;QAEd,CAAC;QACD,MAAMiJ,KAAKA,CAAA,EAAG;UACV,MAAM1K,WAAW,CAACsM,KAAK,CAACK,eAAe,CAAC,CAAC,CAAC;UAC1C,IAAMlL,GAAG,GAAG,MAAMd,eAAe,CAAC+J,KAAK,CAAC,CAAC;UACzC,MAAM1K,WAAW,CAACsM,KAAK,CAACM,cAAc,CAAC,CAAC,CAAC;UACzC,OAAOnL,GAAG;QAEd,CAAC;QACD,MAAM8I,MAAMA,CAAA,EAAG;UACX,MAAMvK,WAAW,CAACsM,KAAK,CAACK,eAAe,CAAC,CAAC,CAAC;UAC1C,IAAMlL,GAAG,GAAG,MAAMd,eAAe,CAAC4J,MAAM,CAAC,CAAC;UAC1C,MAAMvK,WAAW,CAACsM,KAAK,CAACM,cAAc,CAAC,CAAC,CAAC;UACzC,OAAOnL,GAAG;QACd;MACJ,CAAC;IAGL;EACJ,CAAC;EACD,OAAO8K,UAAU;AACrB"} \ No newline at end of file diff --git a/dist/esm/types/rx-error.d.js.map b/dist/esm/types/rx-error.d.js.map index 8a729cb21c4..4656df08485 100644 --- a/dist/esm/types/rx-error.d.js.map +++ b/dist/esm/types/rx-error.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-error.d.js","names":[],"sources":["../../../src/types/rx-error.d.ts"],"sourcesContent":["import type { RxJsonSchema } from './rx-schema.d.ts';\nimport {\n RxSchema\n} from '../rx-schema.ts';\nimport type { RxPlugin } from './rx-plugin.d.ts';\nimport { ERROR_MESSAGES } from '../plugins/dev-mode/error-messages.ts';\nimport type { RxReplicationWriteToMasterRow } from './replication-protocol.d.ts';\nimport type { BulkWriteRow, RxDocumentData } from './rx-storage.d.ts';\n\ntype KeyOf = Extract;\nexport type RxErrorKey = KeyOf;\n\nexport type {\n RxError,\n RxTypeError\n} from '../rx-error.ts';\n\n/**\n * this lists all possible parameters\n */\nexport interface RxErrorParameters {\n readonly error?: PlainJsonError;\n readonly errors?: PlainJsonError[];\n readonly writeError?: RxStorageWriteError;\n readonly schemaPath?: string;\n readonly objPath?: string;\n readonly rootPath?: string;\n readonly childpath?: string;\n readonly obj?: any;\n readonly document?: any;\n readonly schema?: Readonly | RxSchema>;\n readonly schemaObj?: any;\n readonly pluginKey?: string;\n readonly originalDoc?: Readonly;\n readonly finalDoc?: Readonly;\n readonly regex?: string;\n readonly fieldName?: string;\n readonly id?: string;\n readonly data?: any;\n readonly missingCollections?: string[];\n readonly primaryPath?: string;\n readonly primary?: string;\n readonly primaryKey?: string;\n readonly have?: any;\n readonly should?: any;\n readonly name?: string;\n readonly adapter?: any;\n readonly link?: string;\n readonly path?: string;\n readonly value?: any;\n readonly givenName?: string;\n readonly fromVersion?: number;\n readonly toVersion?: number;\n readonly version?: number;\n readonly args?: any;\n readonly opts?: any;\n readonly dataBefore?: any;\n readonly dataAfter?: any;\n readonly pull?: boolean;\n readonly push?: boolean;\n readonly key?: string;\n readonly queryObj?: any;\n readonly query?: any;\n readonly op?: string;\n readonly skip?: any;\n readonly limit?: any;\n readonly passwordHash?: string;\n readonly existingPasswordHash?: string;\n readonly password?: string | any;\n readonly minPassLength?: number;\n readonly own?: any;\n readonly source?: any;\n readonly method?: any;\n readonly field?: string;\n readonly ref?: string;\n readonly funName?: string;\n readonly functionName?: string;\n readonly schemaHash?: string;\n readonly previousSchema?: Readonly>;\n readonly previousSchemaHash?: string;\n readonly type?: string;\n readonly when?: string;\n readonly parallel?: boolean;\n readonly collection?: any;\n readonly database?: any;\n readonly indexes?: Array | Readonly>;\n readonly index?: string | string[] | readonly string[];\n readonly plugin?: RxPlugin | any;\n readonly plugins?: Set;\n\n // used in the replication plugin\n\n /**\n * The checkpoint of the response from the last successful\n * pull by the client.\n * Null if there was no pull operation before\n * so that there is no last pulled checkpoint.\n */\n readonly checkpoint?: any;\n /**\n * The documents that failed to be pushed.\n * Typed as 'any' because they might be modified by the push modifier.\n */\n readonly pushRows?: RxReplicationWriteToMasterRow[];\n readonly direction?: 'pull' | 'push';\n\n}\n\n/**\n * Error-Items which are created by the jsonschema-validator\n */\nexport type RxValidationError = {\n readonly field: string;\n readonly message: string;\n};\n\n/**\n * Use to have a transferable error object\n * in plain json instead of a JavaScript Error instance.\n */\nexport type PlainJsonError = {\n name: string;\n message: string;\n rxdb?: true;\n code?: RxErrorKey;\n parameters?: RxErrorParameters;\n stack?: string;\n};\n\n\n\n\n\n/**\n * Error that can happen per document when\n * RxStorage.bulkWrite() is called\n */\nexport type RxStorageWriteErrorBase = {\n\n status: number\n | 409 // conflict\n | 422 // schema validation error\n | 510 // attachment data missing\n ;\n\n /**\n * set this property to make it easy\n * to detect if the object is a RxStorageBulkWriteError\n */\n isError: true;\n\n // primary key of the document\n documentId: string;\n\n // the original document data that should have been written.\n writeRow: BulkWriteRow;\n};\n\nexport type RxStorageWriteErrorConflict = RxStorageWriteErrorBase & {\n status: 409;\n /**\n * A conflict error state must contain the\n * document state in the database.\n * This ensures that we can continue resolving a conflict\n * without having to pull the document out of the db first.\n * Is not set if the error happens on an insert.\n */\n documentInDb: RxDocumentData;\n};\n\nexport type RxStorageWriteErrorValidation = RxStorageWriteErrorBase & {\n status: 422;\n /**\n * Other properties that give\n * information about the error,\n * for example a schema validation error\n * might contain the exact error from the validator here.\n * Must be plain JSON!\n */\n validationErrors: RxValidationError[];\n};\n\nexport type RxStorageWriteErrorAttachment = RxStorageWriteErrorBase & {\n status: 510;\n attachmentId: string;\n documentInDb?: RxDocumentData;\n};\n\n\nexport type RxStorageWriteError =\n RxStorageWriteErrorConflict |\n RxStorageWriteErrorValidation |\n RxStorageWriteErrorAttachment;\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-error.d.js","names":[],"sources":["../../../src/types/rx-error.d.ts"],"sourcesContent":["import type { RxJsonSchema } from './rx-schema.d.ts';\nimport {\n RxSchema\n} from '../rx-schema.ts';\nimport type { RxPlugin } from './rx-plugin.d.ts';\nimport { ERROR_MESSAGES } from '../plugins/dev-mode/error-messages.ts';\nimport type { RxReplicationWriteToMasterRow } from './replication-protocol.d.ts';\nimport type { BulkWriteRow, RxDocumentData } from './rx-storage.d.ts';\n\ntype KeyOf = Extract;\nexport type RxErrorKey = KeyOf;\n\nexport type {\n RxError,\n RxTypeError\n} from '../rx-error.ts';\n\n/**\n * this lists all possible parameters\n */\nexport interface RxErrorParameters {\n readonly error?: PlainJsonError;\n readonly errors?: PlainJsonError[];\n readonly writeError?: RxStorageWriteError;\n readonly schemaPath?: string;\n readonly objPath?: string;\n readonly rootPath?: string;\n readonly childpath?: string;\n readonly obj?: any;\n readonly document?: any;\n readonly schema?: Readonly | RxSchema>;\n readonly schemaObj?: any;\n readonly pluginKey?: string;\n readonly originalDoc?: Readonly;\n readonly finalDoc?: Readonly;\n readonly regex?: string;\n readonly fieldName?: string;\n readonly id?: string;\n readonly data?: any;\n readonly missingCollections?: string[];\n readonly primaryPath?: string;\n readonly primary?: string;\n readonly primaryKey?: string;\n readonly have?: any;\n readonly should?: any;\n readonly name?: string;\n readonly adapter?: any;\n readonly link?: string;\n readonly path?: string;\n readonly value?: any;\n readonly givenName?: string;\n readonly fromVersion?: number;\n readonly toVersion?: number;\n readonly version?: number;\n readonly args?: any;\n readonly opts?: any;\n readonly dataBefore?: any;\n readonly dataAfter?: any;\n readonly pull?: boolean;\n readonly push?: boolean;\n readonly url?: string;\n readonly key?: string;\n readonly queryObj?: any;\n readonly query?: any;\n readonly op?: string;\n readonly skip?: any;\n readonly limit?: any;\n readonly passwordHash?: string;\n readonly existingPasswordHash?: string;\n readonly password?: string | any;\n readonly minPassLength?: number;\n readonly own?: any;\n readonly source?: any;\n readonly method?: any;\n readonly field?: string;\n readonly ref?: string;\n readonly funName?: string;\n readonly functionName?: string;\n readonly schemaHash?: string;\n readonly previousSchema?: Readonly>;\n readonly previousSchemaHash?: string;\n readonly type?: string;\n readonly when?: string;\n readonly parallel?: boolean;\n readonly collection?: any;\n readonly database?: any;\n readonly indexes?: Array | Readonly>;\n readonly index?: string | string[] | readonly string[];\n readonly plugin?: RxPlugin | any;\n readonly plugins?: Set;\n\n // used in the replication plugin\n\n /**\n * The checkpoint of the response from the last successful\n * pull by the client.\n * Null if there was no pull operation before\n * so that there is no last pulled checkpoint.\n */\n readonly checkpoint?: any;\n /**\n * The documents that failed to be pushed.\n * Typed as 'any' because they might be modified by the push modifier.\n */\n readonly pushRows?: RxReplicationWriteToMasterRow[];\n readonly direction?: 'pull' | 'push';\n\n}\n\n/**\n * Error-Items which are created by the jsonschema-validator\n */\nexport type RxValidationError = {\n readonly field: string;\n readonly message: string;\n};\n\n/**\n * Use to have a transferable error object\n * in plain json instead of a JavaScript Error instance.\n */\nexport type PlainJsonError = {\n name: string;\n message: string;\n rxdb?: true;\n code?: RxErrorKey;\n parameters?: RxErrorParameters;\n stack?: string;\n};\n\n\n\n\n\n/**\n * Error that can happen per document when\n * RxStorage.bulkWrite() is called\n */\nexport type RxStorageWriteErrorBase = {\n\n status: number\n | 409 // conflict\n | 422 // schema validation error\n | 510 // attachment data missing\n ;\n\n /**\n * set this property to make it easy\n * to detect if the object is a RxStorageBulkWriteError\n */\n isError: true;\n\n // primary key of the document\n documentId: string;\n\n // the original document data that should have been written.\n writeRow: BulkWriteRow;\n};\n\nexport type RxStorageWriteErrorConflict = RxStorageWriteErrorBase & {\n status: 409;\n /**\n * A conflict error state must contain the\n * document state in the database.\n * This ensures that we can continue resolving a conflict\n * without having to pull the document out of the db first.\n * Is not set if the error happens on an insert.\n */\n documentInDb: RxDocumentData;\n};\n\nexport type RxStorageWriteErrorValidation = RxStorageWriteErrorBase & {\n status: 422;\n /**\n * Other properties that give\n * information about the error,\n * for example a schema validation error\n * might contain the exact error from the validator here.\n * Must be plain JSON!\n */\n validationErrors: RxValidationError[];\n};\n\nexport type RxStorageWriteErrorAttachment = RxStorageWriteErrorBase & {\n status: 510;\n attachmentId: string;\n documentInDb?: RxDocumentData;\n};\n\n\nexport type RxStorageWriteError =\n RxStorageWriteErrorConflict |\n RxStorageWriteErrorValidation |\n RxStorageWriteErrorAttachment;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/esm/types/rx-schema.d.js.map b/dist/esm/types/rx-schema.d.js.map index 0373625cb7e..6741008bf55 100644 --- a/dist/esm/types/rx-schema.d.js.map +++ b/dist/esm/types/rx-schema.d.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-schema.d.js","names":[],"sources":["../../../src/types/rx-schema.d.ts"],"sourcesContent":["import { AsTyped } from 'as-typed';\nimport type { CRDTSchemaOptions } from './plugins/crdt.d.ts';\nimport type { StringKeys } from './util.d.ts';\n\n/**\n * @link https://github.com/types/lib-json-schema/blob/master/v4/index.d.ts\n */\nexport type JsonSchemaTypes = 'array' | 'boolean' | 'integer' | 'number' | 'null' | 'object' | 'string' | (string & {});\n\nexport type CompositePrimaryKey = {\n /**\n * The top level field of the document that will be used\n * to store the composite key as string.\n */\n key: StringKeys;\n\n /**\n * The fields of the composite key,\n * the fields must be required and final\n * and have the type number, int, or string.\n */\n fields: (StringKeys | string)[] | readonly (StringKeys | string)[];\n /**\n * The separator which is used to concat the\n * primary fields values.\n * Choose a character as separator that is known\n * to never appear inside of the primary fields values.\n * I recommend to use the pipe char '|'.\n */\n separator: string;\n};\n\nexport type PrimaryKey = StringKeys | CompositePrimaryKey;\n\nexport type JsonSchema = {\n allOf?: JsonSchema[] | readonly JsonSchema[];\n anyOf?: JsonSchema[] | readonly JsonSchema[];\n oneOf?: JsonSchema[] | readonly JsonSchema[];\n additionalItems?: boolean | JsonSchema;\n additionalProperties?: boolean | JsonSchema;\n type?: JsonSchemaTypes | JsonSchemaTypes[] | readonly JsonSchemaTypes[];\n description?: string;\n dependencies?: {\n [key: string]: JsonSchema | string[] | readonly string[];\n };\n exclusiveMinimum?: boolean;\n exclusiveMaximum?: boolean;\n items?: JsonSchema | JsonSchema[] | readonly JsonSchema[];\n multipleOf?: number;\n maxProperties?: number;\n maximum?: number;\n minimum?: number;\n maxLength?: number;\n minLength?: number;\n maxItems?: number;\n minItems?: number;\n minProperties?: number;\n pattern?: string;\n patternProperties?: {\n [key: string]: JsonSchema;\n };\n properties?: {\n [key in StringKeys]: JsonSchema;\n };\n required?: string[] | readonly string[];\n uniqueItems?: boolean;\n enum?: any[] | readonly any[];\n not?: JsonSchema;\n definitions?: {\n [key: string]: JsonSchema;\n };\n format?: 'date-time' | 'email' | 'hostname' | 'ipv4' | 'ipv6' | 'uri' | string;\n example?: any;\n\n // RxDB-specific\n ref?: string;\n final?: boolean;\n};\n\nexport interface TopLevelProperty extends JsonSchema {\n default?: any;\n}\n\n/**\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API\n */\nexport type CompressionMode = 'deflate' | 'gzip';\n\nexport type RxJsonSchema<\n /**\n * The doctype must be given, and '=any' cannot be used,\n * otherwise the keyof of primaryKey\n * would be optional when the type of the document is not known.\n */\n RxDocType\n> = {\n title?: string;\n description?: string;\n version: number;\n\n /**\n * The primary key of the documents.\n * Must be in the top level of the properties of the schema\n * and that property must have the type 'string'\n */\n primaryKey: PrimaryKey;\n\n /**\n * TODO this looks like a typescript-bug\n * we have to allows all string because the 'object'-literal is not recognized\n * retry this in later typescript-versions\n */\n type: 'object' | string;\n properties: { [key in StringKeys]: TopLevelProperty };\n\n /**\n * On the top level the required-array must be set\n * because we always have to set the primary key to required.\n *\n * TODO required should be made non-optional on the top level\n */\n required?: StringKeys[] | readonly StringKeys[];\n\n\n indexes?: (string | string[])[] | (string | readonly string[])[] | readonly (string | string[])[] | readonly (string | readonly string[])[];\n encrypted?: string[] | readonly string[];\n keyCompression?: boolean;\n /**\n * if not set, rxdb will set 'false' as default\n * Having additionalProperties: true is not allowed on the root level to ensure\n * that property names do not clash with properties of the RxDocument class\n * or ORM methods.\n */\n additionalProperties?: false;\n attachments?: {\n encrypted?: boolean;\n /**\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API\n */\n compression?: CompressionMode;\n };\n /**\n * Options for the sharding plugin of rxdb-premium.\n * We set these on the schema because changing the shard amount or mode\n * will require a migration.\n * @link https://rxdb.info/rx-storage-sharding.html\n */\n sharding?: {\n /**\n * Amount of shards.\n * This value cannot be changed after you have stored data,\n * if you change it anyway, you will loose the existing data.\n */\n shards: number;\n /**\n * Either shard by collection or by database.\n * For most use cases (IndexedDB based storages), sharding by collection is the way to go\n * because it has a faster initial load time.\n */\n mode: 'database' | 'collection';\n };\n crdt?: CRDTSchemaOptions;\n};\n\n/**\n * Used to aggregate the document type from the schema.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport type ExtractDocumentTypeFromTypedRxJsonSchema = AsTyped;\n"],"mappings":""} \ No newline at end of file +{"version":3,"file":"rx-schema.d.js","names":[],"sources":["../../../src/types/rx-schema.d.ts"],"sourcesContent":["import { AsTyped } from 'as-typed';\nimport type { CRDTSchemaOptions } from './plugins/crdt.d.ts';\nimport type { StringKeys } from './util.d.ts';\n\n/**\n * @link https://github.com/types/lib-json-schema/blob/master/v4/index.d.ts\n */\nexport type JsonSchemaTypes = 'array' | 'boolean' | 'integer' | 'number' | 'null' | 'object' | 'string' | (string & {});\n\nexport type CompositePrimaryKey = {\n /**\n * The top level field of the document that will be used\n * to store the composite key as string.\n */\n key: StringKeys;\n\n /**\n * The fields of the composite key,\n * the fields must be required and final\n * and have the type number, int, or string.\n */\n fields: (StringKeys | string)[] | readonly (StringKeys | string)[];\n /**\n * The separator which is used to concat the\n * primary fields values.\n * Choose a character as separator that is known\n * to never appear inside of the primary fields values.\n * I recommend to use the pipe char '|'.\n */\n separator: string;\n};\n\nexport type PrimaryKey = StringKeys | CompositePrimaryKey;\n\nexport type JsonSchema = {\n allOf?: JsonSchema[] | readonly JsonSchema[];\n anyOf?: JsonSchema[] | readonly JsonSchema[];\n oneOf?: JsonSchema[] | readonly JsonSchema[];\n additionalItems?: boolean | JsonSchema;\n additionalProperties?: boolean | JsonSchema;\n type?: JsonSchemaTypes | JsonSchemaTypes[] | readonly JsonSchemaTypes[];\n description?: string;\n dependencies?: {\n [key: string]: JsonSchema | string[] | readonly string[];\n };\n exclusiveMinimum?: boolean;\n exclusiveMaximum?: boolean;\n items?: JsonSchema | JsonSchema[] | readonly JsonSchema[];\n multipleOf?: number;\n maxProperties?: number;\n maximum?: number;\n minimum?: number;\n maxLength?: number;\n minLength?: number;\n maxItems?: number;\n minItems?: number;\n minProperties?: number;\n pattern?: string;\n patternProperties?: {\n [key: string]: JsonSchema;\n };\n properties?: {\n [key in StringKeys]: JsonSchema;\n };\n required?: string[] | readonly string[];\n uniqueItems?: boolean;\n enum?: any[] | readonly any[];\n not?: JsonSchema;\n definitions?: {\n [key: string]: JsonSchema;\n };\n format?: 'date-time' | 'email' | 'hostname' | 'ipv4' | 'ipv6' | 'uri' | string;\n example?: any;\n\n // RxDB-specific\n ref?: string;\n final?: boolean;\n};\n\nexport interface TopLevelProperty extends JsonSchema {\n default?: any;\n}\n\n/**\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API\n */\nexport type CompressionMode = 'deflate' | 'gzip';\n\nexport type RxJsonSchema<\n /**\n * The doctype must be given, and '=any' cannot be used,\n * otherwise the keyof of primaryKey\n * would be optional when the type of the document is not known.\n */\n RxDocType\n> = {\n title?: string;\n description?: string;\n version: number;\n\n /**\n * The primary key of the documents.\n * Must be in the top level of the properties of the schema\n * and that property must have the type 'string'\n */\n primaryKey: PrimaryKey;\n\n /**\n * TODO this looks like a typescript-bug\n * we have to allows all string because the 'object'-literal is not recognized\n * retry this in later typescript-versions\n */\n type: 'object' | string;\n properties: { [key in StringKeys]: TopLevelProperty };\n\n /**\n * On the top level the required-array must be set\n * because we always have to set the primary key to required.\n *\n * TODO required should be made non-optional on the top level\n */\n required?: StringKeys[] | readonly StringKeys[];\n\n\n /**\n * Indexes that will be used for the queries.\n * RxDB will internally prepend the _deleted field to the index\n * because queries do NOT return documents with _deleted=true.\n */\n indexes?: (string | string[])[] | (string | readonly string[])[] | readonly (string | string[])[] | readonly (string | readonly string[])[];\n\n /**\n * Internally used indexes that do not get _deleted prepended\n * by RxDB. Use these to speed up queries that are run manually on the storage\n * or to speed up requests when you use the RxDB server.\n * These could also be utilised when you build a plugin that\n * has to query documents without respecting the _deleted value.\n */\n internalIndexes?: string[][] | readonly string[][];\n\n\n encrypted?: string[] | readonly string[];\n keyCompression?: boolean;\n /**\n * if not set, rxdb will set 'false' as default\n * Having additionalProperties: true is not allowed on the root level to ensure\n * that property names do not clash with properties of the RxDocument class\n * or ORM methods.\n */\n additionalProperties?: false;\n attachments?: {\n encrypted?: boolean;\n /**\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API\n */\n compression?: CompressionMode;\n };\n /**\n * Options for the sharding plugin of rxdb-premium.\n * We set these on the schema because changing the shard amount or mode\n * will require a migration.\n * @link https://rxdb.info/rx-storage-sharding.html\n */\n sharding?: {\n /**\n * Amount of shards.\n * This value cannot be changed after you have stored data,\n * if you change it anyway, you will loose the existing data.\n */\n shards: number;\n /**\n * Either shard by collection or by database.\n * For most use cases (IndexedDB based storages), sharding by collection is the way to go\n * because it has a faster initial load time.\n */\n mode: 'database' | 'collection';\n };\n crdt?: CRDTSchemaOptions;\n};\n\n/**\n * Used to aggregate the document type from the schema.\n * @link https://github.com/pubkey/rxdb/discussions/3467\n */\nexport type ExtractDocumentTypeFromTypedRxJsonSchema = AsTyped;\n"],"mappings":""} \ No newline at end of file diff --git a/dist/types/plugins/dev-mode/error-messages.d.ts b/dist/types/plugins/dev-mode/error-messages.d.ts index 95e1d6c9bc0..cd0f518b743 100644 --- a/dist/types/plugins/dev-mode/error-messages.d.ts +++ b/dist/types/plugins/dev-mode/error-messages.d.ts @@ -120,6 +120,9 @@ export declare const ERROR_MESSAGES: { RC_WEBRTC_PEER: string; RC_COUCHDB_1: string; RC_COUCHDB_2: string; + RC_OUTDATED: string; + RC_UNAUTHORIZED: string; + RC_FORBIDDEN: string; SC1: string; SC2: string; SC3: string; diff --git a/dist/types/plugins/replication-graphql/index.d.ts b/dist/types/plugins/replication-graphql/index.d.ts index 86d94629a80..b2a0d359646 100644 --- a/dist/types/plugins/replication-graphql/index.d.ts +++ b/dist/types/plugins/replication-graphql/index.d.ts @@ -1,4 +1,4 @@ -import type { RxCollection, ReplicationPullOptions, ReplicationPushOptions, GraphQLServerUrl, RxGraphQLReplicationQueryBuilderResponseObject, RxGraphQLReplicationClientState } from '../../types/index.d.ts'; +import type { RxCollection, ReplicationPullOptions, ReplicationPushOptions, GraphQLServerUrl, RxGraphQLReplicationQueryBuilderResponseObject, RxGraphQLReplicationClientState, ById } from '../../types/index.d.ts'; import { RxReplicationState } from '../replication/index.ts'; import { SyncOptionsGraphQL } from '../../index.ts'; export declare class RxGraphQLReplicationState extends RxReplicationState { @@ -14,9 +14,7 @@ export declare class RxGraphQLReplicationState extend autoStart?: boolean | undefined; readonly customFetch?: ((input: RequestInfo | URL, init?: RequestInit | undefined) => Promise) | undefined; constructor(url: GraphQLServerUrl, clientState: RxGraphQLReplicationClientState, replicationIdentifier: string, collection: RxCollection, deletedField: string, pull?: ReplicationPullOptions | undefined, push?: ReplicationPushOptions | undefined, live?: boolean | undefined, retryTime?: number | undefined, autoStart?: boolean | undefined, customFetch?: ((input: RequestInfo | URL, init?: RequestInit | undefined) => Promise) | undefined); - setHeaders(headers: { - [k: string]: string; - }): void; + setHeaders(headers: ById): void; setCredentials(credentials: RequestCredentials | undefined): void; graphQLRequest(queryParams: RxGraphQLReplicationQueryBuilderResponseObject): Promise; } diff --git a/dist/types/plugins/replication-websocket/websocket-client.d.ts b/dist/types/plugins/replication-websocket/websocket-client.d.ts index 3dc6bda3946..e4bbac74983 100644 --- a/dist/types/plugins/replication-websocket/websocket-client.d.ts +++ b/dist/types/plugins/replication-websocket/websocket-client.d.ts @@ -11,11 +11,11 @@ export type WebsocketClient = { error$: Subject; }; /** - * Copied and adapter from the 'reconnecting-websocket' npm module. + * Copied and adapted from the 'reconnecting-websocket' npm module. * Some bundlers have problems with bundling the isomorphic-ws plugin * so we directly check the correctness in RxDB to ensure that we can * throw a helpful error. */ export declare function ensureIsWebsocket(w: typeof IsomorphicWebSocket): void; -export declare function createWebSocketClient(url: string): Promise; +export declare function createWebSocketClient(options: WebsocketClientOptions): Promise; export declare function replicateWithWebsocketServer(options: WebsocketClientOptions): Promise>; diff --git a/dist/types/plugins/replication-websocket/websocket-server.d.ts b/dist/types/plugins/replication-websocket/websocket-server.d.ts index ffe1036a7de..183adba8f14 100644 --- a/dist/types/plugins/replication-websocket/websocket-server.d.ts +++ b/dist/types/plugins/replication-websocket/websocket-server.d.ts @@ -1,4 +1,6 @@ +import type { RxDatabase, RxReplicationHandler } from '../../types/index.d.ts'; import type { ServerOptions } from 'isomorphic-ws'; import type { WebsocketServerOptions, WebsocketServerState } from './websocket-types.ts'; export declare function startSocketServer(options: ServerOptions): WebsocketServerState; +export declare function getReplicationHandlerByCollection(database: RxDatabase, collectionName: string): RxReplicationHandler; export declare function startWebsocketServer(options: WebsocketServerOptions): WebsocketServerState; diff --git a/dist/types/plugins/replication-websocket/websocket-types.d.ts b/dist/types/plugins/replication-websocket/websocket-types.d.ts index ce276ff63e8..0be7f8e8a4f 100644 --- a/dist/types/plugins/replication-websocket/websocket-types.d.ts +++ b/dist/types/plugins/replication-websocket/websocket-types.d.ts @@ -15,11 +15,14 @@ export type WebsocketClientOptions = { url: string; batchSize?: number; live?: boolean; + headers?: { + [k: string]: string; + }; } & ClientOptions; export type WebsocketMessageType = { id: string; collection: string; - method: StringKeys>; + method: StringKeys> | 'auth'; params: any[]; }; export type WebsocketMessageResponseType = { diff --git a/dist/types/plugins/replication/index.d.ts b/dist/types/plugins/replication/index.d.ts index 592f7a6119f..59c494756a0 100644 --- a/dist/types/plugins/replication/index.d.ts +++ b/dist/types/plugins/replication/index.d.ts @@ -34,6 +34,7 @@ export declare class RxReplicationState { readonly canceled$: Observable; readonly active$: Observable; startPromise: Promise; + onCancel: (() => void)[]; constructor( /** * The identifier, used to flag revisions diff --git a/dist/types/plugins/storage-denokv/index.d.ts b/dist/types/plugins/storage-denokv/index.d.ts index dc9f1f6ca61..820d282cf26 100644 --- a/dist/types/plugins/storage-denokv/index.d.ts +++ b/dist/types/plugins/storage-denokv/index.d.ts @@ -4,7 +4,7 @@ import { RxStorageInstanceDenoKV } from "./rx-storage-instance-denokv.ts"; export declare class RxStorageDenoKV implements RxStorage, DenoKVSettings> { settings: DenoKVSettings; name: string; - readonly rxdbVersion = "15.3.0"; + readonly rxdbVersion = "15.4.0"; constructor(settings: DenoKVSettings); createStorageInstance(params: RxStorageInstanceCreationParams): Promise>; } diff --git a/dist/types/plugins/storage-dexie/rx-storage-dexie.d.ts b/dist/types/plugins/storage-dexie/rx-storage-dexie.d.ts index 961b5c977d8..348d8c592c0 100644 --- a/dist/types/plugins/storage-dexie/rx-storage-dexie.d.ts +++ b/dist/types/plugins/storage-dexie/rx-storage-dexie.d.ts @@ -4,7 +4,7 @@ import { RxStorageInstanceDexie } from './rx-storage-instance-dexie.ts'; export declare class RxStorageDexie implements RxStorage { settings: DexieSettings; name: string; - readonly rxdbVersion = "15.3.0"; + readonly rxdbVersion = "15.4.0"; constructor(settings: DexieSettings); createStorageInstance(params: RxStorageInstanceCreationParams): Promise>; } diff --git a/dist/types/plugins/storage-lokijs/rx-storage-lokijs.d.ts b/dist/types/plugins/storage-lokijs/rx-storage-lokijs.d.ts index dcfcc107649..66c9e3cf8bd 100644 --- a/dist/types/plugins/storage-lokijs/rx-storage-lokijs.d.ts +++ b/dist/types/plugins/storage-lokijs/rx-storage-lokijs.d.ts @@ -4,7 +4,7 @@ import type { LeaderElector } from 'broadcast-channel'; export declare class RxStorageLoki implements RxStorage { databaseSettings: LokiDatabaseSettings; name: string; - readonly rxdbVersion = "15.3.0"; + readonly rxdbVersion = "15.4.0"; /** * Create one leader elector by db name. * This is done inside of the storage, not globally diff --git a/dist/types/plugins/storage-memory/memory-types.d.ts b/dist/types/plugins/storage-memory/memory-types.d.ts index 0b390654ab0..5bebf6f19b4 100644 --- a/dist/types/plugins/storage-memory/memory-types.d.ts +++ b/dist/types/plugins/storage-memory/memory-types.d.ts @@ -18,6 +18,7 @@ export type MemoryStorageInternalsByIndex = { * that have been created with the same [databaseName+collectionName] combination. */ export type MemoryStorageInternals = { + id: string; /** * Schema of the first instance created with the given settings. * Used to ensure that the same storage is not re-created with diff --git a/dist/types/plugins/storage-mongodb/rx-storage-mongodb.d.ts b/dist/types/plugins/storage-mongodb/rx-storage-mongodb.d.ts index f1380b47c24..3784bc5e7c4 100644 --- a/dist/types/plugins/storage-mongodb/rx-storage-mongodb.d.ts +++ b/dist/types/plugins/storage-mongodb/rx-storage-mongodb.d.ts @@ -4,7 +4,7 @@ import { RxStorageInstanceMongoDB } from './rx-storage-instance-mongodb.ts'; export declare class RxStorageMongoDB implements RxStorage { databaseSettings: MongoDBDatabaseSettings; name: string; - readonly rxdbVersion = "15.3.0"; + readonly rxdbVersion = "15.4.0"; constructor(databaseSettings: MongoDBDatabaseSettings); createStorageInstance(params: RxStorageInstanceCreationParams): Promise>; } diff --git a/dist/types/plugins/storage-remote/rx-storage-remote.d.ts b/dist/types/plugins/storage-remote/rx-storage-remote.d.ts index 79914baf97c..c3c97f5e722 100644 --- a/dist/types/plugins/storage-remote/rx-storage-remote.d.ts +++ b/dist/types/plugins/storage-remote/rx-storage-remote.d.ts @@ -4,7 +4,7 @@ import type { MessageFromRemote, RemoteMessageChannel, RxStorageRemoteInternals, export declare class RxStorageRemote implements RxStorage { readonly settings: RxStorageRemoteSettings; readonly name: string; - readonly rxdbVersion = "15.3.0"; + readonly rxdbVersion = "15.4.0"; private seed; private lastRequestId; messageChannelIfOneMode?: Promise; diff --git a/dist/types/plugins/utils/utils-other.d.ts b/dist/types/plugins/utils/utils-other.d.ts index 6a5c386d33d..fc2cf466604 100644 --- a/dist/types/plugins/utils/utils-other.d.ts +++ b/dist/types/plugins/utils/utils-other.d.ts @@ -1,5 +1,5 @@ export declare function runXTimes(xTimes: number, fn: (idx: number) => void): void; -export declare function ensureNotFalsy(obj: T | false | undefined | null): T; +export declare function ensureNotFalsy(obj: T | false | undefined | null, message?: string): T; export declare function ensureInteger(obj: unknown): number; /** * Using shareReplay() without settings will not unsubscribe diff --git a/dist/types/plugins/utils/utils-rxdb-version.d.ts b/dist/types/plugins/utils/utils-rxdb-version.d.ts index 9fd069534ba..a51ef9e74b6 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 = "15.3.0"; +export declare const RXDB_VERSION = "15.4.0"; diff --git a/dist/types/rx-database.d.ts b/dist/types/rx-database.d.ts index 15879ad8bc7..b270f11c6ab 100644 --- a/dist/types/rx-database.d.ts +++ b/dist/types/rx-database.d.ts @@ -27,7 +27,7 @@ export declare class RxDatabaseBase | undefined; readonly allowSlowCount?: boolean | undefined; readonly idleQueue: IdleQueue; - readonly rxdbVersion = "15.3.0"; + readonly rxdbVersion = "15.4.0"; /** * Contains all known non-closed storage instances * that belong to this database. diff --git a/dist/types/rx-storage-helper.d.ts b/dist/types/rx-storage-helper.d.ts index acb849f25f2..db987272cf0 100644 --- a/dist/types/rx-storage-helper.d.ts +++ b/dist/types/rx-storage-helper.d.ts @@ -1,7 +1,7 @@ /** * Helper functions for accessing the RxStorage instances. */ -import type { BulkWriteRow, BulkWriteRowProcessed, CategorizeBulkWriteRowsOutput, RxAttachmentData, RxAttachmentWriteData, RxChangeEvent, RxCollection, RxDatabase, RxDocumentData, RxDocumentWriteData, RxJsonSchema, RxStorageWriteError, RxStorageChangeEvent, RxStorageInstance, RxStorageInstanceCreationParams, StringKeys, RxStorage } from './types/index.d.ts'; +import type { BulkWriteRow, BulkWriteRowProcessed, CategorizeBulkWriteRowsOutput, RxAttachmentData, RxAttachmentWriteData, RxChangeEvent, RxCollection, RxDatabase, RxDocumentData, RxDocumentWriteData, RxJsonSchema, RxStorageWriteError, RxStorageChangeEvent, RxStorageInstance, RxStorageInstanceCreationParams, StringKeys, RxStorage, FilledMangoQuery } from './types/index.d.ts'; import { Observable } from 'rxjs'; export declare const INTERNAL_STORAGE_NAME = "_rxdb_internal"; export declare const RX_DATABASE_LOCAL_DOCS_STORAGE_NAME = "rxdatabase_storage_local"; @@ -87,6 +87,7 @@ rxJsonSchema: RxJsonSchema>): WrappedRxStorageInstance */ export declare function ensureRxStorageInstanceParamsAreCorrect(params: RxStorageInstanceCreationParams): void; export declare function hasEncryption(jsonSchema: RxJsonSchema): boolean; +export declare function getChangedDocumentsSinceQuery(storageInstance: RxStorageInstance, limit: number, checkpoint?: CheckpointType): FilledMangoQuery; export declare function getChangedDocumentsSince(storageInstance: RxStorageInstance, limit: number, checkpoint?: CheckpointType): Promise<{ documents: RxDocumentData[]; /** diff --git a/dist/types/types/rx-error.d.ts b/dist/types/types/rx-error.d.ts index d2e8a507d4d..9abfe30a604 100644 --- a/dist/types/types/rx-error.d.ts +++ b/dist/types/types/rx-error.d.ts @@ -58,6 +58,7 @@ export interface RxErrorParameters { readonly dataAfter?: any; readonly pull?: boolean; readonly push?: boolean; + readonly url?: string; readonly key?: string; readonly queryObj?: any; readonly query?: any; diff --git a/dist/types/types/rx-schema.d.ts b/dist/types/types/rx-schema.d.ts index 96103b6bb49..805cb56d8f2 100644 --- a/dist/types/types/rx-schema.d.ts +++ b/dist/types/types/rx-schema.d.ts @@ -122,7 +122,23 @@ export type RxJsonSchema< required?: StringKeys[] | readonly StringKeys[]; + /** + * Indexes that will be used for the queries. + * RxDB will internally prepend the _deleted field to the index + * because queries do NOT return documents with _deleted=true. + */ indexes?: (string | string[])[] | (string | readonly string[])[] | readonly (string | string[])[] | readonly (string | readonly string[])[]; + + /** + * Internally used indexes that do not get _deleted prepended + * by RxDB. Use these to speed up queries that are run manually on the storage + * or to speed up requests when you use the RxDB server. + * These could also be utilised when you build a plugin that + * has to query documents without respecting the _deleted value. + */ + internalIndexes?: string[][] | readonly string[][]; + + encrypted?: string[] | readonly string[]; keyCompression?: boolean; /** diff --git a/docs/404.html b/docs/404.html index 525994cf5a2..1929491fb18 100644 --- a/docs/404.html +++ b/docs/404.html @@ -11,8 +11,8 @@ - - + +

RxDB
404 Page Not Found

The page you are looking for does not exist anymore or never has existed. If you have found this page through a link, you should tell the link author to update it.

Maybe one of these can help you to find the desired content:

diff --git a/docs/adapters.html b/docs/adapters.html index bd08211df17..a1519a94016 100644 --- a/docs/adapters.html +++ b/docs/adapters.html @@ -11,8 +11,8 @@ - - + +

PouchDB Adapters

diff --git a/docs/alternatives.html b/docs/alternatives.html index a6f6d7acaa7..1a977e20d68 100644 --- a/docs/alternatives.html +++ b/docs/alternatives.html @@ -11,8 +11,8 @@ - - + +

Alternatives for realtime offline-first JavaScript applications

diff --git a/docs/articles/angular-database.html b/docs/articles/angular-database.html index ae641c3f191..12987e86e15 100644 --- a/docs/articles/angular-database.html +++ b/docs/articles/angular-database.html @@ -11,8 +11,8 @@ - - + +

RxDB as a Database in an Angular Application

diff --git a/docs/articles/browser-database.html b/docs/articles/browser-database.html index 25d08ddffe5..7193d55266c 100644 --- a/docs/articles/browser-database.html +++ b/docs/articles/browser-database.html @@ -11,8 +11,8 @@ - - + +

RxDB: The benefits of Browser Databases

diff --git a/docs/articles/browser-storage.html b/docs/articles/browser-storage.html index b113ee05c1e..8b1e3f8d01a 100644 --- a/docs/articles/browser-storage.html +++ b/docs/articles/browser-storage.html @@ -11,8 +11,8 @@ - - + +

Browser Storage - RxDB as a Database for Browsers

diff --git a/docs/articles/data-base.html b/docs/articles/data-base.html index 32184cb78d8..5f1bda0fb0b 100644 --- a/docs/articles/data-base.html +++ b/docs/articles/data-base.html @@ -11,8 +11,8 @@ - - + +

RxDB as a data base: Empowering Web Applications with Reactive Data Handling

diff --git a/docs/articles/embedded-database.html b/docs/articles/embedded-database.html index 64bdc9039ef..2060b0596c2 100644 --- a/docs/articles/embedded-database.html +++ b/docs/articles/embedded-database.html @@ -11,8 +11,8 @@ - - + +

Using RxDB as an Embedded Database

diff --git a/docs/articles/flutter-database.html b/docs/articles/flutter-database.html index bb6ecb1615c..9c436c8b16d 100644 --- a/docs/articles/flutter-database.html +++ b/docs/articles/flutter-database.html @@ -11,8 +11,8 @@ - - + +

RxDB as a Database in a Flutter Application

diff --git a/docs/articles/frontend-database.html b/docs/articles/frontend-database.html index ade867b1e06..dd29f4f1e47 100644 --- a/docs/articles/frontend-database.html +++ b/docs/articles/frontend-database.html @@ -11,8 +11,8 @@ - - + +

RxDB JavaScript Frontend Database: Efficient Data Storage in Frontend Applications

diff --git a/docs/articles/in-memory-nosql-database.html b/docs/articles/in-memory-nosql-database.html index 890aef7684b..5422eddce26 100644 --- a/docs/articles/in-memory-nosql-database.html +++ b/docs/articles/in-memory-nosql-database.html @@ -11,8 +11,8 @@ - - + +

RxDB as In-memory NoSQL Database: Empowering Real-Time Applications

diff --git a/docs/articles/ionic-database.html b/docs/articles/ionic-database.html index 4506899f440..5f5c6e12181 100644 --- a/docs/articles/ionic-database.html +++ b/docs/articles/ionic-database.html @@ -11,8 +11,8 @@ - - + +

Ionic Storage - RxDB as database for hybrid apps

diff --git a/docs/articles/json-database.html b/docs/articles/json-database.html index 5aecf744b1b..84028f3cbe6 100644 --- a/docs/articles/json-database.html +++ b/docs/articles/json-database.html @@ -11,8 +11,8 @@ - - + +

RxDB - JSON Database for JavaScript

diff --git a/docs/articles/localstorage.html b/docs/articles/localstorage.html index c4e8e35b097..cee7e28c158 100644 --- a/docs/articles/localstorage.html +++ b/docs/articles/localstorage.html @@ -11,8 +11,8 @@ - - + +

Using localStorage in Modern Applications: A Comprehensive Guide

diff --git a/docs/articles/mobile-database.html b/docs/articles/mobile-database.html index c831cb41571..b2519221075 100644 --- a/docs/articles/mobile-database.html +++ b/docs/articles/mobile-database.html @@ -11,8 +11,8 @@ - - + +

Mobile Database - RxDB as Database for Mobile Applications

diff --git a/docs/articles/progressive-web-app-database.html b/docs/articles/progressive-web-app-database.html index 169966eb061..f06f3983ec9 100644 --- a/docs/articles/progressive-web-app-database.html +++ b/docs/articles/progressive-web-app-database.html @@ -11,8 +11,8 @@ - - + +

RxDB as a Database for Progressive Web Apps (PWA)

diff --git a/docs/articles/react-database.html b/docs/articles/react-database.html index 5405aa8f40b..6a2453994e7 100644 --- a/docs/articles/react-database.html +++ b/docs/articles/react-database.html @@ -11,8 +11,8 @@ - - + +

RxDB as a Database for React Applications

diff --git a/docs/articles/realtime-database.html b/docs/articles/realtime-database.html index 44148ab7ca3..8566fb8b558 100644 --- a/docs/articles/realtime-database.html +++ b/docs/articles/realtime-database.html @@ -11,8 +11,8 @@ - - + +

What is a realtime database?

diff --git a/docs/assets/js/0e268d20.5a58af76.js b/docs/assets/js/0e268d20.5a58af76.js new file mode 100644 index 00000000000..1ed6e279840 --- /dev/null +++ b/docs/assets/js/0e268d20.5a58af76.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[2160],{5921:(e,t,r)=>{r.d(t,{O9:()=>Hr,N8:()=>Qr,dZ:()=>Fr});var a=r(8061);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function i(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function s(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var i in t)n[i]=e(t[i]);return n};function l(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var u=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},h=new Set(["__proto__","prototype","constructor"]),d=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var i of e)switch(i){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=i),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=i;break}if(h.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=i;break}if("property"===a){if(h.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!d.has(i))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=i}switch(n&&(r+="\\"),a){case"property":if(h.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function p(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function f(e,t){if(p(e,t))throw new Error("Cannot use string index")}function y(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!u(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function k(e,t,r){return"RxError ("+t+"):\n"+e+"\n"+function(e){var t="";return 0===Object.keys(e).length?t:(t+="Given parameters: {\n",t+=Object.keys(e).map((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var D=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=k(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.Z)(t,e),t.prototype.toString=function(){return this.message},(0,b.Z)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,w.Z)(Error)),_=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=k(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.Z)(t,e),t.prototype.toString=function(){return this.message},(0,b.Z)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,w.Z)(TypeError));function I(e,t){return new D(e,j.tunnelErrorMessage(e),t)}function R(e,t){return new _(e,j.tunnelErrorMessage(e),t)}function E(e){return!(!e||409!==e.status)&&e}var P={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var S=/\./g,C="abcdefghijklmnopqrstuvwxyz";function O(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=y(t,e);if(void 0===r)throw I("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function W(e){var t=T((e=s(e)).primaryKey);e.properties=s(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=z,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=F(e);(0,g.gu)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,g.AD)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var z={type:"object",properties:{lwt:{type:"number",minimum:A,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function F(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=T(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var Q="docs",H="changes",U="attachments",K="dexie",Z=new Map,V=new Map;var J="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return J+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(J)?"|"+e.substring(J.length):e}function X(e,t){return t?(t=te(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=T(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,g.qo)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function ie(e,t){return e+"||"+t}function se(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,g.qo)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===M(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,g.Nb)(r)):r}var oe=r(6974),ce=r(984),le=r(7400),ue=String.fromCharCode(65535),he=Number.MIN_SAFE_INTEGER;function de(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),i=new Set;Object.keys(r).forEach((t=>{var a=M(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&i.add(t)}));var s,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!i.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,l=!0,u=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],i={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);i=Object.assign(i,r)}})):i={startKey:l?he:ue,endKey:a?ue:he,inclusiveStart:!0,inclusiveEnd:!0};return void 0===i.startKey&&(i.startKey=he),void 0===i.endKey&&(i.endKey=ue),void 0===i.inclusiveStart&&(i.inclusiveStart=!0),void 0===i.inclusiveEnd&&(i.inclusiveEnd=!0),l&&!i.inclusiveStart&&(l=!1),a&&!i.inclusiveEnd&&(a=!1),i})),h=u.map((e=>e.startKey)),d=u.map((e=>e.endKey)),m={index:e,startKeys:h,endKeys:d,inclusiveEnd:a,inclusiveStart:l,sortSatisfiedByIndex:!n&&o===e.filter((e=>!i.has(e))).join(","),selectorSatisfiedByIndex:ye(e,t.selector,h,d)},p=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},i=10,s=(0,g.r0)(r.startKeys,(e=>e!==he&&e!==ue));n(s*i);var o=(0,g.r0)(r.startKeys,(e=>e!==ue&&e!==he));n(o*i);var c=(0,g.r0)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*i*1.5);var l=r.sortSatisfiedByIndex?5:0;return n(l),a}(0,0,m);(p>=c||t.index)&&(c=p,s=m)})),!s)throw I("SNH",{query:t});return s}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),pe=new Set(["$eq","$gt","$gte"]),fe=new Set(["$eq","$lt","$lte"]);function ye(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var i=[],s=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var l=Object.keys(c).filter((e=>pe.has(e)));if(l.length>1)return!1;var u=l[0];if(u&&s.add(o),"$eq"!==u){if(i.length>0)return!1;i.push(u)}}var h=[],d=new Set;for(var[m,p]of Object.entries(t)){if(!e.includes(m))return!1;var f=Object.keys(p).filter((e=>fe.has(e)));if(f.length>1)return!1;var y=f[0];if(y&&d.add(m),"$eq"!==y){if(h.length>0)return!1;h.push(y)}}var v=0;for(var g of e){for(var b of[s,d]){if(!b.has(g)&&b.size>0)return!1;b.delete(g)}if(r[v]!==a[v]&&s.size>0&&d.size>0)return!1;v++}return!0}var ve=r(6250),ge=r(7761),be=r(7132),xe=r(6496),we=r(6851),je=r(3516),ke=r(8039),De=r(5308),_e=r(2106),Ie=!1;function Re(e){return Ie||((0,ge.Qs)(ge.$M.PIPELINE,{$sort:xe.E3,$project:xe.FM}),(0,ge.Qs)(ge.$M.QUERY,{$and:we.h$,$eq:je.l3,$elemMatch:De.rr,$exists:_e.G,$gt:je.ok,$gte:je.m9,$in:je.FI,$lt:je.Ty,$lte:je.HG,$ne:je.ny,$nin:je.IS,$mod:ke.JD,$nor:we.ps,$not:we._w,$or:we.Ko,$regex:ke.GO,$size:De.QH,$type:_e.e}),Ie=!0),new be.A(e)}function Ee(e,t){var r=T(e.primaryKey);t=s(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,g.qo)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var i=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&i.add(t)}));var o,l=-1;e.indexes.forEach((e=>{var t=(0,g.AD)(e)?e:[e],r=t.findIndex((e=>!i.has(e)));r>0&&r>l&&(l=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Pe(e,t){if(!t.sort)throw I("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,i=Object.keys(e)[0],s=Object.values(e)[0];r.push({key:i,direction:s,getValueFn:(t=i,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Ce(e){return e===he?-1/0:e}function Oe(e,t,r){return e.includes(t)?r===ue||!0===r?"1":"0":r}function Ne(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Ce),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Ce);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Be(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,i=n+(a.limit?a.limit:1/0),s=t.queryPlan,o=!1;s.selectorSatisfiedByIndex||(o=Se(e.schema,t.query));var c=Ne(r.booleanIndexes,s,r.dexieDb._options.IDBKeyRange),l=s.index,u=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(Q);t="["+l.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||u.push(n),s.sortSatisfiedByIndex&&u.length===i?e():a.continue()}else e()}}))})),!s.sortSatisfiedByIndex){var h=Pe(e.schema,t.query);u=u.sort(h)}return{documents:u=u.slice(n,i)}}function Ae(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function qe(e){return parseInt(e.split("-")[0],10)}function Me(e,t){var r=t?t._rev:null;return(r?Ae(r).height:0)+1+"-"+e}var $e="_rxdb_internal";async function Te(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function We(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:j.deepFreezeWhenDevMode(a),previousDocumentData:j.deepFreezeWhenDevMode(n)}}function ze(e,t,r,a){if(a)throw 409===a.status?I("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?I("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function Fe(e){return{previous:e.previous,document:Qe(e.document)}}function Qe(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=s(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,i,s;t._attachments[r]=(s=(n=a).data)?{length:(i=s,atob(i).length),digest:n.digest,type:n.type}:n})),t}function He(e){var t=s(e);return t._meta=s(e._meta),t}function Ue(e,t,r){j.deepFreezeWhenDevMode(r);var a=T(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,i){var o=n.map((n=>function(n){var i=s(n.document);if(i._meta=s(i._meta),j.isDevMode()){i=$(a,r,i);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw I("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw I("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return i._meta.lwt=(0,ce.z)(),i._rev=Me(e.token,n.previous),{document:i,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,i))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,le.Is)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var s=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:Me(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(s,i))).then((e=>((0,g.gu)(a.error,e.error),(0,g.gu)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,le.Is)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=s(Object.assign({},e.output.documentData,{_meta:q(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ke=r(5677),Ze=r(3981),Ve=new Map;function Je(e,t){var r=Ve.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Ve.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Ve.get(t);return n||(n={bc:new Ze.g0(["RxDB:",e,r].join("|")),refs:new Set},Ve.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),i=new oe.x,s=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&i.next(r.eventBulk)};n.addEventListener("message",s);var o=r.changeStream(),c=!1,l=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return i.asObservable().pipe((0,Ke.b)(o))};var u=r.close.bind(r);r.close=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),u()};var h=r.remove.bind(r);r.remove=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),h()}}}var Ye=(0,ce.z)(),Xe=function(){function e(e,t,r,a,n,i,s){this.changes$=new oe.x,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=i,this.settings=s,this.primaryPath=T(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw I("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},i=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var s=new Map;(await ne(this.internals,i)).forEach((e=>{var t=e;return t&&s.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,i,s){for(var o,c=!!e.schema.attachments,l=[],u=[],h=[],d={id:O(10),events:[],checkpoint:null,context:n,startTime:(0,ce.z)(),endTime:0},m=d.events,p=[],f=[],y=[],v=r.size>0,g=a.length,b=function(){var e,n=a[x],d=n.document,g=n.previous,b=d[t],w=d._deleted,j=g&&g._deleted,k=void 0;if(v&&(k=r.get(b)),k){var D=k._rev;if(!g||g&&D!==g._rev){var _={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:k};return h.push(_),1}var R=c?Fe(n):n;c&&(w?g&&Object.keys(g._attachments).forEach((e=>{f.push({documentId:b,attachmentId:e,digest:(0,le.Is)(g)._attachments[e].digest})})):(Object.entries(d._attachments).find((t=>{let[r,a]=t;return(g?g._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:k,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(d._attachments).forEach((e=>{let[t,r]=e;var a=g?g._attachments[t]:void 0;if(a){var n=R.document._attachments[t].digest;r.data&&a.digest!==n&&y.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else p.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?h.push(e):(c?(u.push(Fe(R)),s&&s(d)):(u.push(R),s&&s(d)),o=R);var E=null,P=null,S=null;if(j&&!w)S="INSERT",E=c?Qe(d):d;else if(!g||j||w){if(!w)throw I("SNH",{args:{writeRow:n}});S="DELETE",E=(0,le.Is)(d),P=g}else S="UPDATE",E=c?Qe(d):d,P=g;var C={documentId:b,documentData:E,previousDocumentData:P,operation:S};m.push(C)}else{var O=!!w;if(c&&Object.entries(d._attachments).forEach((t=>{let[r,a]=t;a.data?p.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},h.push(e))})),e||(c?(l.push(Fe(n)),i&&i(d)):(l.push(n),i&&i(d)),o=n),!O){var N={documentId:b,operation:"INSERT",documentData:c?Qe(d):d,previousDocumentData:c&&g?Qe(g):g};m.push(N)}}},x=0;x{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>ie(e.documentId,e.attachmentId))))})),(r=(0,le.Is)(r)).eventBulk.events.length>0){var s=(0,le.Is)(r.newestRow).document;r.eventBulk.checkpoint={id:s[this.primaryPath],lwt:s._meta.lwt},r.eventBulk.endTime=(0,ce.z)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Be(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,i=Ne(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),s=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(Q);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(i);s=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),s}(this,e);return{count:t,mode:"fast"}}return{count:(await Be(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.z)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=ie(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=V.get(e)-1;0===r?(t.dexieDb.close(),V.delete(e)):V.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.x},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=i(Z,o,(()=>{var e=(async()=>{var e=s(r);e.autoOpen=!1;var t=new a.U(o,e),i={[Q]:ae(n),[H]:"++sequence, id",[U]:"id"};return t.version(1).stores(i),await t.open(),{dexieDb:t,dexieTable:t[Q],dexieAttachmentsTable:t[U],booleanIndexes:se(n)}})();return Z.set(o,c),V.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(K,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.4.0",at=function(){function e(e){this.name=K,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw I("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw I("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw I("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var i=n[a];if(!nt(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}var it={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function st(e,t){it[e]&&it[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(it[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,g.AD)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=T(this.jsonSchema.primaryKey),this.finalFields=F(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw I("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=M(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),l(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.Z)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),l(this,"defaultValues",e)}},{key:"hash",get:function(){return l(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function lt(e,t,r){void 0===r&&(r=!0),r&&st("preCreateRxSchema",e);var a=W(e);a=function(e){return o(e,!0)}(a),j.deepFreezeWhenDevMode(a);var n=new ct(a,t);return st("createRxSchema",n),n}var ut=r(598),ht=r(6621),dt=r(6728),mt=r(6005),pt=r(7570),ft=r(4419);function yt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=N(e)})),r+="Plugin",new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { "+r+" } from 'rxdb/plugins/"+e+"';\n addRxPlugin("+r+");\n ")}function vt(e){return e.documentData?e.documentData:e.previousDocumentData}var gt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=i(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var i={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,le.Is)(a).push(i),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,i,s,o=(n=a.map((e=>e.lastKnownDocumentState)),i=n[0],s=Ae(i._rev).height,n.forEach((e=>{var t=Ae(e._rev).height;t>s&&(i=e,s=t)})),i),l=o;for(var u of a)try{l=await u.modifier(c(l))}catch(h){u.reject(h),u.reject=()=>{},u.resolve=()=>{}}try{await this.preWrite(l,o)}catch(h){return void a.forEach((e=>e.reject(h)))}e.push({previous:o,document:l})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,s=n(t,a),o=E(e);if(o){var c=i(this.queueByDocId,a,(()=>[]));s.reverse().forEach((e=>{e.lastKnownDocumentState=(0,le.Is)(o.documentInDb),(0,le.Is)(c).unshift(e)}))}else{var l=I("COL20",{name:P[(r=e).status],document:r.documentId,writeError:r});s.forEach((e=>e.reject(l)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var xt={get primaryPath(){if(this.isInstanceOfRxDocument)return this.collection.schema.primaryPath},get primary(){var e=this;if(e.isInstanceOfRxDocument)return e._data[e.primaryPath]},get revision(){if(this.isInstanceOfRxDocument)return this._data._rev},get deleted$(){if(this.isInstanceOfRxDocument)return this.$.pipe((0,ut.U)((e=>e._data._deleted)))},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,ht.h)((e=>!e.isLocal)),(0,ht.h)((e=>e.documentId===this.primary)),(0,ut.U)((e=>vt(e))),(0,dt.O)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.x)(((e,t)=>e._rev===t._rev)),(0,ut.U)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,pt.d)(le.kv))},get$(e){if(j.isDevMode()){if(e.includes(".item."))throw I("DOC1",{path:e});if(e===this.primaryPath)throw I("DOC2");if(this.collection.schema.finalFields.includes(e))throw I("DOC3",{path:e});if(!M(this.collection.schema.jsonSchema,e))throw I("DOC4",{path:e})}return this.$.pipe((0,ut.U)((t=>y(t,e))),(0,mt.x)())},populate(e){var t=M(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return ft.m5;if(!t)throw I("DOC5",{path:e});if(!t.ref)throw I("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw I("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return i(this._propertyCache,e,(()=>{var t=y(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return j.deepFreezeWhenDevMode(t);var r=this;return new Proxy(s(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if("$"===n){var i=a.slice(0,-1);return r.get$(B(e+"."+i))}if("_"===n){var s=a.slice(0,-1);return r.populate(B(e+"."+s))}return r.get(B(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return j.deepFreezeWhenDevMode(this._data);var t=s(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,j.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw yt("update")},incrementalUpdate(e){throw yt("update")},updateCRDT(e){throw yt("crdt")},putAttachment(){throw yt("attachments")},getAttachment(){throw yt("attachments")},allAttachments(){throw yt("attachments")},get allAttachments$(){throw yt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=s(e),this._data._deleted)throw I("DOC11",{id:this.primary,document:this});await jt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return ze(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(I("DOC13",{document:this,id:this.primary}));var t,r=s(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return ze(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw I("DOC14")}};function wt(e){void 0===e&&(e=xt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function jt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),j.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var kt=r(10),Dt=r(6871),_t=r(3028),It=r(1556),Rt=r(8456);function Et(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Pt=new WeakMap;function St(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return i(Pt,e,(()=>{var t=e.collection,r=Ee(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Pe(t.schema.jsonSchema,r),i=Se(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:Et(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>i({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,le.Is)(e._result).docsData.slice(0),n=(0,le.Is)(e._result).docsDataMap,s=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:j.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(g.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},i=(0,Rt.Rf)(t);return"runFullQueryAgain"===i||("doNothing"!==i?(s=!0,(0,Rt.wu)(i,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:a}}var Ct=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return i(this._map,t,(()=>e))},e}();function Ot(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function Nt(e){return e.refCount$.observers.length}var Bt,At,qt=(Bt=100,At=3e4,(e,t)=>{if(!(t._map.size0||(0===i._lastEnsureEqual&&i._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,s).forEach((e=>Ot(t,e)))}}),Mt=new WeakSet;var $t=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=vt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.Z)(e,[{key:"getCachedRxDocument",get:function(){return l(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=j.deepFreezeWhenDevMode,s=e.documentCreator,o=o=>{var c=o[t],l=qe(o._rev),u=i(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),h=u.byRev,d=h.get(l),m=d?d.deref():void 0;return m||(o=n(o),m=s(o),h.set(l,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,ft.y$)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:qe(e.revision)})})))}))))),m};return o}(this))}}]),e}();function Tt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Wt=function(){function e(e,t,r){this.time=(0,ce.z)(),this.collection=e,this.count=r,this.documents=Tt(this.collection._docCache,t)}return(0,b.Z)(e,[{key:"docsData",get:function(){return l(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),l(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Wt(this.collection,e,e.length);this._result=t}else this._result=new Wt(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.z)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw I("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,le.Is)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var i=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,g.gu)(t,n)}}else{var i=e.isFindOneByIdQuery,s=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!s){var o=await r.storageInstance.findDocumentsById([i],!1);o[0]&&(s=o[0])}s&&!s._deleted&&t.push(s)}else{var c=e.getPreparedQuery(),l=await r.storageInstance.query(c);t=l.documents}return t}(this);return i.then((e=>(this._lastExecEnd=(0,ce.z)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw I("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Ut(this).then((()=>(0,Dt.z)(this.$))).then((t=>{if(!t&&e)throw I("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Ee(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),st("prePrepareQuery",e);var t=Kt(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw yt("update")},t.where=function(e){throw yt("query-builder")},t.sort=function(e){throw yt("query-builder")},t.skip=function(e){throw yt("query-builder")},t.limit=function(e){throw yt("query-builder")},(0,b.Z)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,ht.h)((e=>!e.isLocal)),(0,dt.O)(null),(0,It.z)((()=>Ut(this))),(0,ut.U)((()=>this._result)),(0,pt.d)(le.kv),(0,mt.x)(((e,t)=>!(!e||e.time!==(0,le.Is)(t).time))),(0,ht.h)((e=>!!e)),(0,ut.U)((e=>{var t=(0,le.Is)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,_t.T)(e,this.refCount$.pipe((0,ht.h)((()=>!1))))}return this._$}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return l(this,"queryMatcher",Se(0,Ee(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}]),e}();function Qt(e,t,r,a){st("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,i,s=new Ft(e,t,r,a);return s=(n=s).collection._queryCache.getByQuery(n),i=r,Mt.has(i)||(Mt.add(i),(0,ft.Y3)().then((()=>(0,ft.C2)(200))).then((()=>{i.destroyed||i.cacheReplacementPolicy(i,i._queryCache),Mt.delete(i)}))),s}function Ht(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Ut(e){return e.collection.database.destroyed||Ht(e)?ft.kZ:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.z)(),e.collection.database.destroyed||Ht(e))return ft.kZ;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var i=(0,le.Is)(e._result).count,s=i;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&s++,r&&!a&&s--})),s!==i&&(t=!0,e._setResultData(s))}else{var o=St(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var l=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!l.has(t)&&(l.add(t),!0)})),await Promise.all(c.map((async t=>{var s=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:i,devMode:j.isDevMode()});await s.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),s){var u=o.map((e=>{var t=He(e);return t._deleted=!0,t._meta.lwt=(0,ce.z)(),t._rev=Me(r,e),{previous:e,document:t}}));await t.bulkWrite(u,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,ht.h)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var ir=new WeakMap;function sr(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,xt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((t=>{var r=Object.getOwnPropertyDescriptor(e,t),n=!0;(t.startsWith("_")||t.endsWith("_")||t.startsWith("$")||t.endsWith("$"))&&(n=!1),"function"==typeof r.value?Object.defineProperty(a,t,{get(){return r.value.bind(this)},enumerable:n,configurable:!1}):(r.enumerable=n,r.configurable=!1,r.writable&&(r.writable=!1),Object.defineProperty(a,t,r))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return st("createRxDocument",a),a}(function(e){return i(ir,e,(()=>wt(sr(e))))}(e),e,j.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),st("postCreateRxDocument",r),r}var cr=function(e,t){return nt(Qe(e.newDocumentState),Qe(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var lr=["pre","post"],ur=["insert","save","remove","create"],hr=!1,dr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,h){void 0===n&&(n={}),void 0===i&&(i={}),void 0===s&&(s={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===l&&(l=qt),void 0===u&&(u={}),void 0===h&&(h=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new Ct,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=s,this.attachments=o,this.options=c,this.cacheReplacementPolicy=l,this.statics=u,this.conflictHandler=h,function(e){if(hr)return;hr=!0;var t=Object.getPrototypeOf(e);ur.forEach((e=>{lr.map((r=>{var a=r+N(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ue(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new gt(this.storageInstance,this.schema.primaryPath,((e,t)=>jt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,ht.h)((e=>e.collectionName===this.name)));this.$=t.pipe((0,It.z)((e=>e.events))),this.checkpoint$=t.pipe((0,ut.U)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new $t(this.schema.primaryPath,this.$.pipe((0,ht.h)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>We(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),ft.$Y},t.cleanup=function(e){throw yt("cleanup")},t.migrationNeeded=function(){throw yt("migration-schema")},t.getMigrationState=function(){throw yt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return ze(this,e[this.schema.primaryPath],e,r),(0,le.Is)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),i=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),s=Tt(this._docCache,i.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(s.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:s,error:i.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],i=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),i.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=s(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),l=c.success.map((e=>e[t]));return await Promise.all(l.map((e=>this._runHooks("post","remove",i.get(e),r.get(e))))),{success:l.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw I("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),i=a.success.slice(0),s=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)s.push(e);else{var t=e.documentId,a=n(r,t),o=(0,le.Is)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),l=await c.incrementalModify((()=>a));i.push(l)}}))),{error:s,success:i}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return ze(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw I("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=ft.$Y),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw I("COL5",{queryObj:e});return e||(e={selector:{}}),Qt("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw R("COL6",{queryObj:e});var t;if("string"==typeof e)t=Qt("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw I("QU6");(e=s(e)).limit=1,t=Qt("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Qt("count",e,this)},t.findByIds=function(e){return Qt("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw yt("json-dump")},t.importJSON=function(e){throw yt("json-dump")},t.insertCRDT=function(e){throw yt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw R("COL7",{key:t,when:e});if(!lr.includes(e))throw R("COL8",{key:t,when:e});if(!ur.includes(t))throw I("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw I("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),i=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return ft.$Y;var i=n.series.map((e=>()=>e(r,a)));return(0,ft.Ze)(i).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?ft.kZ:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.Z)(e,[{key:"insert$",get:function(){return this.$.pipe((0,ht.h)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,ht.h)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,ht.h)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();var mr=r(7782),pr=r(6753);var fr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,pr.JQ)(e))},yr=r(5898),vr=new Set,gr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,h){void 0===s&&(s=!1),void 0===o&&(o={}),this.idleQueue=new mr.F,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.eventBulks$=new oe.x,this.observable$=this.eventBulks$.pipe((0,It.z)((e=>e.events))),this.storageToken=ft.kZ,this.storageTokenDocument=ft.kZ,this.emittedEventBulkIds=new yr.i(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=i,this.eventReduce=s,this.options=o,this.internalStore=c,this.hashFunction=l,this.cleanupPolicy=u,this.allowSlowCount=h,"pseudoInstance"!==this.name&&(this.internalStore=Ue(this.asRxDatabase,c,Jt),this.storageTokenDocument=async function(e){var t=O(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Vt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:q(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var i=(0,le.Is)(n.error[0]);if(i.isError&&E(i)){var s=i;if(c=s.documentInDb.data.rxdbVersion,l=e.rxdbVersion,!c||l.includes("beta")&&l!==c||c.split(".")[0]!==l.split(".")[0])throw I("DM5",{args:{database:e.name,databaseStateVersion:s.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==s.documentInDb.data.passwordHash)throw I("DB1",{passwordHash:r,existingPasswordHash:s.documentInDb.data.passwordHash});var o=s.documentInDb;return(0,le.Is)(o)}var c,l;throw i}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.$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 Te(this.internalStore,Gt(tr(e,t),Zt));if(!r)throw I("SNH",{name:e,schema:t});var a=He(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[i,o]=e;var c=i,l=o.schema;t[c]=l;var u=lt(l,this.hashFunction);if(r[c]=u,this.collections[i])throw I("DB3",{name:i});var h=tr(i,l),d={id:Gt(h,Zt),key:h,context:Zt,data:{name:c,schemaHash:await u.hash,schema:u.jsonSchema,version:u.version,connectedStorages:[]},_deleted:!1,_meta:q(),_rev:"",_attachments:{}};a.push({document:d});var m=Object.assign({},o,{name:c,schema:u,database:this}),p=s(o);p.database=this,p.name=i,st("preCreateRxCollection",p),m.conflictHandler=p.conflictHandler,n[c]=m})));var i=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(i.error.map((async e=>{if(409!==e.status)throw I("DB12",{database:this.name,writeError:e});var a=(0,le.Is)(e.documentInDb),n=a.data.name,i=r[n];if(a.data.schemaHash!==await i.hash)throw I("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await i.hash,previousSchema:a.data.schema,schema:(0,le.Is)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:s=!0,statics:o={},methods:c={},attachments:l={},options:u={},localDocuments:h=!1,cacheReplacementPolicy:d=qt,conflictHandler:m=cr}=e;var p={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:j.isDevMode()};return st("preCreateRxStorageInstance",p),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,p).then((e=>{var p=new dr(t,r,a,e,n,i,c,l,u,d,o,m);return p.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(p,t,{get:()=>r.bind(p)})}));var e=ft.$Y;return s&&0!==p.schema.version&&(e=p.migratePromise()),e})).then((()=>(st("createRxCollection",{collection:p,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:i,methods:c,attachments:l,options:u,cacheReplacementPolicy:d,localDocuments:h,statics:o}}),p))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw yt("json-dump")},t.importJSON=function(e){throw yt("json-dump")},t.backup=function(e){throw yt("backup")},t.leaderElector=function(){throw yt("leader-election")},t.isLeader=function(){throw yt("leader-election")},t.waitForLeadership=function(){throw yt("leader-election")},t.migrationStates=function(){throw yt("migration-schema")},t.destroy=async function(){return this.destroyed?ft.kZ:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?ft.kZ:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>vr.delete(this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=O(10),n=await br(a,t,e,{},!1,r),i=await Yt(n),s=new Set;i.forEach((e=>s.add(e.data.name)));var o=Array.from(s);return await Promise.all(o.map((i=>ar(t,n,a,e,i,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.Z)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function br(e,t,r,a,n,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:$e,schema:Jt,options:a,multiInstance:n,password:i,devMode:j.isDevMode()})}function xr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i=!0,eventReduce:s=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:l,allowSlowCount:u=!1,localDocuments:h=!1,hashFunction:d=fr}=e;st("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:h}),o||function(e){if(vr.has(e))throw I("DB8",{name:e,link:"https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate"})}(a),vr.add(a);var m=O(10);return br(m,t,a,r,i,n).catch((e=>{throw vr.delete(a),e})).then((e=>{var p=new gr(a,m,t,r,n,i,s,c,e,d,l,u);return ot("createRxDatabase",{database:p,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:h}}).then((()=>p))}))}var wr={RxSchema:ct.prototype,RxDocument:xt,RxQuery:Ft.prototype,RxCollection:dr.prototype,RxDatabase:gr.prototype},jr=new Set,kr=new Set;var Dr=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,x.Z)(t,e),t}(wt()),_r={get isLocal(){return!0},get allAttachments$(){throw I("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(Pr,this.parent);return this.parent.$.pipe((0,ht.h)((e=>e.documentId===this.primary)),(0,ht.h)((e=>e.isLocal)),(0,ut.U)((e=>vt(e))),(0,dt.O)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.x)(((e,t)=>e._rev===t._rev)),(0,ut.U)((t=>e.docCache.getCachedRxDocument(t))),(0,pt.d)(le.kv))},getLatest(){var e=n(Pr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw R("LD2",{objPath:e});var t=y(this._data,e);return t=j.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,j.isDevMode()){if(e.includes(".item."))throw I("LD3",{objPath:e});if(e===this.primaryPath)throw I("LD4")}return this.$.pipe((0,ut.U)((e=>e._data)),(0,ut.U)((t=>y(t,e))),(0,mt.x)())},async incrementalModify(e){var t=await Cr(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Cr(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=s(e))._rev=r._rev}))},async remove(){var e=await Cr(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:q(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Ir=!1,Rr=()=>{if(!Ir){Ir=!0;var e=xt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(_r,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(_r,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>_r[e]=(e=>()=>{throw I("LD6",{functionName:e})})(e)))}};var Er=new WeakMap,Pr=new WeakMap;function Sr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await Or(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ue(t,a,qr);var n=new $t("id",e.$.pipe((0,ht.h)((e=>e.isLocal))),(t=>function(e,t){Rr();var r=new Dr(e.id,e,t);return Object.setPrototypeOf(r,_r),r.prototype=_r,r}(t,e))),i=new gt(a,"id",(()=>{}),(()=>{})),s=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:s,events:r.events.map((t=>We(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:i};return Pr.set(e,c),c})();Er.set(e,a)}function Cr(e){var t=Er.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw I("LD8",{database:r.name,collection:a})}return t}function Or(e,t,r,a,n,i){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Ar(a),schema:qr,options:n,multiInstance:i,devMode:j.isDevMode()})}function Nr(e){var t=Er.get(e);if(t)return Er.delete(e),t.then((e=>e.storageInstance.close()))}async function Br(e,t,r){var a=O(10),n=await Or(a,e,t,r,{},!1);await n.remove()}function Ar(e){return"plugin-local-documents-"+e}var qr=W({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Mr(e,t){var r=await Cr(this),a={id:e,data:t,_deleted:!1,_meta:q(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function $r(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Tr(e){var t=await Cr(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):Te(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Lr(e){return this.$.pipe((0,dt.O)(null),(0,It.z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,It.z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,ht.h)((e=>e.use)),(0,ut.U)((e=>e.doc)))}var Wr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Mr,e.upsertLocal=$r,e.getLocal=Tr,e.getLocal$=Lr},RxDatabase:e=>{e.insertLocal=Mr,e.upsertLocal=$r,e.getLocal=Tr,e.getLocal$=Lr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Sr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Sr(e.collection)}},preDestroyRxDatabase:{after:e=>Nr(e)},postDestroyRxCollection:{after:e=>Nr(e)},postRemoveRxDatabase:{after:e=>Br(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Br(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let zr;function Fr(){return"undefined"!=typeof window&&window.indexedDB}function Qr(){return zr||(zr=(async()=>{!function(e){if(st("preAddRxPlugin",{plugin:e,plugins:jr}),!jr.has(e)){if(kr.has(e.name))throw I("PL3",{name:e.name,plugin:e});if(jr.add(e),kr.add(e.name),!e.rxdb)throw R("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(wr[t])})),e.overwritable&&Object.assign(j,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&it[t].push(r.after),r.before&&it[t].unshift(r.before)}))}}(Wr);var e;return await xr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),zr}const Hr=["#e6008d","#8d2089","#5f2688"]},341:(e,t,r)=>{function a(e,t){if(!window.trigger)throw new Error("window.trigger not defined");return window.trigger(e,t)}r.d(t,{X:()=>a})},6451:(e,t,r)=>{r.r(t),r.d(t,{default:()=>g});var a=r(2263),n=r(3799),i=r(5742),s=r(7294),o=r(7400),c=r(6087);const l=[{name:"Antigua and Barbuda",code:"AG",salary:49527},{name:"Argentina",code:"AR",salary:17158},{name:"Australia",code:"AU",salary:76036},{name:"Austria",code:"AT",salary:59383},{name:"Bahamas",code:"BS",salary:62024},{name:"Belarus",code:"BY",salary:5749},{name:"Belgium",code:"BE",salary:63749},{name:"Bermuda",code:"BM",salary:86590},{name:"Bosnia and Herzegovina",code:"BA",salary:11992},{name:"Brazil",code:"BR",salary:26464},{name:"Bulgaria",code:"BG",salary:23384},{name:"Cambodia",code:"KH",salary:18e3},{name:"Canada",code:"CA",salary:71554},{name:"Chile",code:"CL",salary:31073},{name:"China",code:"CN",salary:40611},{name:"Colombia",code:"CO",salary:12894},{name:"Costa Rica",code:"CR",salary:40256},{name:"Croatia",code:"HR",salary:22566},{name:"Czech Republic",code:"CZ",salary:33760},{name:"Denmark",code:"DK",salary:68778},{name:"Ecuador",code:"EC",salary:35016},{name:"Egypt",code:"EG",salary:7758},{name:"Estonia",code:"EE",salary:26728},{name:"Finland",code:"FI",salary:64198},{name:"France",code:"FR",salary:58137},{name:"Georgia",code:"GE",salary:40315},{name:"Germany",code:"DE",salary:72138},{name:"Greece",code:"GR",salary:36824},{name:"Guatemala",code:"GT",salary:49612},{name:"Holy See (Vatican City State)",code:"VA",salary:51474},{name:"Hong Kong",code:"HK",salary:71970},{name:"Hungary",code:"HU",salary:22341},{name:"Iceland",code:"IS",salary:66512},{name:"India",code:"IN",salary:17710},{name:"Indonesia",code:"ID",salary:20978},{name:"Iraq",code:"IQ",salary:21029},{name:"Ireland",code:"IE",salary:66281},{name:"Israel",code:"IL",salary:57466},{name:"Italy",code:"IT",salary:50900},{name:"Jamaica",code:"JM",salary:21048},{name:"Japan",code:"JP",salary:57793},{name:"Kazakhstan",code:"KZ",salary:12243},{name:"Korea, Republic of",code:"KR",salary:45957},{name:"Latvia",code:"LV",salary:26728},{name:"Luxembourg",code:"LU",salary:84663},{name:"Malaysia",code:"MY",salary:26117},{name:"Malta",code:"MT",salary:41971},{name:"Mexico",code:"MX",salary:24050},{name:"Morocco",code:"MA",salary:17903},{name:"Netherlands",code:"NL",salary:62661},{name:"New Zealand",code:"NZ",salary:63948},{name:"Norway",code:"NO",salary:69498},{name:"Pakistan",code:"PK",salary:9066},{name:"Panama",code:"PA",salary:39143},{name:"Peru",code:"PE",salary:17469},{name:"Philippines",code:"PH",salary:11088},{name:"Poland",code:"PL",salary:30236},{name:"Portugal",code:"PT",salary:37959},{name:"Romania",code:"RO",salary:22319},{name:"Russian Federation",code:"RU",salary:20492},{name:"Saudi Arabia",code:"SA",salary:47336},{name:"Singapore",code:"SG",salary:66023},{name:"Slovakia",code:"SK",salary:29650},{name:"South Africa",code:"ZA",salary:40336},{name:"Spain",code:"ES",salary:47819},{name:"Sweden",code:"SE",salary:49361},{name:"Switzerland",code:"CH",salary:92820},{name:"Taiwan",code:"TW",salary:47737},{name:"Thailand",code:"TH",salary:21772},{name:"Turkey",code:"TR",salary:8788},{name:"Ukraine",code:"UA",salary:14139},{name:"United Arab Emirates",code:"AE",salary:66381},{name:"United Kingdom",code:"GB",salary:61188},{name:"United States",code:"US",salary:91935},{name:"Uruguay",code:"UY",salary:23754},{name:"Vietnam",code:"VN",salary:19058}],u={browser:.4,native:.4,performance:.35,sourcecode:0,perpetual:0},h=.05;var d=r(341),m=r(5921),p=r(2389),f=r(5893);function y(e){let{children:t,fallback:r}=e;return(0,p.Z)()?(0,f.jsx)(f.Fragment,{children:t?.()}):r??null}const v="premium-price-form-value";function g(){const{siteConfig:e}=(0,a.Z)(),t=(0,p.Z)();return(0,s.useEffect)((()=>{(async()=>{if(!t||!(0,m.dZ)())return;const e=await(0,m.N8)(),r=await e.getLocal(v);r&&(console.log("formValueDoc:"),console.dir(r),b("home-country",r._data.data.homeCountry),b("company-size",r._data.data.companySize),b("project-amount",r._data.data.projectAmount),b("license-period",r._data.data.licensePeriod),Object.keys(u).forEach((e=>{b("package-"+e,!1)})),r._data.data.packages.forEach((e=>{b("package-"+e,!0)})))})()})),(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(i.Z,{children:(0,f.jsx)("body",{className:"homepage"})}),(0,f.jsx)(n.Z,{title:`Premium Plugins - ${e.title}`,description:"RxDB plugins for professionals. FAQ, pricing and license",children:(0,f.jsxs)("main",{children:[(0,f.jsx)("div",{className:"block first",children:(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:["\ud83d\udc51 ",(0,f.jsx)("b",{className:"underline",children:"RxDB"})," Premium Plugins"]}),(0,f.jsxs)("p",{style:{width:"80%"},children:["To make RxDB a sustainable project, some plugins are not part of the RxDB open source project. Instead they are part of the"," ",(0,f.jsx)("b",{children:"rxdb-premium"})," package which must be purchased.",(0,f.jsx)("br",{}),"Professional developers use these to get the best ",(0,f.jsx)("b",{children:"performance"})," and the most out of RxDB."]}),(0,f.jsxs)("div",{className:"premium-blocks",children:[(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage OPFS"}),(0,f.jsxs)("p",{children:["Currently the fastest RxStorage that can be used in the browser. Based on the ",(0,f.jsx)("b",{children:"File System Access API"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage IndexedDB"}),(0,f.jsxs)("p",{children:["A really fast storage based on ",(0,f.jsx)("b",{children:"IndexedDB"}),". Made to be used in browsers."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SQLite"}),(0,f.jsxs)("p",{children:["A really fast storage based on ",(0,f.jsx)("b",{children:"SQLite"}),". Used with"," ",(0,f.jsx)("b",{children:"Node.js"}),", ",(0,f.jsx)("b",{children:"Electron"}),", ",(0,f.jsx)("b",{children:"React Native"}),", ",(0,f.jsx)("b",{children:"Capacitor"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Sharding"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that improves performance by applying the sharding technique."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Memory Synced"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that creates a synced in-memory copy which improves performance for the initial page load time and write & read operations."})]})})}),(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Query Optimizer"}),(0,f.jsx)("p",{children:"A tool to find the best index for a given query. You can use this during build time to find the best index and then use that index during runtime."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Localstorage Meta Optimizer"}),(0,f.jsxs)("p",{children:["A wrapper around any other storage which optimizes the initial page load one by using localstorage for meta key-value document. Only works in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SharedWorker"}),(0,f.jsxs)("p",{children:["A RxStorage wrapper to run the storage inside of a SharedWorker which improves the performance by taking CPU load away from the main process. Used in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Worker"}),(0,f.jsx)("p",{children:"A RxStorage wrapper to run the storage inside of a Worker which improves the performance by taking CPU load away from the main process."})]})})}),(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"WebCrypto Encryption"}),(0,f.jsx)("p",{children:"A faster and more secure encryption plugin based on the Web Crypto API."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Filesystem Node"}),(0,f.jsxs)("p",{children:["A fast RxStorage based on the ",(0,f.jsx)("b",{children:"Node.js"})," Filesystem."]})]})})}),(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Logger"}),(0,f.jsx)("p",{children:"A logging plugin useful to debug performance problems and for monitoring with Application Performance Monitoring (APM) tools like Bugsnag, Datadog, Elastic, Sentry and others"})]})})})]})]})}),(0,f.jsx)("div",{className:"block dark",id:"faq",children:(0,f.jsxs)("div",{className:"content centered premium-faq",children:[(0,f.jsxs)("h2",{children:["F.A.Q. ",(0,f.jsx)("b",{children:"(click to toggle)"})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Do I need the Premium Plugins?"}),"When you start using RxDB, you do not need access to the premium plugins. Most use cases can be implemented with the Open Core part of RxDB. There are many"," ",(0,f.jsx)("a",{href:"/rx-storage.html",target:"_blank",children:"RxStorage"}),"options and all core plugins that are required for replication, schema validation, encryption and so on, are totally free. As soon as your application is more then a side project, it is pretty easy to switch to RxDB Premium Plugins by just changing a few lines of configuration.",(0,f.jsx)("br",{}),"The main benefit of the Premium Plugins is ",(0,f.jsx)("b",{children:"performance"}),". The Premium RxStorage implementations have a better performance so reading and writing data is much faster especially on low-end devices. You can find a performance comparison"," ",(0,f.jsx)("a",{href:"/rx-storage-performance.html",target:"_blank",children:"here"}),". Also there are additional Premium Plugins that can be used to further optimize the performance of your application like the"," ",(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})," ","or the"," ",(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"Sharding"})," ","plugin."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not for free?"}),"The development of RxDB started in 2016 and after all these years it became clear that big implementation and improvement steps will not be done by the RxDB community. While the community submits valuable pull requests, they are mostly small improvements or bugfixes for specific edge case. Big rewrites and optimizations that require a big effort have only be done by the RxDB maintainer.",(0,f.jsx)("br",{}),"Selling RxDB Premium ensures that there will be always an incentive for someone to add features, keep everything up to date and to further improve and optimize the codebase. This gives the user the confidence that RxDB is a ",(0,f.jsx)("b",{children:"future proof"})," tech stack to build on which lets RxDB stand out compared to similar technologies."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is there no free trial period?"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:"RxDB is written in JavaScript and the code of the Premium Plugins does not contain any tracking or measurement code that would send information from your application to our servers in production mode. As soon as someone has the code on his computer, the maintainer has no chance to really ensure that after a free trial period the code is no longer used and deleted."}),(0,f.jsxs)("li",{children:["Before you can use the Premium Plugins you have to debate and sign a license agreement with the maintainer. This is a sophisticated process that creates overhead which distracts the maintainer from writing RxDB code. So handling trial period users is just not manageable. For this reason there is also no monthly subscriptions. Premium access must be paid ",(0,f.jsx)("b",{children:"per year"}),"."]})]})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not cheaper?"}),"The price of the Premium Plugins is chosen in way that ensures that there can be always one person that develops RxDB ",(0,f.jsx)("b",{children:"full time"}),". Compared to other JavaScript frameworks and developer tools, RxDB satisfies an edge use case for people that want to store data inside of their application on the users device. Most web developers do not need to do that and rely on the traditional client-server stack. So RxDB cannot be sold to that many people which increases the price."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I install/build the premium plugins in my CI?"}),(0,f.jsx)("b",{children:"Yes"})," you can safely install and use the Premium Plugins in your CI without additional payment."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I get a discount?"}),"Discounts are provided for people that have made a significant contribution to RxDB or one of RxDB's dependencies or to the Open Source Community overall. Also for private personal projects there is the option to solve one of the",(0,f.jsx)("a",{href:"https://github.com/pubkey/rxdb/blob/master/orga/premium-tasks.md",target:"_blank",children:"Premium Tasks"}),"to get 3 years access to the Premium Plugins."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Which payment methods are accepted?"}),(0,f.jsx)("b",{children:"Stripe.com"})," is used as payment processor so most known payment options like credit card, PayPal, SEPA transfer and others are available. A list of all options can be found"," ",(0,f.jsx)("a",{href:"https://stripe.com/docs/payments/payment-methods/overview",title:"stripe payment options",target:"_blank",children:"here"}),"."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I still use the premium plugins when the license has expired?"}),"By default you are not allowed to use the premium plugins after the license has expired and you will no longer be able to install them. But you can choose the ",(0,f.jsx)("b",{children:"Perpetual license"})," option. With the perpetual license option, you can still use the plugins even after the license is expired. But you will no longer get any updates from newer RxDB versions."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Is there any tracking code inside of the premium plugins?"}),'No, the premium plugins themself do not contain any tracking code. When you build your application with RxDB and deploy it to production, it will not make requests to any RxDB server. But when you run "npm install" with the premium package there will be some metadata send from your developers machine to RxDB.']})]})}),(0,f.jsxs)("div",{className:"block",children:[(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:["RxDB Premium ",(0,f.jsx)("b",{className:"underline",children:"Price Calculator"})]}),(0,f.jsx)("div",{className:"price-calculator",children:(0,f.jsxs)("div",{className:"price-calculator-inner",children:[(0,f.jsxs)("form",{id:"price-calculator-form",children:[(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"home-country",children:"Company Home Country:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{list:"home-country",name:"home-country",pattern:"[A-Za-z \\-]{2,}",required:!0,style:{width:"100%",maxWidth:240},autoComplete:"off"}),(0,f.jsx)("datalist",{id:"home-country",children:l.sort(((e,t)=>e.code>=t.code?1:-1)).map(((e,t)=>(0,f.jsx)("option",{value:e.name,children:e.name},t)))})]})]}),(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"company-size",children:"Company Size:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{type:"number",name:"company-size",min:1,max:1e6,required:!0,onKeyDown:()=>{const e=(0,o.Is)(event);return 69!==e.keyCode&&189!==e.keyCode&&190!==e.keyCode}}),(0,f.jsx)("div",{className:"suffix",children:"employee(s)"})]})]}),(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"project-amount",children:"Project Amount:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsxs)("select",{name:"project-amount",id:"project-amount",required:!0,defaultValue:1,children:[(0,f.jsx)("option",{value:1,children:"1"}),(0,f.jsx)("option",{value:2,children:"2"}),(0,f.jsx)("option",{value:"infinity",children:"Infinity"})]}),(0,f.jsx)("div",{className:"suffix",children:"project(s)"})]})]}),(0,f.jsxs)("div",{className:"packages",children:[(0,f.jsx)("h3",{children:"Packages:"}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-browser",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Browser Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:"RxStorage OPFS"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:"RxStorage IndexedDB"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:"RxStorage Worker"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:"WebCrypto Encryption"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-native",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Native Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:"RxStorage SQLite"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:"RxStorage Filesystem Node"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-performance",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Performance Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"RxStorage Sharding"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:"RxStorage Memory Synced"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:"RxStorage Localstorage Meta Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:"RxStorage Shared Worker"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-utilities",type:"checkbox",className:"package-checkbox",defaultChecked:!0,disabled:!0}),(0,f.jsxs)("h4",{children:["Utilities Package ",(0,f.jsx)("b",{children:"always included"})]}),(0,f.jsx)("ul",{children:(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:"Logger"})})})]})}),(0,f.jsx)("div",{className:"clear"}),(0,f.jsx)("h3",{children:"Other Options:"}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-sourcecode",type:"checkbox",className:"package-checkbox"}),(0,f.jsx)("h4",{children:"Source Code access"}),(0,f.jsxs)("p",{children:["Get read access to the unminified plain source code of all purchased packages.",(0,f.jsx)("br",{})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-perpetual",type:"checkbox",className:"package-checkbox"}),(0,f.jsx)("h4",{children:"Perpetual license"}),(0,f.jsxs)("p",{children:["With the perpetual license option, you can still use the plugins even after the license is expired. But you will no longer get any updates from newer RxDB versions.",(0,f.jsx)("br",{})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("h4",{children:"Increase license period"}),(0,f.jsxs)("p",{children:["The default license period is one year. We can do a longer license period to safe time on both sides by not having to go through the licensing process each single year. By choosing a license period of 2 years, you get a 10% discount. With a 3 year license the discount is 20%.",(0,f.jsx)("br",{})]}),(0,f.jsxs)("div",{className:"field",children:[(0,f.jsxs)("div",{className:"input",style:{float:"left",width:"100%"},children:[(0,f.jsx)("div",{className:"prefix",children:"License period "}),(0,f.jsxs)("select",{name:"license-period",id:"license-period",required:!0,defaultValue:1,children:[(0,f.jsx)("option",{value:1,children:"1"}),(0,f.jsx)("option",{value:2,children:"2 (10% discount)"}),(0,f.jsx)("option",{value:3,children:"3 (20% discount)"})]}),(0,f.jsx)("div",{className:"suffix",children:"year(s)"})]}),(0,f.jsx)("div",{className:"clear"})]}),(0,f.jsx)("p",{})]})}),(0,f.jsx)("div",{className:"clear"})]}),(0,f.jsx)("div",{className:"button",id:"price-calculator-submit",onClick:async()=>{(0,d.X)("calculate_premium_price",3);const e=(0,o.Is)(document.getElementById("price-calculator-form"));if(!e.reportValidity())return void console.log("form not valid");const t=new FormData(e),r=Object.fromEntries(t.entries());console.log("formData:"),console.dir(r);const a=l.find((e=>e.name.toLowerCase()===r["home-country"].toLowerCase()));if(!a)return;const n=Object.entries(r).filter((e=>{let[t,r]=e;return t.startsWith("package-")})).map((e=>{let[t]=e;return(0,c.SI)(t.split("-"))})),i=await(0,m.N8)();await i.upsertLocal(v,{companySize:r["company-size"],projectAmount:r["project-amount"],licensePeriod:r["license-period"],homeCountry:a.name,packages:n});const s={companySize:r["company-size"],teamSize:r["developer-count"],projectAmount:r["project-amount"],licensePeriod:parseInt(r["license-period"],10),homeCountryCode:a.code,packages:n},p=function(e){if(console.log("calculatePrice:"),console.dir(e),"number"!=typeof e.licensePeriod)throw new Error("not a number "+typeof e.licensePeriod);const t=(0,o.Is)(l.find((t=>t.code===e.homeCountryCode))).salary;let r=0;e.packages.forEach((e=>{const t=u[e];r+=t})),console.log("aimInPercent: "+r);let a=350+1.4*t*(r/100);if(2===e.packages.length&&(a*=.9),e.packages.length>2&&(a*=.85),e.companySize>1){let t=1+Math.pow(1*e.companySize-1,.95)/100*4.5;const r=6;t>r&&(t=r),console.log("input.companySize "+e.companySize+" - "+t),a*=t}if(e.packages.includes("sourcecode")){a*=1.75;const e=1520;a{console.log("setPrice:"),console.dir(t),e.innerHTML=Math.ceil(t).toString()+" € (EUR)",e.href=function(e){return"https://www.xe.com/en/currencyconverter/convert/?Amount="+e+"&From=EUR&To=USD"}(Math.ceil(t))},w=p.totalPrice/s.licensePeriod;x(y,"infinity"!==s.projectAmount?w/parseInt(s.projectAmount,10)/12:0),x(g,w),x(b,p.totalPrice),f.style.display="block"},children:"Estimate Price"})]}),(0,f.jsxs)("div",{id:"price-calculator-result",style:{display:"none"},children:[(0,f.jsx)("hr",{}),(0,f.jsx)("h4",{children:"Estimated Price:"}),(0,f.jsx)("table",{children:(0,f.jsxs)("tbody",{children:[(0,f.jsxs)("tr",{children:[(0,f.jsx)("th",{children:"Price Per Project per Month"}),(0,f.jsx)("td",{children:(0,f.jsx)("a",{id:"total-per-project-per-month",target:"_blank",rel:"nofollow noopener noreferrer",title:"Click to convert to other currency",href:"#",children:"XX \u20ac"})})]}),(0,f.jsxs)("tr",{children:[(0,f.jsx)("th",{children:"Total Price per Year"}),(0,f.jsx)("td",{children:(0,f.jsx)("a",{id:"total-per-year",target:"_blank",rel:"nofollow noopener noreferrer",title:"Click to convert to other currency",href:"#",children:"XX \u20ac"})})]}),(0,f.jsxs)("tr",{children:[(0,f.jsx)("th",{children:"Total Price"}),(0,f.jsx)("td",{children:(0,f.jsx)("a",{id:"total-price",target:"_blank",rel:"nofollow noopener noreferrer",title:"Click to convert to other currency",href:"#",children:"XX \u20ac"})})]})]})}),(0,f.jsxs)("div",{className:"proceed-hint",children:["Fill out",(0,f.jsxs)("a",{href:"#premium-request-form-block",children:[" ",(0,f.jsx)("b",{children:"this form"})," "]}),"to proceed."]})]})]})})]}),(0,f.jsx)("div",{className:"block dark",id:"premium-request-form-block",children:(0,f.jsxs)("div",{className:"content centered premium-request",children:[(0,f.jsxs)("h2",{children:["Request Premium ",(0,f.jsx)("b",{className:"underline",children:"Form"})]}),(0,f.jsx)("p",{}),(0,f.jsx)(y,{fallback:(0,f.jsx)("span",{children:"Loading form iframe..."}),children:()=>(0,f.jsxs)("iframe",{id:"request-premium-form",src:"https://webforms.pipedrive.com/f/6qflURDWONiPpj67lpG6r45n8feakrtS2AqMRcBf1EuCPRvNcXWdvNH2unFm5EpjW3",children:["Your browser doesn't support iframes, ",(0,f.jsx)("a",{href:"https://webforms.pipedrive.com/f/6qflURDWONiPpj67lpG6r45n8feakrtS2AqMRcBf1EuCPRvNcXWdvNH2unFm5EpjW3",target:"_blank",rel:"nofollow",children:"go here"})]})})]})})]})]})})]})}function b(e,t){if(void 0===t)return;const r=document.querySelector("[name="+e+"]");r&&(r.type&&"checkbox"===r.type?r.checked=t:r.value=t)}},6087:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function i(e){return Array.isArray(e)}function s(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;ai,Nb:()=>l,S7:()=>s,SI:()=>a,gu:()=>c,qo:()=>n,r0:()=>o})},7400:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{Is:()=>a,kv:()=>n});var n={bufferSize:1,refCount:!0}},4419:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$Y:()=>o,C2:()=>u,Y3:()=>a,YB:()=>n,Ze:()=>h,kZ:()=>i,m5:()=>s,y$:()=>c});Promise.resolve(!0);var i=Promise.resolve(!1),s=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var l=o;function u(e){return void 0===e&&(e=void 0),l=l.then((()=>c(e)))}function h(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},984:(e,t,r)=>{r.d(t,{z:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/0e268d20.611068b9.js b/docs/assets/js/0e268d20.611068b9.js deleted file mode 100644 index 208bbd49d36..00000000000 --- a/docs/assets/js/0e268d20.611068b9.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[2160],{5921:(e,t,r)=>{r.d(t,{O9:()=>Hr,N8:()=>Qr,dZ:()=>Fr});var a=r(8061);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function i(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function s(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var i in t)n[i]=e(t[i]);return n};function l(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var u=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},h=new Set(["__proto__","prototype","constructor"]),d=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var i of e)switch(i){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=i),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=i;break}if(h.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=i;break}if("property"===a){if(h.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!d.has(i))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=i}switch(n&&(r+="\\"),a){case"property":if(h.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function p(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function f(e,t){if(p(e,t))throw new Error("Cannot use string index")}function y(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!u(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function k(e,t,r){return"RxError ("+t+"):\n"+e+"\n"+function(e){var t="";return 0===Object.keys(e).length?t:(t+="Given parameters: {\n",t+=Object.keys(e).map((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var D=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=k(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.Z)(t,e),t.prototype.toString=function(){return this.message},(0,b.Z)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,w.Z)(Error)),_=function(e){function t(t,r,a){var n;void 0===a&&(a={});var i=k(r,t,a);return(n=e.call(this,i)||this).code=t,n.message=i,n.parameters=a,n.rxdb=!0,n}return(0,x.Z)(t,e),t.prototype.toString=function(){return this.message},(0,b.Z)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,w.Z)(TypeError));function I(e,t){return new D(e,j.tunnelErrorMessage(e),t)}function R(e,t){return new _(e,j.tunnelErrorMessage(e),t)}function E(e){return!(!e||409!==e.status)&&e}var P={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var S=/\./g,C="abcdefghijklmnopqrstuvwxyz";function O(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=y(t,e);if(void 0===r)throw I("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function W(e){var t=T((e=s(e)).primaryKey);e.properties=s(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=z,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=F(e);(0,g.gu)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,g.AD)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]);var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var z={type:"object",properties:{lwt:{type:"number",minimum:A,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function F(e){var t=Object.keys(e.properties).filter((t=>e.properties[t].final)),r=T(e.primaryKey);return t.push(r),"string"!=typeof e.primaryKey&&e.primaryKey.fields.forEach((e=>t.push(e))),t}var Q="docs",H="changes",U="attachments",K="dexie",Z=new Map,V=new Map;var J="__";function G(e){var t=e.split(".");if(t.length>1)return t.map((e=>G(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return J+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(J)?"|"+e.substring(J.length):e}function X(e,t){return t?(t=te(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=s(t)),e.forEach((e=>{var r=y(t,e);v(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[G(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=T(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,g.qo)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>G(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function ie(e,t){return e+"||"+t}function se(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,g.qo)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===M(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,g.Nb)(r)):r}var oe=r(6974),ce=r(984),le=r(7400),ue=String.fromCharCode(65535),he=Number.MIN_SAFE_INTEGER;function de(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),i=new Set;Object.keys(r).forEach((t=>{var a=M(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&i.add(t)}));var s,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!i.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,l=!0,u=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],i={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);i=Object.assign(i,r)}})):i={startKey:l?he:ue,endKey:a?ue:he,inclusiveStart:!0,inclusiveEnd:!0};return void 0===i.startKey&&(i.startKey=he),void 0===i.endKey&&(i.endKey=ue),void 0===i.inclusiveStart&&(i.inclusiveStart=!0),void 0===i.inclusiveEnd&&(i.inclusiveEnd=!0),l&&!i.inclusiveStart&&(l=!1),a&&!i.inclusiveEnd&&(a=!1),i})),h=u.map((e=>e.startKey)),d=u.map((e=>e.endKey)),m={index:e,startKeys:h,endKeys:d,inclusiveEnd:a,inclusiveStart:l,sortSatisfiedByIndex:!n&&o===e.filter((e=>!i.has(e))).join(","),selectorSatisfiedByIndex:ye(e,t.selector,h,d)},p=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},i=10,s=(0,g.r0)(r.startKeys,(e=>e!==he&&e!==ue));n(s*i);var o=(0,g.r0)(r.startKeys,(e=>e!==ue&&e!==he));n(o*i);var c=(0,g.r0)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*i*1.5);var l=r.sortSatisfiedByIndex?5:0;return n(l),a}(0,0,m);(p>=c||t.index)&&(c=p,s=m)})),!s)throw I("SNH",{query:t});return s}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),pe=new Set(["$eq","$gt","$gte"]),fe=new Set(["$eq","$lt","$lte"]);function ye(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var i=[],s=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var l=Object.keys(c).filter((e=>pe.has(e)));if(l.length>1)return!1;var u=l[0];if(u&&s.add(o),"$eq"!==u){if(i.length>0)return!1;i.push(u)}}var h=[],d=new Set;for(var[m,p]of Object.entries(t)){if(!e.includes(m))return!1;var f=Object.keys(p).filter((e=>fe.has(e)));if(f.length>1)return!1;var y=f[0];if(y&&d.add(m),"$eq"!==y){if(h.length>0)return!1;h.push(y)}}var v=0;for(var g of e){for(var b of[s,d]){if(!b.has(g)&&b.size>0)return!1;b.delete(g)}if(r[v]!==a[v]&&s.size>0&&d.size>0)return!1;v++}return!0}var ve=r(6250),ge=r(7761),be=r(7132),xe=r(6496),we=r(6851),je=r(3516),ke=r(8039),De=r(5308),_e=r(2106),Ie=!1;function Re(e){return Ie||((0,ge.Qs)(ge.$M.PIPELINE,{$sort:xe.E3,$project:xe.FM}),(0,ge.Qs)(ge.$M.QUERY,{$and:we.h$,$eq:je.l3,$elemMatch:De.rr,$exists:_e.G,$gt:je.ok,$gte:je.m9,$in:je.FI,$lt:je.Ty,$lte:je.HG,$ne:je.ny,$nin:je.IS,$mod:ke.JD,$nor:we.ps,$not:we._w,$or:we.Ko,$regex:ke.GO,$size:De.QH,$type:_e.e}),Ie=!0),new be.A(e)}function Ee(e,t){var r=T(e.primaryKey);t=s(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,g.qo)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var i=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&i.add(t)}));var o,l=-1;e.indexes.forEach((e=>{var t=(0,g.AD)(e)?e:[e],r=t.findIndex((e=>!i.has(e)));r>0&&r>l&&(l=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Pe(e,t){if(!t.sort)throw I("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,i=Object.keys(e)[0],s=Object.values(e)[0];r.push({key:i,direction:s,getValueFn:(t=i,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Ce(e){return e===he?-1/0:e}function Oe(e,t,r){return e.includes(t)?r===ue||!0===r?"1":"0":r}function Ne(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Ce),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Oe(e,n,r)})).map(Ce);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Be(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,i=n+(a.limit?a.limit:1/0),s=t.queryPlan,o=!1;s.selectorSatisfiedByIndex||(o=Se(e.schema,t.query));var c=Ne(r.booleanIndexes,s,r.dexieDb._options.IDBKeyRange),l=s.index,u=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(Q);t="["+l.map((e=>G(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||u.push(n),s.sortSatisfiedByIndex&&u.length===i?e():a.continue()}else e()}}))})),!s.sortSatisfiedByIndex){var h=Pe(e.schema,t.query);u=u.sort(h)}return{documents:u=u.slice(n,i)}}function Ae(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function qe(e){return parseInt(e.split("-")[0],10)}function Me(e,t){var r=t?t._rev:null;return(r?Ae(r).height:0)+1+"-"+e}var $e="_rxdb_internal";async function Te(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function We(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:j.deepFreezeWhenDevMode(a),previousDocumentData:j.deepFreezeWhenDevMode(n)}}function ze(e,t,r,a){if(a)throw 409===a.status?I("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?I("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function Fe(e){return{previous:e.previous,document:Qe(e.document)}}function Qe(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=s(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,i,s;t._attachments[r]=(s=(n=a).data)?{length:(i=s,atob(i).length),digest:n.digest,type:n.type}:n})),t}function He(e){var t=s(e);return t._meta=s(e._meta),t}function Ue(e,t,r){j.deepFreezeWhenDevMode(r);var a=T(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,i){var o=n.map((n=>function(n){var i=s(n.document);if(i._meta=s(i._meta),j.isDevMode()){i=$(a,r,i);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw I("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw I("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return i._meta.lwt=(0,ce.z)(),i._rev=Me(e.token,n.previous),{document:i,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,i))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,le.Is)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var s=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:Me(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(s,i))).then((e=>((0,g.gu)(a.error,e.error),(0,g.gu)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,le.Is)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=s(Object.assign({},e.output.documentData,{_meta:q(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ke=r(5677),Ze=r(3981),Ve=new Map;function Je(e,t){var r=Ve.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Ve.delete(e),r.bc.close()):void 0}function Ge(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Ve.get(t);return n||(n={bc:new Ze.g0(["RxDB:",e,r].join("|")),refs:new Set},Ve.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),i=new oe.x,s=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&i.next(r.eventBulk)};n.addEventListener("message",s);var o=r.changeStream(),c=!1,l=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return i.asObservable().pipe((0,Ke.b)(o))};var u=r.close.bind(r);r.close=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),u()};var h=r.remove.bind(r);r.remove=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",s),a||await Je(t.databaseInstanceToken,r),h()}}}var Ye=(0,ce.z)(),Xe=function(){function e(e,t,r,a,n,i,s){this.changes$=new oe.x,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=i,this.settings=s,this.primaryPath=T(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw I("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},i=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var s=new Map;(await ne(this.internals,i)).forEach((e=>{var t=e;return t&&s.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,i,s){for(var o,c=!!e.schema.attachments,l=[],u=[],h=[],d={id:O(10),events:[],checkpoint:null,context:n,startTime:(0,ce.z)(),endTime:0},m=d.events,p=[],f=[],y=[],v=r.size>0,g=a.length,b=function(){var e,n=a[x],d=n.document,g=n.previous,b=d[t],w=d._deleted,j=g&&g._deleted,k=void 0;if(v&&(k=r.get(b)),k){var D=k._rev;if(!g||g&&D!==g._rev){var _={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:k};return h.push(_),1}var R=c?Fe(n):n;c&&(w?g&&Object.keys(g._attachments).forEach((e=>{f.push({documentId:b,attachmentId:e,digest:(0,le.Is)(g)._attachments[e].digest})})):(Object.entries(d._attachments).find((t=>{let[r,a]=t;return(g?g._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:k,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(d._attachments).forEach((e=>{let[t,r]=e;var a=g?g._attachments[t]:void 0;if(a){var n=R.document._attachments[t].digest;r.data&&a.digest!==n&&y.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else p.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?h.push(e):(c?(u.push(Fe(R)),s&&s(d)):(u.push(R),s&&s(d)),o=R);var E=null,P=null,S=null;if(j&&!w)S="INSERT",E=c?Qe(d):d;else if(!g||j||w){if(!w)throw I("SNH",{args:{writeRow:n}});S="DELETE",E=(0,le.Is)(d),P=g}else S="UPDATE",E=c?Qe(d):d,P=g;var C={documentId:b,documentData:E,previousDocumentData:P,operation:S};m.push(C)}else{var O=!!w;if(c&&Object.entries(d._attachments).forEach((t=>{let[r,a]=t;a.data?p.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},h.push(e))})),e||(c?(l.push(Fe(n)),i&&i(d)):(l.push(n),i&&i(d)),o=n),!O){var N={documentId:b,operation:"INSERT",documentData:c?Qe(d):d,previousDocumentData:c&&g?Qe(g):g};m.push(N)}}},x=0;x{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>X(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:ie(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>ie(e.documentId,e.attachmentId))))})),(r=(0,le.Is)(r)).eventBulk.events.length>0){var s=(0,le.Is)(r.newestRow).document;r.eventBulk.checkpoint={id:s[this.primaryPath],lwt:s._meta.lwt},r.eventBulk.endTime=(0,ce.z)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Be(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,i=Ne(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),s=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(Q);t="["+n.map((e=>G(e))).join("+")+"]";var a=r.index(t).count(i);s=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),s}(this,e);return{count:t,mode:"fast"}}return{count:(await Be(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.z)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=ie(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=V.get(e)-1;0===r?(t.dexieDb.close(),V.delete(e)):V.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.x},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=i(Z,o,(()=>{var e=(async()=>{var e=s(r);e.autoOpen=!1;var t=new a.U(o,e),i={[Q]:ae(n),[H]:"++sequence, id",[U]:"id"};return t.version(1).stores(i),await t.open(),{dexieDb:t,dexieTable:t[Q],dexieAttachmentsTable:t[U],booleanIndexes:se(n)}})();return Z.set(o,c),V.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Xe(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Ge(K,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.3.0",at=function(){function e(e){this.name=K,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw I("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw I("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw I("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var i=n[a];if(!nt(e[i],t[i]))return!1}return!0}return e!=e&&t!=t}var it={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function st(e,t){it[e]&&it[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(it[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,g.AD)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=T(this.jsonSchema.primaryKey),this.finalFields=F(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw I("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=M(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),l(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.Z)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),l(this,"defaultValues",e)}},{key:"hash",get:function(){return l(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function lt(e,t,r){void 0===r&&(r=!0),r&&st("preCreateRxSchema",e);var a=W(e);a=function(e){return o(e,!0)}(a),j.deepFreezeWhenDevMode(a);var n=new ct(a,t);return st("createRxSchema",n),n}var ut=r(598),ht=r(6621),dt=r(6728),mt=r(6005),pt=r(7570),ft=r(4419);function yt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=N(e)})),r+="Plugin",new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { "+r+" } from 'rxdb/plugins/"+e+"';\n addRxPlugin("+r+");\n ")}function vt(e){return e.documentData?e.documentData:e.previousDocumentData}var gt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=i(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var i={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,le.Is)(a).push(i),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,i,s,o=(n=a.map((e=>e.lastKnownDocumentState)),i=n[0],s=Ae(i._rev).height,n.forEach((e=>{var t=Ae(e._rev).height;t>s&&(i=e,s=t)})),i),l=o;for(var u of a)try{l=await u.modifier(c(l))}catch(h){u.reject(h),u.reject=()=>{},u.resolve=()=>{}}try{await this.preWrite(l,o)}catch(h){return void a.forEach((e=>e.reject(h)))}e.push({previous:o,document:l})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,s=n(t,a),o=E(e);if(o){var c=i(this.queueByDocId,a,(()=>[]));s.reverse().forEach((e=>{e.lastKnownDocumentState=(0,le.Is)(o.documentInDb),(0,le.Is)(c).unshift(e)}))}else{var l=I("COL20",{name:P[(r=e).status],document:r.documentId,writeError:r});s.forEach((e=>e.reject(l)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var xt={get primaryPath(){if(this.isInstanceOfRxDocument)return this.collection.schema.primaryPath},get primary(){var e=this;if(e.isInstanceOfRxDocument)return e._data[e.primaryPath]},get revision(){if(this.isInstanceOfRxDocument)return this._data._rev},get deleted$(){if(this.isInstanceOfRxDocument)return this.$.pipe((0,ut.U)((e=>e._data._deleted)))},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,ht.h)((e=>!e.isLocal)),(0,ht.h)((e=>e.documentId===this.primary)),(0,ut.U)((e=>vt(e))),(0,dt.O)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.x)(((e,t)=>e._rev===t._rev)),(0,ut.U)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,pt.d)(le.kv))},get$(e){if(j.isDevMode()){if(e.includes(".item."))throw I("DOC1",{path:e});if(e===this.primaryPath)throw I("DOC2");if(this.collection.schema.finalFields.includes(e))throw I("DOC3",{path:e});if(!M(this.collection.schema.jsonSchema,e))throw I("DOC4",{path:e})}return this.$.pipe((0,ut.U)((t=>y(t,e))),(0,mt.x)())},populate(e){var t=M(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return ft.m5;if(!t)throw I("DOC5",{path:e});if(!t.ref)throw I("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw I("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return i(this._propertyCache,e,(()=>{var t=y(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return j.deepFreezeWhenDevMode(t);var r=this;return new Proxy(s(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if("$"===n){var i=a.slice(0,-1);return r.get$(B(e+"."+i))}if("_"===n){var s=a.slice(0,-1);return r.populate(B(e+"."+s))}return r.get(B(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return j.deepFreezeWhenDevMode(this._data);var t=s(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,j.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw yt("update")},incrementalUpdate(e){throw yt("update")},updateCRDT(e){throw yt("crdt")},putAttachment(){throw yt("attachments")},getAttachment(){throw yt("attachments")},allAttachments(){throw yt("attachments")},get allAttachments$(){throw yt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=s(e),this._data._deleted)throw I("DOC11",{id:this.primary,document:this});await jt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return ze(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(I("DOC13",{document:this,id:this.primary}));var t,r=s(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return ze(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw I("DOC14")}};function wt(e){void 0===e&&(e=xt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function jt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),j.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var kt=r(10),Dt=r(6871),_t=r(3028),It=r(1556),Rt=r(8456);function Et(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Pt=new WeakMap;function St(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return i(Pt,e,(()=>{var t=e.collection,r=Ee(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Pe(t.schema.jsonSchema,r),i=Se(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:Et(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>i({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,le.Is)(e._result).docsData.slice(0),n=(0,le.Is)(e._result).docsDataMap,s=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:j.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(g.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},i=(0,Rt.Rf)(t);return"runFullQueryAgain"===i||("doNothing"!==i?(s=!0,(0,Rt.wu)(i,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:s,newResults:a}}var Ct=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return i(this._map,t,(()=>e))},e}();function Ot(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function Nt(e){return e.refCount$.observers.length}var Bt,At,qt=(Bt=100,At=3e4,(e,t)=>{if(!(t._map.size0||(0===i._lastEnsureEqual&&i._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,s).forEach((e=>Ot(t,e)))}}),Mt=new WeakSet;var $t=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=vt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.Z)(e,[{key:"getCachedRxDocument",get:function(){return l(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=j.deepFreezeWhenDevMode,s=e.documentCreator,o=o=>{var c=o[t],l=qe(o._rev),u=i(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),h=u.byRev,d=h.get(l),m=d?d.deref():void 0;return m||(o=n(o),m=s(o),h.set(l,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,ft.y$)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:qe(e.revision)})})))}))))),m};return o}(this))}}]),e}();function Tt(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Wt=function(){function e(e,t,r){this.time=(0,ce.z)(),this.collection=e,this.count=r,this.documents=Tt(this.collection._docCache,t)}return(0,b.Z)(e,[{key:"docsData",get:function(){return l(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),l(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Wt(this.collection,e,e.length);this._result=t}else this._result=new Wt(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.z)(),"count"===this.op){var e=this.getPreparedQuery(),t=await this.collection.storageInstance.count(e);if("slow"!==t.mode||this.collection.database.allowSlowCount)return t.count;throw I("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,le.Is)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var i=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,g.gu)(t,n)}}else{var i=e.isFindOneByIdQuery,s=e.collection._docCache.getLatestDocumentDataIfExists(i);if(!s){var o=await r.storageInstance.findDocumentsById([i],!1);o[0]&&(s=o[0])}s&&!s._deleted&&t.push(s)}else{var c=e.getPreparedQuery(),l=await r.storageInstance.query(c);t=l.documents}return t}(this);return i.then((e=>(this._lastExecEnd=(0,ce.z)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw I("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Ut(this).then((()=>(0,Dt.z)(this.$))).then((t=>{if(!t&&e)throw I("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Ee(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),st("prePrepareQuery",e);var t=Kt(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw yt("update")},t.where=function(e){throw yt("query-builder")},t.sort=function(e){throw yt("query-builder")},t.skip=function(e){throw yt("query-builder")},t.limit=function(e){throw yt("query-builder")},(0,b.Z)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,ht.h)((e=>!e.isLocal)),(0,dt.O)(null),(0,It.z)((()=>Ut(this))),(0,ut.U)((()=>this._result)),(0,pt.d)(le.kv),(0,mt.x)(((e,t)=>!(!e||e.time!==(0,le.Is)(t).time))),(0,ht.h)((e=>!!e)),(0,ut.U)((e=>{var t=(0,le.Is)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,_t.T)(e,this.refCount$.pipe((0,ht.h)((()=>!1))))}return this._$}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return l(this,"queryMatcher",Se(0,Ee(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}]),e}();function Qt(e,t,r,a){st("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,i,s=new Ft(e,t,r,a);return s=(n=s).collection._queryCache.getByQuery(n),i=r,Mt.has(i)||(Mt.add(i),(0,ft.Y3)().then((()=>(0,ft.C2)(200))).then((()=>{i.destroyed||i.cacheReplacementPolicy(i,i._queryCache),Mt.delete(i)}))),s}function Ht(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Ut(e){return e.collection.database.destroyed||Ht(e)?ft.kZ:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.z)(),e.collection.database.destroyed||Ht(e))return ft.kZ;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var i=(0,le.Is)(e._result).count,s=i;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&s++,r&&!a&&s--})),s!==i&&(t=!0,e._setResultData(s))}else{var o=St(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var l=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!l.has(t)&&(l.add(t),!0)})),await Promise.all(c.map((async t=>{var s=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:i,devMode:j.isDevMode()});await s.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),s){var u=o.map((e=>{var t=He(e);return t._deleted=!0,t._meta.lwt=(0,ce.z)(),t._rev=Me(r,e),{previous:e,document:t}}));await t.bulkWrite(u,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,ht.h)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var ir=new WeakMap;function sr(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,xt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((t=>{var r=Object.getOwnPropertyDescriptor(e,t),n=!0;(t.startsWith("_")||t.endsWith("_")||t.startsWith("$")||t.endsWith("$"))&&(n=!1),"function"==typeof r.value?Object.defineProperty(a,t,{get(){return r.value.bind(this)},enumerable:n,configurable:!1}):(r.enumerable=n,r.configurable=!1,r.writable&&(r.writable=!1),Object.defineProperty(a,t,r))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return st("createRxDocument",a),a}(function(e){return i(ir,e,(()=>wt(sr(e))))}(e),e,j.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),st("postCreateRxDocument",r),r}var cr=function(e,t){return nt(Qe(e.newDocumentState),Qe(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var lr=["pre","post"],ur=["insert","save","remove","create"],hr=!1,dr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,h){void 0===n&&(n={}),void 0===i&&(i={}),void 0===s&&(s={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===l&&(l=qt),void 0===u&&(u={}),void 0===h&&(h=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new Ct,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=i,this.methods=s,this.attachments=o,this.options=c,this.cacheReplacementPolicy=l,this.statics=u,this.conflictHandler=h,function(e){if(hr)return;hr=!0;var t=Object.getPrototypeOf(e);ur.forEach((e=>{lr.map((r=>{var a=r+N(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ue(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new gt(this.storageInstance,this.schema.primaryPath,((e,t)=>jt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,ht.h)((e=>e.collectionName===this.name)));this.$=t.pipe((0,It.z)((e=>e.events))),this.checkpoint$=t.pipe((0,ut.U)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new $t(this.schema.primaryPath,this.$.pipe((0,ht.h)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>We(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),ft.$Y},t.cleanup=function(e){throw yt("cleanup")},t.migrationNeeded=function(){throw yt("migration")},t.getMigrationState=function(){throw yt("migration")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return ze(this,e[this.schema.primaryPath],e,r),(0,le.Is)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),i=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),s=Tt(this._docCache,i.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(s.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:s,error:i.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],i=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),i.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=s(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),l=c.success.map((e=>e[t]));return await Promise.all(l.map((e=>this._runHooks("post","remove",i.get(e),r.get(e))))),{success:l.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw I("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),i=a.success.slice(0),s=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)s.push(e);else{var t=e.documentId,a=n(r,t),o=(0,le.Is)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),l=await c.incrementalModify((()=>a));i.push(l)}}))),{error:s,success:i}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return ze(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw I("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=ft.$Y),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw I("COL5",{queryObj:e});return e||(e={selector:{}}),Qt("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw R("COL6",{queryObj:e});var t;if("string"==typeof e)t=Qt("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw I("QU6");(e=s(e)).limit=1,t=Qt("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Qt("count",e,this)},t.findByIds=function(e){return Qt("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw yt("json-dump")},t.importJSON=function(e){throw yt("json-dump")},t.insertCRDT=function(e){throw yt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw R("COL7",{key:t,when:e});if(!lr.includes(e))throw R("COL8",{key:t,when:e});if(!ur.includes(t))throw I("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw I("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),i=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][i].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return ft.$Y;var i=n.series.map((e=>()=>e(r,a)));return(0,ft.Ze)(i).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?ft.kZ:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.Z)(e,[{key:"insert$",get:function(){return this.$.pipe((0,ht.h)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,ht.h)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,ht.h)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();var mr=r(7782),pr=r(6753);var fr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,pr.JQ)(e))},yr=r(5898),vr=new Set,gr=function(){function e(e,t,r,a,n,i,s,o,c,l,u,h){void 0===s&&(s=!1),void 0===o&&(o={}),this.idleQueue=new mr.F,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.eventBulks$=new oe.x,this.observable$=this.eventBulks$.pipe((0,It.z)((e=>e.events))),this.storageToken=ft.kZ,this.storageTokenDocument=ft.kZ,this.emittedEventBulkIds=new yr.i(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=i,this.eventReduce=s,this.options=o,this.internalStore=c,this.hashFunction=l,this.cleanupPolicy=u,this.allowSlowCount=h,"pseudoInstance"!==this.name&&(this.internalStore=Ue(this.asRxDatabase,c,Jt),this.storageTokenDocument=async function(e){var t=O(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Vt,key:Xt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:q(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var i=(0,le.Is)(n.error[0]);if(i.isError&&E(i)){var s=i;if(c=s.documentInDb.data.rxdbVersion,l=e.rxdbVersion,!c||l.includes("beta")&&l!==c||c.split(".")[0]!==l.split(".")[0])throw I("DM5",{args:{database:e.name,databaseStateVersion:s.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==s.documentInDb.data.passwordHash)throw I("DB1",{passwordHash:r,existingPasswordHash:s.documentInDb.data.passwordHash});var o=s.documentInDb;return(0,le.Is)(o)}var c,l;throw i}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.$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 Te(this.internalStore,Gt(tr(e,t),Zt));if(!r)throw I("SNH",{name:e,schema:t});var a=He(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[i,o]=e;var c=i,l=o.schema;t[c]=l;var u=lt(l,this.hashFunction);if(r[c]=u,this.collections[i])throw I("DB3",{name:i});var h=tr(i,l),d={id:Gt(h,Zt),key:h,context:Zt,data:{name:c,schemaHash:await u.hash,schema:u.jsonSchema,version:u.version,connectedStorages:[]},_deleted:!1,_meta:q(),_rev:"",_attachments:{}};a.push({document:d});var m=Object.assign({},o,{name:c,schema:u,database:this}),p=s(o);p.database=this,p.name=i,st("preCreateRxCollection",p),m.conflictHandler=p.conflictHandler,n[c]=m})));var i=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(i.error.map((async e=>{if(409!==e.status)throw I("DB12",{database:this.name,writeError:e});var a=(0,le.Is)(e.documentInDb),n=a.data.name,i=r[n];if(a.data.schemaHash!==await i.hash)throw I("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await i.hash,previousSchema:a.data.schema,schema:(0,le.Is)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:s=!0,statics:o={},methods:c={},attachments:l={},options:u={},localDocuments:h=!1,cacheReplacementPolicy:d=qt,conflictHandler:m=cr}=e;var p={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:j.isDevMode()};return st("preCreateRxStorageInstance",p),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,p).then((e=>{var p=new dr(t,r,a,e,n,i,c,l,u,d,o,m);return p.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(p,t,{get:()=>r.bind(p)})}));var e=ft.$Y;return s&&0!==p.schema.version&&(e=p.migratePromise()),e})).then((()=>(st("createRxCollection",{collection:p,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:i,methods:c,attachments:l,options:u,cacheReplacementPolicy:d,localDocuments:h,statics:o}}),p))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw yt("json-dump")},t.importJSON=function(e){throw yt("json-dump")},t.backup=function(e){throw yt("backup")},t.leaderElector=function(){throw yt("leader-election")},t.isLeader=function(){throw yt("leader-election")},t.waitForLeadership=function(){throw yt("leader-election")},t.migrationStates=function(){throw yt("migration")},t.destroy=async function(){return this.destroyed?ft.kZ:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?ft.kZ:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>vr.delete(this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=O(10),n=await br(a,t,e,{},!1,r),i=await Yt(n),s=new Set;i.forEach((e=>s.add(e.data.name)));var o=Array.from(s);return await Promise.all(o.map((i=>ar(t,n,a,e,i,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.Z)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function br(e,t,r,a,n,i){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:$e,schema:Jt,options:a,multiInstance:n,password:i,devMode:j.isDevMode()})}function xr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i=!0,eventReduce:s=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:l,allowSlowCount:u=!1,localDocuments:h=!1,hashFunction:d=fr}=e;st("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:h}),o||function(e){if(vr.has(e))throw I("DB8",{name:e,link:"https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate"})}(a),vr.add(a);var m=O(10);return br(m,t,a,r,i,n).catch((e=>{throw vr.delete(a),e})).then((e=>{var p=new gr(a,m,t,r,n,i,s,c,e,d,l,u);return ot("createRxDatabase",{database:p,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:i,eventReduce:s,ignoreDuplicate:o,options:c,localDocuments:h}}).then((()=>p))}))}var wr={RxSchema:ct.prototype,RxDocument:xt,RxQuery:Ft.prototype,RxCollection:dr.prototype,RxDatabase:gr.prototype},jr=new Set,kr=new Set;var Dr=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,x.Z)(t,e),t}(wt()),_r={get isLocal(){return!0},get allAttachments$(){throw I("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(Pr,this.parent);return this.parent.$.pipe((0,ht.h)((e=>e.documentId===this.primary)),(0,ht.h)((e=>e.isLocal)),(0,ut.U)((e=>vt(e))),(0,dt.O)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.x)(((e,t)=>e._rev===t._rev)),(0,ut.U)((t=>e.docCache.getCachedRxDocument(t))),(0,pt.d)(le.kv))},getLatest(){var e=n(Pr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw R("LD2",{objPath:e});var t=y(this._data,e);return t=j.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,j.isDevMode()){if(e.includes(".item."))throw I("LD3",{objPath:e});if(e===this.primaryPath)throw I("LD4")}return this.$.pipe((0,ut.U)((e=>e._data)),(0,ut.U)((t=>y(t,e))),(0,mt.x)())},async incrementalModify(e){var t=await Cr(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Cr(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=s(e))._rev=r._rev}))},async remove(){var e=await Cr(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:q(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Ir=!1,Rr=()=>{if(!Ir){Ir=!0;var e=xt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(_r,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(_r,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>_r[e]=(e=>()=>{throw I("LD6",{functionName:e})})(e)))}};var Er=new WeakMap,Pr=new WeakMap;function Sr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await Or(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ue(t,a,qr);var n=new $t("id",e.$.pipe((0,ht.h)((e=>e.isLocal))),(t=>function(e,t){Rr();var r=new Dr(e.id,e,t);return Object.setPrototypeOf(r,_r),r.prototype=_r,r}(t,e))),i=new gt(a,"id",(()=>{}),(()=>{})),s=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:s,events:r.events.map((t=>We(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:i};return Pr.set(e,c),c})();Er.set(e,a)}function Cr(e){var t=Er.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw I("LD8",{database:r.name,collection:a})}return t}function Or(e,t,r,a,n,i){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Ar(a),schema:qr,options:n,multiInstance:i,devMode:j.isDevMode()})}function Nr(e){var t=Er.get(e);if(t)return Er.delete(e),t.then((e=>e.storageInstance.close()))}async function Br(e,t,r){var a=O(10),n=await Or(a,e,t,r,{},!1);await n.remove()}function Ar(e){return"plugin-local-documents-"+e}var qr=W({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Mr(e,t){var r=await Cr(this),a={id:e,data:t,_deleted:!1,_meta:q(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function $r(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Tr(e){var t=await Cr(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):Te(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Lr(e){return this.$.pipe((0,dt.O)(null),(0,It.z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,It.z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,ht.h)((e=>e.use)),(0,ut.U)((e=>e.doc)))}var Wr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Mr,e.upsertLocal=$r,e.getLocal=Tr,e.getLocal$=Lr},RxDatabase:e=>{e.insertLocal=Mr,e.upsertLocal=$r,e.getLocal=Tr,e.getLocal$=Lr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Sr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Sr(e.collection)}},preDestroyRxDatabase:{after:e=>Nr(e)},postDestroyRxCollection:{after:e=>Nr(e)},postRemoveRxDatabase:{after:e=>Br(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Br(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let zr;function Fr(){return"undefined"!=typeof window&&window.indexedDB}function Qr(){return zr||(zr=(async()=>{!function(e){if(st("preAddRxPlugin",{plugin:e,plugins:jr}),!jr.has(e)){if(kr.has(e.name))throw I("PL3",{name:e.name,plugin:e});if(jr.add(e),kr.add(e.name),!e.rxdb)throw R("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(wr[t])})),e.overwritable&&Object.assign(j,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&it[t].push(r.after),r.before&&it[t].unshift(r.before)}))}}(Wr);var e;return await xr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),zr}const Hr=["#e6008d","#8d2089","#5f2688"]},341:(e,t,r)=>{function a(e,t){if(!window.trigger)throw new Error("window.trigger not defined");return window.trigger(e,t)}r.d(t,{X:()=>a})},6451:(e,t,r)=>{r.r(t),r.d(t,{default:()=>g});var a=r(2263),n=r(3799),i=r(5742),s=r(7294),o=r(7400),c=r(6087);const l=[{name:"Antigua and Barbuda",code:"AG",salary:49527},{name:"Argentina",code:"AR",salary:17158},{name:"Australia",code:"AU",salary:76036},{name:"Austria",code:"AT",salary:59383},{name:"Bahamas",code:"BS",salary:62024},{name:"Belarus",code:"BY",salary:5749},{name:"Belgium",code:"BE",salary:63749},{name:"Bermuda",code:"BM",salary:86590},{name:"Bosnia and Herzegovina",code:"BA",salary:11992},{name:"Brazil",code:"BR",salary:26464},{name:"Bulgaria",code:"BG",salary:23384},{name:"Cambodia",code:"KH",salary:18e3},{name:"Canada",code:"CA",salary:71554},{name:"Chile",code:"CL",salary:31073},{name:"China",code:"CN",salary:40611},{name:"Colombia",code:"CO",salary:12894},{name:"Costa Rica",code:"CR",salary:40256},{name:"Croatia",code:"HR",salary:22566},{name:"Czech Republic",code:"CZ",salary:33760},{name:"Denmark",code:"DK",salary:68778},{name:"Ecuador",code:"EC",salary:35016},{name:"Egypt",code:"EG",salary:7758},{name:"Estonia",code:"EE",salary:26728},{name:"Finland",code:"FI",salary:64198},{name:"France",code:"FR",salary:58137},{name:"Georgia",code:"GE",salary:40315},{name:"Germany",code:"DE",salary:72138},{name:"Greece",code:"GR",salary:36824},{name:"Guatemala",code:"GT",salary:49612},{name:"Holy See (Vatican City State)",code:"VA",salary:51474},{name:"Hong Kong",code:"HK",salary:71970},{name:"Hungary",code:"HU",salary:22341},{name:"Iceland",code:"IS",salary:66512},{name:"India",code:"IN",salary:17710},{name:"Indonesia",code:"ID",salary:20978},{name:"Iraq",code:"IQ",salary:21029},{name:"Ireland",code:"IE",salary:66281},{name:"Israel",code:"IL",salary:57466},{name:"Italy",code:"IT",salary:50900},{name:"Jamaica",code:"JM",salary:21048},{name:"Japan",code:"JP",salary:57793},{name:"Kazakhstan",code:"KZ",salary:12243},{name:"Korea, Republic of",code:"KR",salary:45957},{name:"Latvia",code:"LV",salary:26728},{name:"Luxembourg",code:"LU",salary:84663},{name:"Malaysia",code:"MY",salary:26117},{name:"Malta",code:"MT",salary:41971},{name:"Mexico",code:"MX",salary:24050},{name:"Morocco",code:"MA",salary:17903},{name:"Netherlands",code:"NL",salary:62661},{name:"New Zealand",code:"NZ",salary:63948},{name:"Norway",code:"NO",salary:69498},{name:"Pakistan",code:"PK",salary:9066},{name:"Panama",code:"PA",salary:39143},{name:"Peru",code:"PE",salary:17469},{name:"Philippines",code:"PH",salary:11088},{name:"Poland",code:"PL",salary:30236},{name:"Portugal",code:"PT",salary:37959},{name:"Romania",code:"RO",salary:22319},{name:"Russian Federation",code:"RU",salary:20492},{name:"Saudi Arabia",code:"SA",salary:47336},{name:"Singapore",code:"SG",salary:66023},{name:"Slovakia",code:"SK",salary:29650},{name:"South Africa",code:"ZA",salary:40336},{name:"Spain",code:"ES",salary:47819},{name:"Sweden",code:"SE",salary:49361},{name:"Switzerland",code:"CH",salary:92820},{name:"Taiwan",code:"TW",salary:47737},{name:"Thailand",code:"TH",salary:21772},{name:"Turkey",code:"TR",salary:8788},{name:"Ukraine",code:"UA",salary:14139},{name:"United Arab Emirates",code:"AE",salary:66381},{name:"United Kingdom",code:"GB",salary:61188},{name:"United States",code:"US",salary:91935},{name:"Uruguay",code:"UY",salary:23754},{name:"Vietnam",code:"VN",salary:19058}],u={browser:.4,native:.4,performance:.35,sourcecode:0,perpetual:0},h=.05;var d=r(341),m=r(5921),p=r(2389),f=r(5893);function y(e){let{children:t,fallback:r}=e;return(0,p.Z)()?(0,f.jsx)(f.Fragment,{children:t?.()}):r??null}const v="premium-price-form-value";function g(){const{siteConfig:e}=(0,a.Z)(),t=(0,p.Z)();return(0,s.useEffect)((()=>{(async()=>{if(!t||!(0,m.dZ)())return;const e=await(0,m.N8)(),r=await e.getLocal(v);r&&(console.log("formValueDoc:"),console.dir(r),b("home-country",r._data.data.homeCountry),b("company-size",r._data.data.companySize),b("project-amount",r._data.data.projectAmount),b("license-period",r._data.data.licensePeriod),Object.keys(u).forEach((e=>{b("package-"+e,!1)})),r._data.data.packages.forEach((e=>{b("package-"+e,!0)})))})()})),(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(i.Z,{children:(0,f.jsx)("body",{className:"homepage"})}),(0,f.jsx)(n.Z,{title:`Premium Plugins - ${e.title}`,description:"RxDB plugins for professionals. FAQ, pricing and license",children:(0,f.jsxs)("main",{children:[(0,f.jsx)("div",{className:"block first",children:(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:["\ud83d\udc51 ",(0,f.jsx)("b",{className:"underline",children:"RxDB"})," Premium Plugins"]}),(0,f.jsxs)("p",{style:{width:"80%"},children:["To make RxDB a sustainable project, some plugins are not part of the RxDB open source project. Instead they are part of the"," ",(0,f.jsx)("b",{children:"rxdb-premium"})," package which must be purchased.",(0,f.jsx)("br",{}),"Professional developers use these to get the best ",(0,f.jsx)("b",{children:"performance"})," and the most out of RxDB."]}),(0,f.jsxs)("div",{className:"premium-blocks",children:[(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage OPFS"}),(0,f.jsxs)("p",{children:["Currently the fastest RxStorage that can be used in the browser. Based on the ",(0,f.jsx)("b",{children:"File System Access API"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage IndexedDB"}),(0,f.jsxs)("p",{children:["A really fast storage based on ",(0,f.jsx)("b",{children:"IndexedDB"}),". Made to be used in browsers."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SQLite"}),(0,f.jsxs)("p",{children:["A really fast storage based on ",(0,f.jsx)("b",{children:"SQLite"}),". Used with"," ",(0,f.jsx)("b",{children:"Node.js"}),", ",(0,f.jsx)("b",{children:"Electron"}),", ",(0,f.jsx)("b",{children:"React Native"}),", ",(0,f.jsx)("b",{children:"Capacitor"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Sharding"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that improves performance by applying the sharding technique."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Memory Synced"}),(0,f.jsx)("p",{children:"A wrapper around any other storage that creates a synced in-memory copy which improves performance for the initial page load time and write & read operations."})]})})}),(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Query Optimizer"}),(0,f.jsx)("p",{children:"A tool to find the best index for a given query. You can use this during build time to find the best index and then use that index during runtime."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Localstorage Meta Optimizer"}),(0,f.jsxs)("p",{children:["A wrapper around any other storage which optimizes the initial page load one by using localstorage for meta key-value document. Only works in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage SharedWorker"}),(0,f.jsxs)("p",{children:["A RxStorage wrapper to run the storage inside of a SharedWorker which improves the performance by taking CPU load away from the main process. Used in ",(0,f.jsx)("b",{children:"browsers"}),"."]})]})})}),(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Worker"}),(0,f.jsx)("p",{children:"A RxStorage wrapper to run the storage inside of a Worker which improves the performance by taking CPU load away from the main process."})]})})}),(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"WebCrypto Encryption"}),(0,f.jsx)("p",{children:"A faster and more secure encryption plugin based on the Web Crypto API."})]})})}),(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"RxStorage Filesystem Node"}),(0,f.jsxs)("p",{children:["A fast RxStorage based on the ",(0,f.jsx)("b",{children:"Node.js"})," Filesystem."]})]})})}),(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:(0,f.jsx)("div",{className:"premium-block hover-shadow-middle bg-gradient-right-top",children:(0,f.jsxs)("div",{className:"premium-block-inner",children:[(0,f.jsx)("h4",{children:"Logger"}),(0,f.jsx)("p",{children:"A logging plugin useful to debug performance problems and for monitoring with Application Performance Monitoring (APM) tools like Bugsnag, Datadog, Elastic, Sentry and others"})]})})})]})]})}),(0,f.jsx)("div",{className:"block dark",id:"faq",children:(0,f.jsxs)("div",{className:"content centered premium-faq",children:[(0,f.jsxs)("h2",{children:["F.A.Q. ",(0,f.jsx)("b",{children:"(click to toggle)"})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Do I need the Premium Plugins?"}),"When you start using RxDB, you do not need access to the premium plugins. Most use cases can be implemented with the Open Core part of RxDB. There are many"," ",(0,f.jsx)("a",{href:"/rx-storage.html",target:"_blank",children:"RxStorage"}),"options and all core plugins that are required for replication, schema validation, encryption and so on, are totally free. As soon as your application is more then a side project, it is pretty easy to switch to RxDB Premium Plugins by just changing a few lines of configuration.",(0,f.jsx)("br",{}),"The main benefit of the Premium Plugins is ",(0,f.jsx)("b",{children:"performance"}),". The Premium RxStorage implementations have a better performance so reading and writing data is much faster especially on low-end devices. You can find a performance comparison"," ",(0,f.jsx)("a",{href:"/rx-storage-performance.html",target:"_blank",children:"here"}),". Also there are additional Premium Plugins that can be used to further optimize the performance of your application like the"," ",(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})," ","or the"," ",(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"Sharding"})," ","plugin."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not for free?"}),"The development of RxDB started in 2016 and after all these years it became clear that big implementation and improvement steps will not be done by the RxDB community. While the community submits valuable pull requests, they are mostly small improvements or bugfixes for specific edge case. Big rewrites and optimizations that require a big effort have only be done by the RxDB maintainer.",(0,f.jsx)("br",{}),"Selling RxDB Premium ensures that there will be always an incentive for someone to add features, keep everything up to date and to further improve and optimize the codebase. This gives the user the confidence that RxDB is a ",(0,f.jsx)("b",{children:"future proof"})," tech stack to build on which lets RxDB stand out compared to similar technologies."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is there no free trial period?"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:"RxDB is written in JavaScript and the code of the Premium Plugins does not contain any tracking or measurement code that would send information from your application to our servers in production mode. As soon as someone has the code on his computer, the maintainer has no chance to really ensure that after a free trial period the code is no longer used and deleted."}),(0,f.jsxs)("li",{children:["Before you can use the Premium Plugins you have to debate and sign a license agreement with the maintainer. This is a sophisticated process that creates overhead which distracts the maintainer from writing RxDB code. So handling trial period users is just not manageable. For this reason there is also no monthly subscriptions. Premium access must be paid ",(0,f.jsx)("b",{children:"per year"}),"."]})]})]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Why is it not cheaper?"}),"The price of the Premium Plugins is chosen in way that ensures that there can be always one person that develops RxDB ",(0,f.jsx)("b",{children:"full time"}),". Compared to other JavaScript frameworks and developer tools, RxDB satisfies an edge use case for people that want to store data inside of their application on the users device. Most web developers do not need to do that and rely on the traditional client-server stack. So RxDB cannot be sold to that many people which increases the price."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I install/build the premium plugins in my CI?"}),(0,f.jsx)("b",{children:"Yes"})," you can safely install and use the Premium Plugins in your CI without additional payment."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I get a discount?"}),"Discounts are provided for people that have made a significant contribution to RxDB or one of RxDB's dependencies or to the Open Source Community overall. Also for private personal projects there is the option to solve one of the",(0,f.jsx)("a",{href:"https://github.com/pubkey/rxdb/blob/master/orga/premium-tasks.md",target:"_blank",children:"Premium Tasks"}),"to get 3 years access to the Premium Plugins."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Which payment methods are accepted?"}),(0,f.jsx)("b",{children:"Stripe.com"})," is used as payment processor so most known payment options like credit card, PayPal, SEPA transfer and others are available. A list of all options can be found"," ",(0,f.jsx)("a",{href:"https://stripe.com/docs/payments/payment-methods/overview",title:"stripe payment options",target:"_blank",children:"here"}),"."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Can I still use the premium plugins when the license has expired?"}),"By default you are not allowed to use the premium plugins after the license has expired and you will no longer be able to install them. But you can choose the ",(0,f.jsx)("b",{children:"Perpetual license"})," option. With the perpetual license option, you can still use the plugins even after the license is expired. But you will no longer get any updates from newer RxDB versions."]}),(0,f.jsxs)("details",{children:[(0,f.jsx)("summary",{children:"Is there any tracking code inside of the premium plugins?"}),'No, the premium plugins themself do not contain any tracking code. When you build your application with RxDB and deploy it to production, it will not make requests to any RxDB server. But when you run "npm install" with the premium package there will be some metadata send from your developers machine to RxDB.']})]})}),(0,f.jsxs)("div",{className:"block",children:[(0,f.jsxs)("div",{className:"content centered",children:[(0,f.jsxs)("h2",{children:["RxDB Premium ",(0,f.jsx)("b",{className:"underline",children:"Price Calculator"})]}),(0,f.jsx)("div",{className:"price-calculator",children:(0,f.jsxs)("div",{className:"price-calculator-inner",children:[(0,f.jsxs)("form",{id:"price-calculator-form",children:[(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"home-country",children:"Company Home Country:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{list:"home-country",name:"home-country",pattern:"[A-Za-z \\-]{2,}",required:!0,style:{width:"100%",maxWidth:240},autoComplete:"off"}),(0,f.jsx)("datalist",{id:"home-country",children:l.sort(((e,t)=>e.code>=t.code?1:-1)).map(((e,t)=>(0,f.jsx)("option",{value:e.name,children:e.name},t)))})]})]}),(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"company-size",children:"Company Size:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsx)("input",{type:"number",name:"company-size",min:1,max:1e6,required:!0,onKeyDown:()=>{const e=(0,o.Is)(event);return 69!==e.keyCode&&189!==e.keyCode&&190!==e.keyCode}}),(0,f.jsx)("div",{className:"suffix",children:"employee(s)"})]})]}),(0,f.jsxs)("div",{className:"field",children:[(0,f.jsx)("label",{htmlFor:"project-amount",children:"Project Amount:"}),(0,f.jsxs)("div",{className:"input",children:[(0,f.jsxs)("select",{name:"project-amount",id:"project-amount",required:!0,defaultValue:1,children:[(0,f.jsx)("option",{value:1,children:"1"}),(0,f.jsx)("option",{value:2,children:"2"}),(0,f.jsx)("option",{value:"infinity",children:"Infinity"})]}),(0,f.jsx)("div",{className:"suffix",children:"project(s)"})]})]}),(0,f.jsxs)("div",{className:"packages",children:[(0,f.jsx)("h3",{children:"Packages:"}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-browser",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Browser Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-opfs.html",target:"_blank",children:"RxStorage OPFS"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-indexeddb.html",target:"_blank",children:"RxStorage IndexedDB"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-worker.html",target:"_blank",children:"RxStorage Worker"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/encryption.html",target:"_blank",children:"WebCrypto Encryption"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-native",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Native Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sqlite.html",target:"_blank",children:"RxStorage SQLite"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-filesystem-node.html",target:"_blank",children:"RxStorage Filesystem Node"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-performance",type:"checkbox",className:"package-checkbox",defaultChecked:!0}),(0,f.jsx)("h4",{children:"Performance Package"}),(0,f.jsxs)("ul",{children:[(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-sharding.html",target:"_blank",children:"RxStorage Sharding"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-memory-synced.html",target:"_blank",children:"RxStorage Memory Synced"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/query-optimizer.html",target:"_blank",children:"Query Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:"RxStorage Localstorage Meta Optimizer"})}),(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/rx-storage-shared-worker.html",target:"_blank",children:"RxStorage Shared Worker"})})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-utilities",type:"checkbox",className:"package-checkbox",defaultChecked:!0,disabled:!0}),(0,f.jsxs)("h4",{children:["Utilities Package ",(0,f.jsx)("b",{children:"always included"})]}),(0,f.jsx)("ul",{children:(0,f.jsx)("li",{children:(0,f.jsx)("a",{href:"/logger.html",target:"_blank",children:"Logger"})})})]})}),(0,f.jsx)("div",{className:"clear"}),(0,f.jsx)("h3",{children:"Other Options:"}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-sourcecode",type:"checkbox",className:"package-checkbox"}),(0,f.jsx)("h4",{children:"Source Code access"}),(0,f.jsxs)("p",{children:["Get read access to the unminified plain source code of all purchased packages.",(0,f.jsx)("br",{})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("input",{name:"package-perpetual",type:"checkbox",className:"package-checkbox"}),(0,f.jsx)("h4",{children:"Perpetual license"}),(0,f.jsxs)("p",{children:["With the perpetual license option, you can still use the plugins even after the license is expired. But you will no longer get any updates from newer RxDB versions.",(0,f.jsx)("br",{})]})]})}),(0,f.jsx)("div",{className:"package bg-gradient-left-top",children:(0,f.jsxs)("div",{className:"package-inner",children:[(0,f.jsx)("h4",{children:"Increase license period"}),(0,f.jsxs)("p",{children:["The default license period is one year. We can do a longer license period to safe time on both sides by not having to go through the licensing process each single year. By choosing a license period of 2 years, you get a 10% discount. With a 3 year license the discount is 20%.",(0,f.jsx)("br",{})]}),(0,f.jsxs)("div",{className:"field",children:[(0,f.jsxs)("div",{className:"input",style:{float:"left",width:"100%"},children:[(0,f.jsx)("div",{className:"prefix",children:"License period "}),(0,f.jsxs)("select",{name:"license-period",id:"license-period",required:!0,defaultValue:1,children:[(0,f.jsx)("option",{value:1,children:"1"}),(0,f.jsx)("option",{value:2,children:"2 (10% discount)"}),(0,f.jsx)("option",{value:3,children:"3 (20% discount)"})]}),(0,f.jsx)("div",{className:"suffix",children:"year(s)"})]}),(0,f.jsx)("div",{className:"clear"})]}),(0,f.jsx)("p",{})]})}),(0,f.jsx)("div",{className:"clear"})]}),(0,f.jsx)("div",{className:"button",id:"price-calculator-submit",onClick:async()=>{(0,d.X)("calculate_premium_price",3);const e=(0,o.Is)(document.getElementById("price-calculator-form"));if(!e.reportValidity())return void console.log("form not valid");const t=new FormData(e),r=Object.fromEntries(t.entries());console.log("formData:"),console.dir(r);const a=l.find((e=>e.name.toLowerCase()===r["home-country"].toLowerCase()));if(!a)return;const n=Object.entries(r).filter((e=>{let[t,r]=e;return t.startsWith("package-")})).map((e=>{let[t]=e;return(0,c.SI)(t.split("-"))})),i=await(0,m.N8)();await i.upsertLocal(v,{companySize:r["company-size"],projectAmount:r["project-amount"],licensePeriod:r["license-period"],homeCountry:a.name,packages:n});const s={companySize:r["company-size"],teamSize:r["developer-count"],projectAmount:r["project-amount"],licensePeriod:parseInt(r["license-period"],10),homeCountryCode:a.code,packages:n},p=function(e){if(console.log("calculatePrice:"),console.dir(e),"number"!=typeof e.licensePeriod)throw new Error("not a number "+typeof e.licensePeriod);const t=(0,o.Is)(l.find((t=>t.code===e.homeCountryCode))).salary;let r=0;e.packages.forEach((e=>{const t=u[e];r+=t})),console.log("aimInPercent: "+r);let a=350+1.4*t*(r/100);if(2===e.packages.length&&(a*=.9),e.packages.length>2&&(a*=.85),e.companySize>1){let t=1+Math.pow(1*e.companySize-1,.95)/100*4.5;const r=6;t>r&&(t=r),console.log("input.companySize "+e.companySize+" - "+t),a*=t}if(e.packages.includes("sourcecode")){a*=1.75;const e=1520;a{console.log("setPrice:"),console.dir(t),e.innerHTML=Math.ceil(t).toString()+" € (EUR)",e.href=function(e){return"https://www.xe.com/en/currencyconverter/convert/?Amount="+e+"&From=EUR&To=USD"}(Math.ceil(t))},w=p.totalPrice/s.licensePeriod;x(y,"infinity"!==s.projectAmount?w/parseInt(s.projectAmount,10)/12:0),x(g,w),x(b,p.totalPrice),f.style.display="block"},children:"Estimate Price"})]}),(0,f.jsxs)("div",{id:"price-calculator-result",style:{display:"none"},children:[(0,f.jsx)("hr",{}),(0,f.jsx)("h4",{children:"Estimated Price:"}),(0,f.jsx)("table",{children:(0,f.jsxs)("tbody",{children:[(0,f.jsxs)("tr",{children:[(0,f.jsx)("th",{children:"Price Per Project per Month"}),(0,f.jsx)("td",{children:(0,f.jsx)("a",{id:"total-per-project-per-month",target:"_blank",rel:"nofollow noopener noreferrer",title:"Click to convert to other currency",href:"#",children:"XX \u20ac"})})]}),(0,f.jsxs)("tr",{children:[(0,f.jsx)("th",{children:"Total Price per Year"}),(0,f.jsx)("td",{children:(0,f.jsx)("a",{id:"total-per-year",target:"_blank",rel:"nofollow noopener noreferrer",title:"Click to convert to other currency",href:"#",children:"XX \u20ac"})})]}),(0,f.jsxs)("tr",{children:[(0,f.jsx)("th",{children:"Total Price"}),(0,f.jsx)("td",{children:(0,f.jsx)("a",{id:"total-price",target:"_blank",rel:"nofollow noopener noreferrer",title:"Click to convert to other currency",href:"#",children:"XX \u20ac"})})]})]})}),(0,f.jsxs)("div",{className:"proceed-hint",children:["Fill out",(0,f.jsxs)("a",{href:"#premium-request-form-block",children:[" ",(0,f.jsx)("b",{children:"this form"})," "]}),"to proceed."]})]})]})})]}),(0,f.jsx)("div",{className:"block dark",id:"premium-request-form-block",children:(0,f.jsxs)("div",{className:"content centered premium-request",children:[(0,f.jsxs)("h2",{children:["Request Premium ",(0,f.jsx)("b",{className:"underline",children:"Form"})]}),(0,f.jsx)("p",{}),(0,f.jsx)(y,{fallback:(0,f.jsx)("span",{children:"Loading form iframe..."}),children:()=>(0,f.jsxs)("iframe",{id:"request-premium-form",src:"https://webforms.pipedrive.com/f/6qflURDWONiPpj67lpG6r45n8feakrtS2AqMRcBf1EuCPRvNcXWdvNH2unFm5EpjW3",children:["Your browser doesn't support iframes, ",(0,f.jsx)("a",{href:"https://webforms.pipedrive.com/f/6qflURDWONiPpj67lpG6r45n8feakrtS2AqMRcBf1EuCPRvNcXWdvNH2unFm5EpjW3",target:"_blank",rel:"nofollow",children:"go here"})]})})]})})]})]})})]})}function b(e,t){if(void 0===t)return;const r=document.querySelector("[name="+e+"]");r&&(r.type&&"checkbox"===r.type?r.checked=t:r.value=t)}},6087:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function i(e){return Array.isArray(e)}function s(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;ai,Nb:()=>l,S7:()=>s,SI:()=>a,gu:()=>c,qo:()=>n,r0:()=>o})},7400:(e,t,r)=>{function a(e){if(!e)throw new Error("ensureNotFalsy() is falsy");return e}r.d(t,{Is:()=>a,kv:()=>n});var n={bufferSize:1,refCount:!0}},4419:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$Y:()=>o,C2:()=>u,Y3:()=>a,YB:()=>n,Ze:()=>h,kZ:()=>i,m5:()=>s,y$:()=>c});Promise.resolve(!0);var i=Promise.resolve(!1),s=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var l=o;function u(e){return void 0===e&&(e=void 0),l=l.then((()=>c(e)))}function h(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},984:(e,t,r)=>{r.d(t,{z:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/0e945c41.df3b3c6c.js b/docs/assets/js/0e945c41.df3b3c6c.js new file mode 100644 index 00000000000..e16fbc5a120 --- /dev/null +++ b/docs/assets/js/0e945c41.df3b3c6c.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[8280],{1413:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>a,contentTitle:()=>o,default:()=>p,frontMatter:()=>c,metadata:()=>s,toc:()=>l});var r=t(5893),i=t(1151);const c={},o="RxDB Server Replication",s={id:"replication-server",title:"RxDB Server Replication",description:"The Server Replication Plugin connects to the replication endpoint of an RxDB Server and replicates data between the client and the server.",source:"@site/docs/replication-server.md",sourceDirName:".",slug:"/replication-server",permalink:"/replication-server",draft:!1,unlisted:!1,editUrl:"https://github.com/pubkey/rxdb/tree/master/docs-src/docs/replication-server.md",tags:[],version:"current",frontMatter:{}},a={},l=[];function d(e){const n={a:"a",em:"em",h1:"h1",li:"li",p:"p",ul:"ul",...(0,i.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(n.h1,{id:"rxdb-server-replication",children:"RxDB Server Replication"}),"\n",(0,r.jsxs)(n.p,{children:["The ",(0,r.jsx)(n.em,{children:"Server Replication Plugin"})," connects to the replication endpoint of an ",(0,r.jsx)(n.a,{href:"/server",children:"RxDB Server"})," and replicates data between the client and the server."]}),"\n",(0,r.jsxs)(n.ul,{children:["\n",(0,r.jsx)(n.li,{children:"outdatedClient$"}),"\n",(0,r.jsx)(n.li,{children:"unauthorized$ - setHeaders()"}),"\n",(0,r.jsx)(n.li,{children:"forbidden$"}),"\n",(0,r.jsx)(n.li,{children:"custom EventSource library"}),"\n"]})]})}function p(e={}){const{wrapper:n}={...(0,i.a)(),...e.components};return n?(0,r.jsx)(n,{...e,children:(0,r.jsx)(d,{...e})}):d(e)}},1151:(e,n,t)=>{t.d(n,{Z:()=>s,a:()=>o});var r=t(7294);const i={},c=r.createContext(i);function o(e){const n=r.useContext(c);return r.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function s(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(i):e.components||i:o(e.components),r.createElement(c.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/docs/assets/js/1df93b7f.1ca6466d.js b/docs/assets/js/1df93b7f.1ca6466d.js deleted file mode 100644 index 4aafb68577b..00000000000 --- a/docs/assets/js/1df93b7f.1ca6466d.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[3237],{5921:(e,t,r)=>{r.d(t,{O9:()=>zr,N8:()=>Hr,dZ:()=>Fr});var a=r(8061);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function s(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function i(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var s in t)n[s]=e(t[s]);return n};function l(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var u=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},h=new Set(["__proto__","prototype","constructor"]),d=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var s of e)switch(s){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=s),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=s;break}if(h.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=s;break}if("property"===a){if(h.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!d.has(s))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=s}switch(n&&(r+="\\"),a){case"property":if(h.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function p(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function f(e,t){if(p(e,t))throw new Error("Cannot use string index")}function v(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!u(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function k(e,t,r){return"RxError ("+t+"):\n"+e+"\n"+function(e){var t="";return 0===Object.keys(e).length?t:(t+="Given parameters: {\n",t+=Object.keys(e).map((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var _=function(e){function t(t,r,a){var n;void 0===a&&(a={});var s=k(r,t,a);return(n=e.call(this,s)||this).code=t,n.message=s,n.parameters=a,n.rxdb=!0,n}return(0,x.Z)(t,e),t.prototype.toString=function(){return this.message},(0,b.Z)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,w.Z)(Error)),D=function(e){function t(t,r,a){var n;void 0===a&&(a={});var s=k(r,t,a);return(n=e.call(this,s)||this).code=t,n.message=s,n.parameters=a,n.rxdb=!0,n}return(0,x.Z)(t,e),t.prototype.toString=function(){return this.message},(0,b.Z)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,w.Z)(TypeError));function N(e,t){return new _(e,j.tunnelErrorMessage(e),t)}function I(e,t){return new D(e,j.tunnelErrorMessage(e),t)}function E(e){return!(!e||409!==e.status)&&e}var C={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var R=/\./g,O="abcdefghijklmnopqrstuvwxyz";function S(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=v(t,e);if(void 0===r)throw N("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function Q(e){var t=A((e=i(e)).primaryKey);e.properties=i(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=W,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=F(e);(0,y.gu)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,y.AD)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]);var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var W={type:"object",properties:{lwt:{type:"number",minimum:$,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function F(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}var H="docs",z="changes",K="attachments",U="dexie",Z=new Map,J=new Map;var V="__";function X(e){var t=e.split(".");if(t.length>1)return t.map((e=>X(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return V+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(V)?"|"+e.substring(V.length):e}function G(e,t){return t?(t=te(t=i(t)),e.forEach((e=>{var r=v(t,e);g(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=i(t)),e.forEach((e=>{var r=v(t,e);g(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[X(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=A(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,y.qo)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>X(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function se(e,t){return e+"||"+t}function ie(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,y.qo)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===q(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,y.Nb)(r)):r}var oe=r(6974),ce=r(984),le=r(7400),ue=String.fromCharCode(65535),he=Number.MIN_SAFE_INTEGER;function de(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),s=new Set;Object.keys(r).forEach((t=>{var a=q(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&s.add(t)}));var i,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!s.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,l=!0,u=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],s={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);s=Object.assign(s,r)}})):s={startKey:l?he:ue,endKey:a?ue:he,inclusiveStart:!0,inclusiveEnd:!0};return void 0===s.startKey&&(s.startKey=he),void 0===s.endKey&&(s.endKey=ue),void 0===s.inclusiveStart&&(s.inclusiveStart=!0),void 0===s.inclusiveEnd&&(s.inclusiveEnd=!0),l&&!s.inclusiveStart&&(l=!1),a&&!s.inclusiveEnd&&(a=!1),s})),h=u.map((e=>e.startKey)),d=u.map((e=>e.endKey)),m={index:e,startKeys:h,endKeys:d,inclusiveEnd:a,inclusiveStart:l,sortSatisfiedByIndex:!n&&o===e.filter((e=>!s.has(e))).join(","),selectorSatisfiedByIndex:ve(e,t.selector,h,d)},p=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},s=10,i=(0,y.r0)(r.startKeys,(e=>e!==he&&e!==ue));n(i*s);var o=(0,y.r0)(r.startKeys,(e=>e!==ue&&e!==he));n(o*s);var c=(0,y.r0)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*s*1.5);var l=r.sortSatisfiedByIndex?5:0;return n(l),a}(0,0,m);(p>=c||t.index)&&(c=p,i=m)})),!i)throw N("SNH",{query:t});return i}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),pe=new Set(["$eq","$gt","$gte"]),fe=new Set(["$eq","$lt","$lte"]);function ve(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var s=[],i=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var l=Object.keys(c).filter((e=>pe.has(e)));if(l.length>1)return!1;var u=l[0];if(u&&i.add(o),"$eq"!==u){if(s.length>0)return!1;s.push(u)}}var h=[],d=new Set;for(var[m,p]of Object.entries(t)){if(!e.includes(m))return!1;var f=Object.keys(p).filter((e=>fe.has(e)));if(f.length>1)return!1;var v=f[0];if(v&&d.add(m),"$eq"!==v){if(h.length>0)return!1;h.push(v)}}var g=0;for(var y of e){for(var b of[i,d]){if(!b.has(y)&&b.size>0)return!1;b.delete(y)}if(r[g]!==a[g]&&i.size>0&&d.size>0)return!1;g++}return!0}var ge=r(6250),ye=r(7761),be=r(7132),xe=r(6496),we=r(6851),je=r(3516),ke=r(8039),_e=r(5308),De=r(2106),Ne=!1;function Ie(e){return Ne||((0,ye.Qs)(ye.$M.PIPELINE,{$sort:xe.E3,$project:xe.FM}),(0,ye.Qs)(ye.$M.QUERY,{$and:we.h$,$eq:je.l3,$elemMatch:_e.rr,$exists:De.G,$gt:je.ok,$gte:je.m9,$in:je.FI,$lt:je.Ty,$lte:je.HG,$ne:je.ny,$nin:je.IS,$mod:ke.JD,$nor:we.ps,$not:we._w,$or:we.Ko,$regex:ke.GO,$size:_e.QH,$type:De.e}),Ne=!0),new be.A(e)}function Ee(e,t){var r=A(e.primaryKey);t=i(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,y.qo)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var s=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&s.add(t)}));var o,l=-1;e.indexes.forEach((e=>{var t=(0,y.AD)(e)?e:[e],r=t.findIndex((e=>!s.has(e)));r>0&&r>l&&(l=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ce(e,t){if(!t.sort)throw N("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,s=Object.keys(e)[0],i=Object.values(e)[0];r.push({key:s,direction:i,getValueFn:(t=s,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Oe(e){return e===he?-1/0:e}function Se(e,t,r){return e.includes(t)?r===ue||!0===r?"1":"0":r}function Pe(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Se(e,n,r)})).map(Oe),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Se(e,n,r)})).map(Oe);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Be(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,s=n+(a.limit?a.limit:1/0),i=t.queryPlan,o=!1;i.selectorSatisfiedByIndex||(o=Re(e.schema,t.query));var c=Pe(r.booleanIndexes,i,r.dexieDb._options.IDBKeyRange),l=i.index,u=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(H);t="["+l.map((e=>X(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||u.push(n),i.sortSatisfiedByIndex&&u.length===s?e():a.continue()}else e()}}))})),!i.sortSatisfiedByIndex){var h=Ce(e.schema,t.query);u=u.sort(h)}return{documents:u=u.slice(n,s)}}function $e(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Te(e){return parseInt(e.split("-")[0],10)}function qe(e,t){var r=t?t._rev:null;return(r?$e(r).height:0)+1+"-"+e}var Me="_rxdb_internal";async function Ae(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function Qe(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:j.deepFreezeWhenDevMode(a),previousDocumentData:j.deepFreezeWhenDevMode(n)}}function We(e,t,r,a){if(a)throw 409===a.status?N("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?N("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function Fe(e){return{previous:e.previous,document:He(e.document)}}function He(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=i(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,s,i;t._attachments[r]=(i=(n=a).data)?{length:(s=i,atob(s).length),digest:n.digest,type:n.type}:n})),t}function ze(e){var t=i(e);return t._meta=i(e._meta),t}function Ke(e,t,r){j.deepFreezeWhenDevMode(r);var a=A(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,s){var o=n.map((n=>function(n){var s=i(n.document);if(s._meta=i(s._meta),j.isDevMode()){s=M(a,r,s);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw N("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw N("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return s._meta.lwt=(0,ce.z)(),s._rev=qe(e.token,n.previous),{document:s,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,s))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,le.Is)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var i=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:qe(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(i,s))).then((e=>((0,y.gu)(a.error,e.error),(0,y.gu)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,le.Is)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=i(Object.assign({},e.output.documentData,{_meta:T(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ue=r(5677),Ze=r(3981),Je=new Map;function Ve(e,t){var r=Je.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Je.delete(e),r.bc.close()):void 0}function Xe(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Je.get(t);return n||(n={bc:new Ze.g0(["RxDB:",e,r].join("|")),refs:new Set},Je.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),s=new oe.x,i=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&s.next(r.eventBulk)};n.addEventListener("message",i);var o=r.changeStream(),c=!1,l=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return s.asObservable().pipe((0,Ue.b)(o))};var u=r.close.bind(r);r.close=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",i),a||await Ve(t.databaseInstanceToken,r),u()};var h=r.remove.bind(r);r.remove=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",i),a||await Ve(t.databaseInstanceToken,r),h()}}}var Ye=(0,ce.z)(),Ge=function(){function e(e,t,r,a,n,s,i){this.changes$=new oe.x,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=s,this.settings=i,this.primaryPath=A(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw N("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},s=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var i=new Map;(await ne(this.internals,s)).forEach((e=>{var t=e;return t&&i.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,s,i){for(var o,c=!!e.schema.attachments,l=[],u=[],h=[],d={id:S(10),events:[],checkpoint:null,context:n,startTime:(0,ce.z)(),endTime:0},m=d.events,p=[],f=[],v=[],g=r.size>0,y=a.length,b=function(){var e,n=a[x],d=n.document,y=n.previous,b=d[t],w=d._deleted,j=y&&y._deleted,k=void 0;if(g&&(k=r.get(b)),k){var _=k._rev;if(!y||y&&_!==y._rev){var D={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:k};return h.push(D),1}var I=c?Fe(n):n;c&&(w?y&&Object.keys(y._attachments).forEach((e=>{f.push({documentId:b,attachmentId:e,digest:(0,le.Is)(y)._attachments[e].digest})})):(Object.entries(d._attachments).find((t=>{let[r,a]=t;return(y?y._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:k,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(d._attachments).forEach((e=>{let[t,r]=e;var a=y?y._attachments[t]:void 0;if(a){var n=I.document._attachments[t].digest;r.data&&a.digest!==n&&v.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else p.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?h.push(e):(c?(u.push(Fe(I)),i&&i(d)):(u.push(I),i&&i(d)),o=I);var E=null,C=null,R=null;if(j&&!w)R="INSERT",E=c?He(d):d;else if(!y||j||w){if(!w)throw N("SNH",{args:{writeRow:n}});R="DELETE",E=(0,le.Is)(d),C=y}else R="UPDATE",E=c?He(d):d,C=y;var O={documentId:b,documentData:E,previousDocumentData:C,operation:R};m.push(O)}else{var S=!!w;if(c&&Object.entries(d._attachments).forEach((t=>{let[r,a]=t;a.data?p.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},h.push(e))})),e||(c?(l.push(Fe(n)),s&&s(d)):(l.push(n),s&&s(d)),o=n),!S){var P={documentId:b,operation:"INSERT",documentData:c?He(d):d,previousDocumentData:c&&y?He(y):y};m.push(P)}}},x=0;x{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>G(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:se(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:se(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>se(e.documentId,e.attachmentId))))})),(r=(0,le.Is)(r)).eventBulk.events.length>0){var i=(0,le.Is)(r.newestRow).document;r.eventBulk.checkpoint={id:i[this.primaryPath],lwt:i._meta.lwt},r.eventBulk.endTime=(0,ce.z)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Be(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,s=Pe(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),i=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(H);t="["+n.map((e=>X(e))).join("+")+"]";var a=r.index(t).count(s);i=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),i}(this,e);return{count:t,mode:"fast"}}return{count:(await Be(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.z)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=se(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=J.get(e)-1;0===r?(t.dexieDb.close(),J.delete(e)):J.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.x},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=s(Z,o,(()=>{var e=(async()=>{var e=i(r);e.autoOpen=!1;var t=new a.U(o,e),s={[H]:ae(n),[z]:"++sequence, id",[K]:"id"};return t.version(1).stores(s),await t.open(),{dexieDb:t,dexieTable:t[H],dexieAttachmentsTable:t[K],booleanIndexes:ie(n)}})();return Z.set(o,c),J.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Ge(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Xe(U,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.3.0",at=function(){function e(e){this.name=U,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw N("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw N("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw N("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var s=n[a];if(!nt(e[s],t[s]))return!1}return!0}return e!=e&&t!=t}var st={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function it(e,t){st[e]&&st[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(st[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,y.AD)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=A(this.jsonSchema.primaryKey),this.finalFields=F(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw N("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=q(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),l(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.Z)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),l(this,"defaultValues",e)}},{key:"hash",get:function(){return l(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function lt(e,t,r){void 0===r&&(r=!0),r&&it("preCreateRxSchema",e);var a=Q(e);a=function(e){return o(e,!0)}(a),j.deepFreezeWhenDevMode(a);var n=new ct(a,t);return it("createRxSchema",n),n}var ut=r(598),ht=r(6621),dt=r(6728),mt=r(6005),pt=r(7570),ft=r(4419);function vt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=P(e)})),r+="Plugin",new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { "+r+" } from 'rxdb/plugins/"+e+"';\n addRxPlugin("+r+");\n ")}function gt(e){return e.documentData?e.documentData:e.previousDocumentData}var yt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=s(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var s={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,le.Is)(a).push(s),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,s,i,o=(n=a.map((e=>e.lastKnownDocumentState)),s=n[0],i=$e(s._rev).height,n.forEach((e=>{var t=$e(e._rev).height;t>i&&(s=e,i=t)})),s),l=o;for(var u of a)try{l=await u.modifier(c(l))}catch(h){u.reject(h),u.reject=()=>{},u.resolve=()=>{}}try{await this.preWrite(l,o)}catch(h){return void a.forEach((e=>e.reject(h)))}e.push({previous:o,document:l})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,i=n(t,a),o=E(e);if(o){var c=s(this.queueByDocId,a,(()=>[]));i.reverse().forEach((e=>{e.lastKnownDocumentState=(0,le.Is)(o.documentInDb),(0,le.Is)(c).unshift(e)}))}else{var l=N("COL20",{name:C[(r=e).status],document:r.documentId,writeError:r});i.forEach((e=>e.reject(l)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var xt={get primaryPath(){if(this.isInstanceOfRxDocument)return this.collection.schema.primaryPath},get primary(){var e=this;if(e.isInstanceOfRxDocument)return e._data[e.primaryPath]},get revision(){if(this.isInstanceOfRxDocument)return this._data._rev},get deleted$(){if(this.isInstanceOfRxDocument)return this.$.pipe((0,ut.U)((e=>e._data._deleted)))},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,ht.h)((e=>!e.isLocal)),(0,ht.h)((e=>e.documentId===this.primary)),(0,ut.U)((e=>gt(e))),(0,dt.O)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.x)(((e,t)=>e._rev===t._rev)),(0,ut.U)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,pt.d)(le.kv))},get$(e){if(j.isDevMode()){if(e.includes(".item."))throw N("DOC1",{path:e});if(e===this.primaryPath)throw N("DOC2");if(this.collection.schema.finalFields.includes(e))throw N("DOC3",{path:e});if(!q(this.collection.schema.jsonSchema,e))throw N("DOC4",{path:e})}return this.$.pipe((0,ut.U)((t=>v(t,e))),(0,mt.x)())},populate(e){var t=q(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return ft.m5;if(!t)throw N("DOC5",{path:e});if(!t.ref)throw N("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw N("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return s(this._propertyCache,e,(()=>{var t=v(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return j.deepFreezeWhenDevMode(t);var r=this;return new Proxy(i(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if("$"===n){var s=a.slice(0,-1);return r.get$(B(e+"."+s))}if("_"===n){var i=a.slice(0,-1);return r.populate(B(e+"."+i))}return r.get(B(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return j.deepFreezeWhenDevMode(this._data);var t=i(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,j.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw vt("update")},incrementalUpdate(e){throw vt("update")},updateCRDT(e){throw vt("crdt")},putAttachment(){throw vt("attachments")},getAttachment(){throw vt("attachments")},allAttachments(){throw vt("attachments")},get allAttachments$(){throw vt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=i(e),this._data._deleted)throw N("DOC11",{id:this.primary,document:this});await jt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return We(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(N("DOC13",{document:this,id:this.primary}));var t,r=i(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return We(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw N("DOC14")}};function wt(e){void 0===e&&(e=xt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function jt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),j.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var kt=r(10),_t=r(6871),Dt=r(3028),Nt=r(1556),It=r(8456);function Et(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Ct=new WeakMap;function Rt(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return s(Ct,e,(()=>{var t=e.collection,r=Ee(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ce(t.schema.jsonSchema,r),s=Re(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:Et(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>s({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,le.Is)(e._result).docsData.slice(0),n=(0,le.Is)(e._result).docsDataMap,i=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:j.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(y.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},s=(0,It.Rf)(t);return"runFullQueryAgain"===s||("doNothing"!==s?(i=!0,(0,It.wu)(s,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:i,newResults:a}}var Ot=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return s(this._map,t,(()=>e))},e}();function St(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function Pt(e){return e.refCount$.observers.length}var Bt,$t,Tt=(Bt=100,$t=3e4,(e,t)=>{if(!(t._map.size0||(0===s._lastEnsureEqual&&s._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,i).forEach((e=>St(t,e)))}}),qt=new WeakSet;var Mt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=gt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.Z)(e,[{key:"getCachedRxDocument",get:function(){return l(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=j.deepFreezeWhenDevMode,i=e.documentCreator,o=o=>{var c=o[t],l=Te(o._rev),u=s(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),h=u.byRev,d=h.get(l),m=d?d.deref():void 0;return m||(o=n(o),m=i(o),h.set(l,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,ft.y$)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Te(e.revision)})})))}))))),m};return o}(this))}}]),e}();function At(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Qt=function(){function e(e,t,r){this.time=(0,ce.z)(),this.collection=e,this.count=r,this.documents=At(this.collection._docCache,t)}return(0,b.Z)(e,[{key:"docsData",get:function(){return l(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),l(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Qt(this.collection,e,e.length);this._result=t}else this._result=new Qt(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.z)(),"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 N("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,le.Is)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var s=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,y.gu)(t,n)}}else{var s=e.isFindOneByIdQuery,i=e.collection._docCache.getLatestDocumentDataIfExists(s);if(!i){var o=await r.storageInstance.findDocumentsById([s],!1);o[0]&&(i=o[0])}i&&!i._deleted&&t.push(i)}else{var c=e.getPreparedQuery(),l=await r.storageInstance.query(c);t=l.documents}return t}(this);return s.then((e=>(this._lastExecEnd=(0,ce.z)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw N("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Kt(this).then((()=>(0,_t.z)(this.$))).then((t=>{if(!t&&e)throw N("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Ee(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),it("prePrepareQuery",e);var t=Ut(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw vt("update")},t.where=function(e){throw vt("query-builder")},t.sort=function(e){throw vt("query-builder")},t.skip=function(e){throw vt("query-builder")},t.limit=function(e){throw vt("query-builder")},(0,b.Z)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,ht.h)((e=>!e.isLocal)),(0,dt.O)(null),(0,Nt.z)((()=>Kt(this))),(0,ut.U)((()=>this._result)),(0,pt.d)(le.kv),(0,mt.x)(((e,t)=>!(!e||e.time!==(0,le.Is)(t).time))),(0,ht.h)((e=>!!e)),(0,ut.U)((e=>{var t=(0,le.Is)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,Dt.T)(e,this.refCount$.pipe((0,ht.h)((()=>!1))))}return this._$}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return l(this,"queryMatcher",Re(0,Ee(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}]),e}();function Ht(e,t,r,a){it("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,s,i=new Ft(e,t,r,a);return i=(n=i).collection._queryCache.getByQuery(n),s=r,qt.has(s)||(qt.add(s),(0,ft.Y3)().then((()=>(0,ft.C2)(200))).then((()=>{s.destroyed||s.cacheReplacementPolicy(s,s._queryCache),qt.delete(s)}))),i}function zt(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Kt(e){return e.collection.database.destroyed||zt(e)?ft.kZ:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.z)(),e.collection.database.destroyed||zt(e))return ft.kZ;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var s=(0,le.Is)(e._result).count,i=s;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&i++,r&&!a&&i--})),i!==s&&(t=!0,e._setResultData(i))}else{var o=Rt(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var l=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!l.has(t)&&(l.add(t),!0)})),await Promise.all(c.map((async t=>{var i=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:s,devMode:j.isDevMode()});await i.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),i){var u=o.map((e=>{var t=ze(e);return t._deleted=!0,t._meta.lwt=(0,ce.z)(),t._rev=qe(r,e),{previous:e,document:t}}));await t.bulkWrite(u,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,ht.h)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var sr=new WeakMap;function ir(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,xt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((t=>{var r=Object.getOwnPropertyDescriptor(e,t),n=!0;(t.startsWith("_")||t.endsWith("_")||t.startsWith("$")||t.endsWith("$"))&&(n=!1),"function"==typeof r.value?Object.defineProperty(a,t,{get(){return r.value.bind(this)},enumerable:n,configurable:!1}):(r.enumerable=n,r.configurable=!1,r.writable&&(r.writable=!1),Object.defineProperty(a,t,r))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return it("createRxDocument",a),a}(function(e){return s(sr,e,(()=>wt(ir(e))))}(e),e,j.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),it("postCreateRxDocument",r),r}var cr=function(e,t){return nt(He(e.newDocumentState),He(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var lr=["pre","post"],ur=["insert","save","remove","create"],hr=!1,dr=function(){function e(e,t,r,a,n,s,i,o,c,l,u,h){void 0===n&&(n={}),void 0===s&&(s={}),void 0===i&&(i={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===l&&(l=Tt),void 0===u&&(u={}),void 0===h&&(h=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new Ot,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=s,this.methods=i,this.attachments=o,this.options=c,this.cacheReplacementPolicy=l,this.statics=u,this.conflictHandler=h,function(e){if(hr)return;hr=!0;var t=Object.getPrototypeOf(e);ur.forEach((e=>{lr.map((r=>{var a=r+P(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ke(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new yt(this.storageInstance,this.schema.primaryPath,((e,t)=>jt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,ht.h)((e=>e.collectionName===this.name)));this.$=t.pipe((0,Nt.z)((e=>e.events))),this.checkpoint$=t.pipe((0,ut.U)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new Mt(this.schema.primaryPath,this.$.pipe((0,ht.h)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>Qe(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),ft.$Y},t.cleanup=function(e){throw vt("cleanup")},t.migrationNeeded=function(){throw vt("migration")},t.getMigrationState=function(){throw vt("migration")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return We(this,e[this.schema.primaryPath],e,r),(0,le.Is)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),s=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),i=At(this._docCache,s.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(i.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:i,error:s.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],s=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),s.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=i(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),l=c.success.map((e=>e[t]));return await Promise.all(l.map((e=>this._runHooks("post","remove",s.get(e),r.get(e))))),{success:l.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw N("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),s=a.success.slice(0),i=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)i.push(e);else{var t=e.documentId,a=n(r,t),o=(0,le.Is)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),l=await c.incrementalModify((()=>a));s.push(l)}}))),{error:i,success:s}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return We(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw N("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=ft.$Y),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw N("COL5",{queryObj:e});return e||(e={selector:{}}),Ht("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw I("COL6",{queryObj:e});var t;if("string"==typeof e)t=Ht("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw N("QU6");(e=i(e)).limit=1,t=Ht("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Ht("count",e,this)},t.findByIds=function(e){return Ht("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw vt("json-dump")},t.importJSON=function(e){throw vt("json-dump")},t.insertCRDT=function(e){throw vt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw I("COL7",{key:t,when:e});if(!lr.includes(e))throw I("COL8",{key:t,when:e});if(!ur.includes(t))throw N("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw N("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),s=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][s].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return ft.$Y;var s=n.series.map((e=>()=>e(r,a)));return(0,ft.Ze)(s).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?ft.kZ:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.Z)(e,[{key:"insert$",get:function(){return this.$.pipe((0,ht.h)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,ht.h)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,ht.h)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();var mr=r(7782),pr=r(6753);var fr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,pr.JQ)(e))},vr=r(5898),gr=new Set,yr=function(){function e(e,t,r,a,n,s,i,o,c,l,u,h){void 0===i&&(i=!1),void 0===o&&(o={}),this.idleQueue=new mr.F,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.eventBulks$=new oe.x,this.observable$=this.eventBulks$.pipe((0,Nt.z)((e=>e.events))),this.storageToken=ft.kZ,this.storageTokenDocument=ft.kZ,this.emittedEventBulkIds=new vr.i(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=s,this.eventReduce=i,this.options=o,this.internalStore=c,this.hashFunction=l,this.cleanupPolicy=u,this.allowSlowCount=h,"pseudoInstance"!==this.name&&(this.internalStore=Ke(this.asRxDatabase,c,Vt),this.storageTokenDocument=async function(e){var t=S(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Jt,key:Gt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:T(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var s=(0,le.Is)(n.error[0]);if(s.isError&&E(s)){var i=s;if(c=i.documentInDb.data.rxdbVersion,l=e.rxdbVersion,!c||l.includes("beta")&&l!==c||c.split(".")[0]!==l.split(".")[0])throw N("DM5",{args:{database:e.name,databaseStateVersion:i.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==i.documentInDb.data.passwordHash)throw N("DB1",{passwordHash:r,existingPasswordHash:i.documentInDb.data.passwordHash});var o=i.documentInDb;return(0,le.Is)(o)}var c,l;throw s}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.$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 Ae(this.internalStore,Xt(tr(e,t),Zt));if(!r)throw N("SNH",{name:e,schema:t});var a=ze(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[s,o]=e;var c=s,l=o.schema;t[c]=l;var u=lt(l,this.hashFunction);if(r[c]=u,this.collections[s])throw N("DB3",{name:s});var h=tr(s,l),d={id:Xt(h,Zt),key:h,context:Zt,data:{name:c,schemaHash:await u.hash,schema:u.jsonSchema,version:u.version,connectedStorages:[]},_deleted:!1,_meta:T(),_rev:"",_attachments:{}};a.push({document:d});var m=Object.assign({},o,{name:c,schema:u,database:this}),p=i(o);p.database=this,p.name=s,it("preCreateRxCollection",p),m.conflictHandler=p.conflictHandler,n[c]=m})));var s=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(s.error.map((async e=>{if(409!==e.status)throw N("DB12",{database:this.name,writeError:e});var a=(0,le.Is)(e.documentInDb),n=a.data.name,s=r[n];if(a.data.schemaHash!==await s.hash)throw N("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await s.hash,previousSchema:a.data.schema,schema:(0,le.Is)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:s={},autoMigrate:i=!0,statics:o={},methods:c={},attachments:l={},options:u={},localDocuments:h=!1,cacheReplacementPolicy:d=Tt,conflictHandler:m=cr}=e;var p={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:j.isDevMode()};return it("preCreateRxStorageInstance",p),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,p).then((e=>{var p=new dr(t,r,a,e,n,s,c,l,u,d,o,m);return p.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(p,t,{get:()=>r.bind(p)})}));var e=ft.$Y;return i&&0!==p.schema.version&&(e=p.migratePromise()),e})).then((()=>(it("createRxCollection",{collection:p,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:s,methods:c,attachments:l,options:u,cacheReplacementPolicy:d,localDocuments:h,statics:o}}),p))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw vt("json-dump")},t.importJSON=function(e){throw vt("json-dump")},t.backup=function(e){throw vt("backup")},t.leaderElector=function(){throw vt("leader-election")},t.isLeader=function(){throw vt("leader-election")},t.waitForLeadership=function(){throw vt("leader-election")},t.migrationStates=function(){throw vt("migration")},t.destroy=async function(){return this.destroyed?ft.kZ:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?ft.kZ:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>gr.delete(this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=S(10),n=await br(a,t,e,{},!1,r),s=await Yt(n),i=new Set;s.forEach((e=>i.add(e.data.name)));var o=Array.from(i);return await Promise.all(o.map((s=>ar(t,n,a,e,s,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.Z)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function br(e,t,r,a,n,s){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Me,schema:Vt,options:a,multiInstance:n,password:s,devMode:j.isDevMode()})}function xr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s=!0,eventReduce:i=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:l,allowSlowCount:u=!1,localDocuments:h=!1,hashFunction:d=fr}=e;it("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s,eventReduce:i,ignoreDuplicate:o,options:c,localDocuments:h}),o||function(e){if(gr.has(e))throw N("DB8",{name:e,link:"https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate"})}(a),gr.add(a);var m=S(10);return br(m,t,a,r,s,n).catch((e=>{throw gr.delete(a),e})).then((e=>{var p=new yr(a,m,t,r,n,s,i,c,e,d,l,u);return ot("createRxDatabase",{database:p,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s,eventReduce:i,ignoreDuplicate:o,options:c,localDocuments:h}}).then((()=>p))}))}var wr={RxSchema:ct.prototype,RxDocument:xt,RxQuery:Ft.prototype,RxCollection:dr.prototype,RxDatabase:yr.prototype},jr=new Set,kr=new Set;var _r=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,x.Z)(t,e),t}(wt()),Dr={get isLocal(){return!0},get allAttachments$(){throw N("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(Cr,this.parent);return this.parent.$.pipe((0,ht.h)((e=>e.documentId===this.primary)),(0,ht.h)((e=>e.isLocal)),(0,ut.U)((e=>gt(e))),(0,dt.O)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.x)(((e,t)=>e._rev===t._rev)),(0,ut.U)((t=>e.docCache.getCachedRxDocument(t))),(0,pt.d)(le.kv))},getLatest(){var e=n(Cr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw I("LD2",{objPath:e});var t=v(this._data,e);return t=j.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,j.isDevMode()){if(e.includes(".item."))throw N("LD3",{objPath:e});if(e===this.primaryPath)throw N("LD4")}return this.$.pipe((0,ut.U)((e=>e._data)),(0,ut.U)((t=>v(t,e))),(0,mt.x)())},async incrementalModify(e){var t=await Or(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Or(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=i(e))._rev=r._rev}))},async remove(){var e=await Or(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:T(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Nr=!1,Ir=()=>{if(!Nr){Nr=!0;var e=xt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(Dr,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(Dr,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>Dr[e]=(e=>()=>{throw N("LD6",{functionName:e})})(e)))}};var Er=new WeakMap,Cr=new WeakMap;function Rr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await Sr(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ke(t,a,Tr);var n=new Mt("id",e.$.pipe((0,ht.h)((e=>e.isLocal))),(t=>function(e,t){Ir();var r=new _r(e.id,e,t);return Object.setPrototypeOf(r,Dr),r.prototype=Dr,r}(t,e))),s=new yt(a,"id",(()=>{}),(()=>{})),i=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:i,events:r.events.map((t=>Qe(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:s};return Cr.set(e,c),c})();Er.set(e,a)}function Or(e){var t=Er.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw N("LD8",{database:r.name,collection:a})}return t}function Sr(e,t,r,a,n,s){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:$r(a),schema:Tr,options:n,multiInstance:s,devMode:j.isDevMode()})}function Pr(e){var t=Er.get(e);if(t)return Er.delete(e),t.then((e=>e.storageInstance.close()))}async function Br(e,t,r){var a=S(10),n=await Sr(a,e,t,r,{},!1);await n.remove()}function $r(e){return"plugin-local-documents-"+e}var Tr=Q({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function qr(e,t){var r=await Or(this),a={id:e,data:t,_deleted:!1,_meta:T(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function Mr(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Ar(e){var t=await Or(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):Ae(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Lr(e){return this.$.pipe((0,dt.O)(null),(0,Nt.z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,Nt.z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,ht.h)((e=>e.use)),(0,ut.U)((e=>e.doc)))}var Qr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=qr,e.upsertLocal=Mr,e.getLocal=Ar,e.getLocal$=Lr},RxDatabase:e=>{e.insertLocal=qr,e.upsertLocal=Mr,e.getLocal=Ar,e.getLocal$=Lr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Rr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Rr(e.collection)}},preDestroyRxDatabase:{after:e=>Pr(e)},postDestroyRxCollection:{after:e=>Pr(e)},postRemoveRxDatabase:{after:e=>Br(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Br(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Wr;function Fr(){return"undefined"!=typeof window&&window.indexedDB}function Hr(){return Wr||(Wr=(async()=>{!function(e){if(it("preAddRxPlugin",{plugin:e,plugins:jr}),!jr.has(e)){if(kr.has(e.name))throw N("PL3",{name:e.name,plugin:e});if(jr.add(e),kr.add(e.name),!e.rxdb)throw I("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(wr[t])})),e.overwritable&&Object.assign(j,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&st[t].push(r.after),r.before&&st[t].unshift(r.before)}))}}(Qr);var e;return await xr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Wr}const zr=["#e6008d","#8d2089","#5f2688"]},341:(e,t,r)=>{function a(e,t){if(!window.trigger)throw new Error("window.trigger not defined");return window.trigger(e,t)}r.d(t,{X:()=>a})},1960:(e,t,r)=>{r.r(t),r.d(t,{default:()=>O});var a=r(2263),n=r(3799),s=r(5742),i=r(3028),o=r(5556),c=r(9655),l=r(3784),u=r(1556),h=r(7236),d=r(8804),m=r(598),p=Array.isArray;function f(e){return(0,m.U)((function(t){return function(e,t){return p(t)?e.apply(void 0,(0,o.ev)([],(0,o.CR)(t))):e(t)}(e,t)}))}var v=["addListener","removeListener"],g=["addEventListener","removeEventListener"],y=["on","off"];function b(e,t,r,a){if((0,d.m)(r)&&(a=r,r=void 0),a)return b(e,t,r).pipe(f(a));var n=(0,o.CR)(function(e){return(0,d.m)(e.addEventListener)&&(0,d.m)(e.removeEventListener)}(e)?g.map((function(a){return function(n){return e[a](t,n,r)}})):function(e){return(0,d.m)(e.addListener)&&(0,d.m)(e.removeListener)}(e)?v.map(x(e,t)):function(e){return(0,d.m)(e.on)&&(0,d.m)(e.off)}(e)?y.map(x(e,t)):[],2),s=n[0],i=n[1];if(!s&&(0,h.z)(e))return(0,u.z)((function(e){return b(e,t,r)}))((0,c.Xf)(e));if(!s)throw new TypeError("Invalid event target");return new l.y((function(e){var t=function(){for(var t=[],r=0;r{for(await(0,k.YB)(B);C;){const e=$(),r=(0,k.YB)(e.timeToNextPeriod);if(e.period%2==0)try{await t.incrementalModify((t=>(t.beatPeriod>=e.period||(t.beatPeriod=e.period,t.color=D.O9[e.period%3],e.period%4==0?t.text1=L(S,e.period)[0]:t.text2=L(P,e.period)[0]),t)))}catch(p){}await r}})();const r=await e.upsertLocal("mousepos",{x:0,y:0,time:0});let a=[];window.addEventListener("mousemove",(e=>{a=[e.clientX,e.clientY]})),(0,i.T)(b(window,"mousemove"),b(window,"scroll"),b(window,"resize")).subscribe((()=>{r.incrementalPatch({x:a[0],y:a[1],time:(0,_.z)()})})),function(e){const t=document.getElementsByClassName("tilt-to-mouse"),r=100;function a(e,t,a){const n=a.getBoundingClientRect(),s=-(t-n.y-n.height/2)/r,i=(e-n.x-n.width/2)/r;return`perspective(150px) rotateX(${M(s)}deg) rotateY(${M(i)}deg) `}function n(e,t){e.style.transform=a.apply(null,t)}e.$.subscribe((e=>{e._data.data.time&&Array.from(t).forEach((t=>{if(!W(t))return;n(t,(0,j.Is)([e._data.data.x,e._data.data.y]).concat([t]))}))}))}(r),function(e){const t=document.getElementsByClassName("enlarge-on-mouse");function r(e){const t=e.getBoundingClientRect();return{centerX:t.left+t.width/2,centerY:t.top+t.height/2,width:t.width,height:t.height}}function a(e,t){const r=`scale(${t})`;e.style.transform=r}e.$.pipe((0,m.U)((e=>e._data))).subscribe((e=>{e.data.time&&e.data.x&&e.data.y&&Array.from(t).forEach((t=>{if(!W(t))return;const n=r(t),s=e.data.x-n.centerX,i=e.data.y-n.centerY,o=Math.sqrt(s*s+i*i);function c(e){return 1.9^e}let l=1+n.width/2/c(o+300);l>1.5&&(l=1.5),l<1.01&&(l=1),a(t,l)}))}))}(r);const n=document.getElementsByClassName("beating"),s=document.getElementsByClassName("beating-first"),o=document.getElementsByClassName("beating-second"),c=document.getElementsByClassName("beating-number"),l=document.getElementsByClassName("beating-color"),u=document.getElementsByClassName("beating-color-string"),h=[];let d=0;$(),t.$.pipe((0,m.U)((e=>e._data.data)),(0,w.x)(((e,t)=>JSON.stringify(e)===JSON.stringify(t)))).subscribe((e=>{h.forEach((function(e){e(d)})),d+=1;const t=e.color;Array.from(l).forEach((function(e){e.style.backgroundColor=t})),Array.from(u).forEach((function(e){e.innerHTML=t}))})),h.push((function(){Array.from(n).forEach((function(e){e.style.animationDuration=B+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")})),Array.from(s).forEach((function(e){e.style.animationDuration=B+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")})),Array.from(o).forEach((function(e){e.style.animationDuration=B+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")}))})),h.push((function(){Array.from(c).forEach((function(e){A()&&A()&&setTimeout((function(){const t=parseFloat(e.innerHTML)+1;e.innerHTML=t+""}),105)}))}))}function O(){const{siteConfig:e}=(0,a.Z)();return(0,N.useEffect)((()=>(R(),()=>{console.log("stop animation"),C=!1}))),(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(s.Z,{children:(0,E.jsx)("body",{className:"homepage"})}),(0,E.jsx)(n.Z,{title:`${e.title}`,description:"RxDB is a fast, local-first NoSQL-database for JavaScript Applications like Websites, hybrid Apps, Electron-Apps, Progressive Web Apps and Node.js",children:(0,E.jsxs)("main",{children:[(0,E.jsx)("div",{className:"block first centered",children:(0,E.jsx)("div",{className:"content",children:(0,E.jsxs)("div",{className:"inner",children:[(0,E.jsxs)("div",{className:"half",children:[(0,E.jsx)("br",{}),(0,E.jsxs)("h1",{children:["The local ",(0,E.jsx)("b",{className:"underline",children:"Database"})," for"," ",(0,E.jsx)("b",{className:"underline",children:"JavaScript"})," Applications"]}),(0,E.jsx)("br",{}),(0,E.jsxs)("ul",{className:"checked",children:[(0,E.jsx)("li",{children:"Realtime Queries"}),(0,E.jsx)("li",{children:"Realtime Replication"}),(0,E.jsx)("li",{children:"Works Offline"}),(0,E.jsx)("li",{children:"Supports all JavaScript runtimes"}),(0,E.jsx)("li",{children:"Great Performance"})]}),(0,E.jsx)("a",{className:"button",href:"/quickstart.html",target:"_blank",children:"Get Started"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsx)("div",{className:"half",style:{display:"flex",alignItems:"center",justifyContent:"center"},children:(0,E.jsxs)("div",{className:"content-canvas",style:{marginTop:30,marginBottom:30},children:[(0,E.jsx)("div",{className:"device tablet",style:{marginLeft:481,marginTop:117},children:(0,E.jsx)("div",{className:"beating-color",style:{backgroundColor:"rgb(141, 32, 137)"},children:(0,E.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo animation",alt:"RxDB",style:{animationDuration:"851ms"}})})}),(0,E.jsx)("div",{className:"device desktop",style:{marginTop:"0%"},children:(0,E.jsx)("div",{className:"beating-color",style:{backgroundColor:"rgb(141, 32, 137)"},children:(0,E.jsx)("img",{src:"/files/logo/logo_text.svg",className:"beating logo animation",alt:"RxDB",style:{animationDuration:"851ms",width:"52%"}})})}),(0,E.jsxs)("div",{className:"device server",style:{marginLeft:0,marginTop:168},children:[(0,E.jsx)("div",{className:"beating-color one",style:{backgroundColor:"rgb(141, 32, 137)"}}),(0,E.jsx)("div",{className:"beating-color two",style:{backgroundColor:"rgb(141, 32, 137)"}}),(0,E.jsx)("div",{className:"beating-color three",style:{backgroundColor:"rgb(141, 32, 137)"}})]})]})})]})})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb",onClick:()=>(0,I.X)("github_trophy_click",.2),target:"_blank",children:(0,E.jsxs)("div",{className:"trophy",children:[(0,E.jsx)("img",{src:"./files/icons/github-star-with-logo.svg",alt:"RxDB github star"}),(0,E.jsxs)("div",{style:{flex:1},children:[(0,E.jsx)("div",{className:"subtitle",children:"Open Source on"}),(0,E.jsx)("div",{className:"title",children:"GitHub"})]}),(0,E.jsxs)("div",{children:[(0,E.jsx)("div",{className:"valuetitle",children:"stars"}),(0,E.jsxs)("div",{className:"value",children:["19247",(0,E.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,E.jsx)("div",{className:"block second dark",children:(0,E.jsxs)("div",{className:"content",children:[(0,E.jsxs)("h2",{children:["Realtime applications ",(0,E.jsx)("b",{className:"underline",children:"made easy"})]}),(0,E.jsxs)("p",{children:["From the results of a query, to a single field of a document, with RxDB you can ",(0,E.jsx)("b",{children:"observe everything"}),". This enables you to build realtime applications ",(0,E.jsx)("b",{children:"fast"})," and ",(0,E.jsx)("b",{children:"reliable"}),". It does not matter if the data was changed by"," ",(0,E.jsx)("b",{children:"a user event"}),", ",(0,E.jsx)("b",{children:"another browser tab"})," or by the",(0,E.jsx)("b",{children:" replication"}),"."," ","Whenever your data changes, your UI reflects the new state."]}),(0,E.jsxs)("div",{className:"inner",children:[(0,E.jsxs)("div",{className:"code half",children:[(0,E.jsxs)("fieldset",{className:"samp-wrapper",style:{backgroundColor:"var(--bg-color)"},children:[(0,E.jsx)("legend",{children:"Write"}),(0,E.jsxs)("samp",{children:[(0,E.jsx)("span",{className:"cm-keyword",children:"await "}),(0,E.jsx)("span",{className:"cm-variable",children:"collection"}),".",(0,E.jsx)("span",{className:"cm-method",children:"upsert"}),"(","{",(0,E.jsx)("br",{}),(0,E.jsx)("span",{className:"cm-property",children:"\xa0 id"}),": ",(0,E.jsx)("span",{className:"cm-string",children:"'foobar'"}),",",(0,E.jsx)("br",{}),(0,E.jsx)("span",{className:"cm-property",children:"\xa0 color"}),": ",(0,E.jsxs)("span",{className:"cm-string",children:["'",(0,E.jsx)("span",{className:"beating-color-string beating-color",children:"#e6008d"}),"'"]}),(0,E.jsx)("br",{}),"}",");"]})]}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsxs)("fieldset",{className:"samp-wrapper",style:{backgroundColor:"var(--bg-color)"},children:[(0,E.jsx)("legend",{children:"Observe"}),(0,E.jsxs)("samp",{style:{backgroundColor:"var(--bg-color)"},children:[(0,E.jsx)("span",{className:"cm-keyword",children:"await "}),(0,E.jsx)("span",{className:"cm-variable",children:"collection"}),".",(0,E.jsxs)("span",{className:"cm-method",children:["findOne(",(0,E.jsx)("span",{className:"cm-string",children:"'foobar'"}),")"]}),(0,E.jsx)("br",{}),"\xa0.",(0,E.jsx)("span",{className:"cm-property",children:"$"}),(0,E.jsx)("span",{className:"cm-comment",children:" // get observable"}),(0,E.jsx)("br",{}),"\xa0.",(0,E.jsx)("span",{className:"cm-method",children:"subscribe"}),"(",(0,E.jsx)("span",{className:"cm-def",children:"d"}),(0,E.jsx)("span",{className:"cm-operator",children:" =>"})," ","{",(0,E.jsx)("br",{}),(0,E.jsx)("span",{className:"cm-variable",children:"\xa0\xa0 screen"}),".",(0,E.jsx)("span",{className:"cm-property",children:"backgroundColor"}),(0,E.jsx)("span",{className:"cm-operator",children:" = "}),(0,E.jsx)("span",{className:"cm-variable",children:"d"}),".",(0,E.jsx)("span",{className:"cm-property beating-color",children:"color"}),";",(0,E.jsx)("br",{}),"\xa0","}",");"]})]})]}),(0,E.jsx)("div",{className:"canvas half",children:(0,E.jsxs)("div",{className:"content-canvas",children:[(0,E.jsx)("div",{className:"device tablet",style:{marginLeft:481,marginTop:117},children:(0,E.jsx)("div",{className:"beating-color",children:(0,E.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo",alt:"RxDB"})})}),(0,E.jsx)("div",{className:"device desktop",style:{marginTop:"0%"},children:(0,E.jsx)("div",{className:"beating-color",children:(0,E.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo",alt:"RxDB"})})}),(0,E.jsxs)("div",{className:"device server",style:{marginLeft:0,marginTop:168},children:[(0,E.jsx)("div",{className:"beating-color one"}),(0,E.jsx)("div",{className:"beating-color two"}),(0,E.jsx)("div",{className:"beating-color three"})]})]})})]})]})}),(0,E.jsx)("a",{href:"https://twitter.com/intent/user?screen_name=rxdbjs",onClick:()=>(0,I.X)("twitter_trophy_click",.2),target:"_blank",children:(0,E.jsxs)("div",{className:"trophy twitter",children:[(0,E.jsx)("img",{src:"./files/icons/twitter-blue.svg",alt:"RxDB Twitter"}),(0,E.jsxs)("div",{style:{flex:1},children:[(0,E.jsx)("div",{className:"subtitle",children:"Follow on"}),(0,E.jsx)("div",{className:"title",children:"Twitter"})]}),(0,E.jsxs)("div",{children:[(0,E.jsx)("div",{className:"valuetitle",children:"followers"}),(0,E.jsxs)("div",{className:"value",children:["2843",(0,E.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,E.jsx)("div",{className:"block replication",children:(0,E.jsxs)("div",{className:"content",children:[(0,E.jsxs)("div",{className:"half left",children:[(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsxs)("h2",{children:["Replicate ",(0,E.jsx)("b",{children:"with your existing infrastructure"})]}),(0,E.jsxs)("p",{children:["RxDB supports replication with a"," ",(0,E.jsx)("a",{href:"/replication-couchdb.html",target:"_blank",children:"CouchDB"})," ","server or any custom"," ",(0,E.jsx)("a",{href:"/replication-graphql.html",target:"_blank",children:"GraphQL"})," ","endpoint which smoothly integrates with your existing infrastructure. Also you can use the replication primitives plugin to create custom replications over any protocol like"," ",(0,E.jsx)("a",{href:"/replication-http.html",target:"_blank",children:"HTTP"}),","," ",(0,E.jsx)("a",{href:"/replication-websocket.html",target:"_blank",children:"Websocket"}),","," ",(0,E.jsx)("a",{href:"/replication-webrtc.html",target:"_blank",children:"WebRTC"})," ","or"," ",(0,E.jsx)("a",{href:"/replication-firestore.html",target:"_blank",children:"Firestore"}),"."]})]}),(0,E.jsx)("div",{className:"half right",children:(0,E.jsxs)("div",{className:"replication-icons",children:[(0,E.jsx)("img",{src:"./files/logo/logo.svg",alt:"RxDB",className:"replicate-logo tilt-to-mouse"}),(0,E.jsx)("a",{href:"/replication-graphql.html",target:"_blank",children:(0,E.jsx)("div",{className:"neumorphism-circle-xl centered replicate-graphql enlarge-on-mouse",children:(0,E.jsx)("img",{src:"./files/icons/graphql-text.svg",alt:"GraphQL",className:"protocol"})})}),(0,E.jsx)("a",{href:"/replication-couchdb.html",target:"_blank",children:(0,E.jsx)("div",{className:"neumorphism-circle-xl centered replicate-couchdb enlarge-on-mouse",children:(0,E.jsx)("img",{src:"./files/icons/couchdb-text.svg",alt:"CouchDB",className:"protocol"})})}),(0,E.jsxs)("div",{className:"neumorphism-circle-xs centered replicate-rest enlarge-on-mouse",children:["{"," REST ","}"]}),(0,E.jsx)("a",{href:"/replication-websocket.html",target:"_blank",children:(0,E.jsx)("div",{className:"neumorphism-circle-xs centered replicate-websocket enlarge-on-mouse",children:"websocket"})}),(0,E.jsx)("a",{href:"/replication-webrtc.html",target:"_blank",children:(0,E.jsx)("div",{className:"neumorphism-circle-xs centered replicate-webrtc enlarge-on-mouse",children:"WebRTC"})})]})}),(0,E.jsx)("div",{className:"clear"})]})}),(0,E.jsx)("a",{href:"https://rxdb.info/chat.html",onClick:()=>(0,I.X)("discord_trophy_click",.2),target:"_blank",children:(0,E.jsxs)("div",{className:"trophy discord",children:[(0,E.jsx)("img",{src:"./files/icons/discord.svg",alt:"RxDB Discord chat"}),(0,E.jsxs)("div",{style:{flex:1},children:[(0,E.jsx)("div",{className:"subtitle",children:"Chat on"}),(0,E.jsx)("div",{className:"title",children:"Discord"})]}),(0,E.jsxs)("div",{children:[(0,E.jsx)("div",{className:"valuetitle",children:"members"}),(0,E.jsxs)("div",{className:"value",children:["414",(0,E.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,E.jsxs)("div",{className:"block offline-first dark",children:[(0,E.jsx)("div",{className:"offline-image-wrapper",children:(0,E.jsx)("img",{src:"files/icons/wifi/wifi_1a202c.svg",className:"offline-image beating-second",alt:"offline"})}),(0,E.jsxs)("div",{className:"content",children:[(0,E.jsxs)("h2",{children:["Online ",(0,E.jsx)("b",{className:"underline",children:"is optional"})]}),(0,E.jsxs)("div",{className:"full-width",children:[(0,E.jsx)("div",{className:"half left",children:(0,E.jsxs)("p",{children:["RxDB follows the"," ",(0,E.jsx)("a",{href:"/offline-first.html",target:"_blank",children:"Offline First"})," ","paradigm where an application must work as well offline as it does online. This is done by persisting data locally on the client side and replicating it in the background. RxDB can even be used solely on the client side, with no backend at all."]})}),(0,E.jsx)("div",{className:"half right",children:(0,E.jsxs)("ul",{className:"checked",children:[(0,E.jsxs)("li",{children:["Your application still ",(0,E.jsx)("b",{children:"works offline"})]}),(0,E.jsxs)("li",{children:["Increases ",(0,E.jsx)("b",{children:"perceived performance"})]}),(0,E.jsxs)("li",{children:["Easier and ",(0,E.jsx)("b",{children:"faster implementation"})]}),(0,E.jsxs)("li",{children:["Needs less backend resources and ",(0,E.jsx)("b",{children:"scales better"})]})]})})]})]})]}),(0,E.jsx)("div",{className:"block frameworks",children:(0,E.jsxs)("div",{className:"content",children:[(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/angular",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"-10%",left:"10%"},children:[(0,E.jsx)("img",{src:"./files/icons/angular.svg",alt:"angular"}),"Angular"]})}),(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"10%",left:"58%"},children:[(0,E.jsx)("img",{src:"./files/icons/capacitor.svg",alt:"capacitor"}),"Capacitor"]}),(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"-4%",left:"44%"},children:[(0,E.jsx)("img",{src:"./files/icons/deno.svg",alt:"deno"}),"Deno"]}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/node",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"-5%",left:"85%"},children:[(0,E.jsx)("img",{src:"./files/icons/nodejs.svg",alt:"Node.js"}),"Node.js"]})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/react",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"4%",left:"26%"},children:[(0,E.jsx)("img",{src:"./files/icons/react.svg",alt:"React"}),"React"]})}),(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"15%",left:"90%",marginLeft:"-35px"},children:[(0,E.jsx)("img",{src:"./files/icons/svelte.svg",alt:"Svelte"}),"Svelte"]}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsxs)("h2",{children:["Flexible ",(0,E.jsx)("b",{className:"underline",children:"storage layer"})]}),(0,E.jsxs)("p",{children:["RxDB is based on a storage interface that enables you to swap out the underlying storage engine. This increases code reuse because the same database code can be used in ",(0,E.jsx)("b",{children:"any JavaScript runtime"})," ","by just switching out the storage settings.",(0,E.jsx)("br",{})]}),(0,E.jsxs)("div",{className:"below-text",children:[(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/electron",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"2%",left:"18%"},children:[(0,E.jsx)("img",{src:"./files/icons/electron.svg",alt:"electron"}),"Electron"]})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/vue",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"3%",left:"45%"},children:[(0,E.jsx)("img",{src:"./files/icons/vuejs.svg",alt:"Vue.js"}),"Vue.js"]})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/ionic2",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"2%",left:"71%"},children:[(0,E.jsx)("img",{src:"./files/icons/ionic.svg",alt:"ionic"}),"Ionic"]})}),(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"46%",left:"11%"},children:[(0,E.jsx)("img",{src:"./files/icons/nativescript.svg",alt:"NativeScript"}),"NativeScript"]}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/react-native",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"45%",left:"35%"},children:[(0,E.jsx)("img",{src:"./files/icons/react.svg",alt:"React Native"}),"React Native"]})}),(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"45%",left:"62%"},children:[(0,E.jsx)("img",{src:"./files/icons/nextjs.svg",alt:"Next.js"}),"Next.js"]}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/flutter",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"40%",left:"86%"},children:[(0,E.jsx)("img",{src:"./files/icons/flutter.svg",alt:"Flutter"}),"Flutter"]})})]})]})}),(0,E.jsx)("div",{className:"block fifth dark",children:(0,E.jsx)("div",{className:"content centered",children:(0,E.jsxs)("div",{className:"inner",children:[(0,E.jsxs)("h2",{children:["Trusted and ",(0,E.jsx)("b",{className:"underline",children:"open source"})]}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/github-star.svg",alt:"github star"}),(0,E.jsx)("div",{className:"label",children:"Github Stars"}),(0,E.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb",rel:"noopener",target:"_blank",children:"19247"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/download.svg",alt:"npm downloads"}),(0,E.jsx)("div",{className:"label",children:"npm downloads"}),(0,E.jsx)("a",{className:"value beating-number",href:"https://www.npmjs.com/package/rxdb",rel:"noopener",target:"_blank",children:"238572"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsx)("div",{className:"clear"}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/person.svg",alt:"contributor"}),(0,E.jsx)("div",{className:"label",children:"Contributors"}),(0,E.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/graphs/contributors",rel:"noopener",target:"_blank",children:"133"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/commit.svg",alt:"commit"}),(0,E.jsx)("div",{className:"label",children:"Commits"}),(0,E.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/commits/master",rel:"noopener",target:"_blank",children:"6891"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsx)("div",{className:"clear"}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/gear.svg",alt:"gear"}),(0,E.jsx)("div",{className:"label",children:"Projects build with RxDB"}),(0,E.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/network/dependents?package_id=UGFja2FnZS0xODM0NzAyMw%3D%3D",rel:"noopener",target:"_blank",children:"825"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/twitter.svg",alt:"twitter"}),(0,E.jsx)("div",{className:"label",children:"Twitter followers"}),(0,E.jsx)("a",{className:"value",href:"https://twitter.com/intent/user?screen_name=rxdbjs",rel:"noopener",target:"_blank",children:"2843"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsx)("div",{className:"clear"})]})})}),(0,E.jsx)("div",{className:"block sixth",children:(0,E.jsxs)("div",{className:"content",children:[(0,E.jsx)("h2",{children:"Pricing Models"}),(0,E.jsx)("div",{className:"inner",children:(0,E.jsxs)("div",{className:"buy-options",children:[(0,E.jsx)("div",{className:"buy-option bg-gradient-left-top",children:(0,E.jsxs)("div",{className:"buy-option-inner",children:[(0,E.jsxs)("div",{className:"buy-option-title",children:[(0,E.jsx)("h2",{children:"RxDB Basics"}),(0,E.jsx)("div",{className:"price",children:"Free & Open Source"})]}),(0,E.jsx)("div",{className:"buy-option-features",children:(0,E.jsxs)("ul",{children:[(0,E.jsx)("li",{children:"Basic RxStorages"}),(0,E.jsx)("li",{children:"Realtime Replication"}),(0,E.jsx)("li",{children:"Live Queries"}),(0,E.jsx)("li",{children:"Schema Validation"}),(0,E.jsx)("li",{children:"Multi-Tab Support"}),(0,E.jsx)("li",{children:"Encryption"}),(0,E.jsx)("li",{children:"Compression"})]})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb",target:"_blank",rel:"noopener",onClick:()=>(0,I.X)("goto_code",.2),children:(0,E.jsx)("div",{className:"buy-option-action bg-top hover-shadow-top",children:"Get the Code"})})]})}),(0,E.jsx)("div",{className:"buy-option bg-gradient-right-top",children:(0,E.jsxs)("div",{className:"buy-option-inner",children:[(0,E.jsxs)("div",{className:"buy-option-title",children:[(0,E.jsx)("h2",{children:"Premium Plugins"}),(0,E.jsx)("div",{className:"price",children:"for professionals to get the most out of RxDB"})]}),(0,E.jsx)("div",{className:"buy-option-features",children:(0,E.jsxs)("ul",{children:[(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-sqlite.html",target:"_blank",children:"SQLite RxStorage"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-opfs.html",target:"_blank",children:"OPFS RxStorage"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-indexeddb.html",target:"_blank",children:"IndexedDB RxStorage"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-memory-synced.html",target:"_blank",children:"Memory-Synced RxStorage"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-sharding.html",target:"_blank",children:"Sharding Plugin"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/query-optimizer.html",target:"_blank",children:"Query Optimizer"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/migration-storage.html",target:"_blank",children:"Storage Migrator"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:"RxStorage Localstorage Meta Optimizer"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-shared-worker.html",target:"_blank",children:"Shared Worker"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-worker.html",target:"_blank",children:"Worker"})})]})}),(0,E.jsx)("a",{href:"/premium",onClick:()=>(0,I.X)("premium_request",1),children:(0,E.jsx)("div",{className:"buy-option-action bg-middle hover-shadow-middle",children:"Request Premium"})})]})}),(0,E.jsx)("div",{className:"buy-option bg-gradient-left-top",children:(0,E.jsxs)("div",{className:"buy-option-inner",children:[(0,E.jsxs)("div",{className:"buy-option-title",children:[(0,E.jsx)("h2",{children:"Consulting Session"}),(0,E.jsx)("div",{className:"price",children:"fast in person consulting"})]}),(0,E.jsx)("div",{className:"buy-option-features",children:(0,E.jsxs)("p",{children:["Book a one hour consulting session with the RxDB maintainer. I will answer all your questions, give proposals for your use case and we can even do a pair programming session if you have a specific problem in your source code.",(0,E.jsx)("br",{}),"You can book this by doing a one-time donation via github sponsors."]})}),(0,E.jsx)("a",{href:"https://github.com/sponsors/pubkey?frequency=one-time&sponsor=pubkey",target:"_blank",onClick:()=>(0,I.X)("consulting_session_request",1.5),children:(0,E.jsx)("div",{className:"buy-option-action bg-bottom hover-shadow-bottom",children:"Book Now"})})]})})]})})]})}),(0,E.jsx)("div",{className:"block last dark",children:(0,E.jsxs)("div",{className:"content",children:[(0,E.jsxs)("h2",{children:["Start using ",(0,E.jsx)("b",{className:"underline",children:"RxDB"})," today"]}),(0,E.jsxs)("div",{className:"buttons full-width",children:[(0,E.jsx)("a",{href:"/quickstart.html",rel:"noopener",target:"_blank",onClick:()=>(0,I.X)("start_now",.4),children:(0,E.jsx)("div",{className:"button get-premium",style:{left:"50%",top:"20%",marginLeft:"-122px"},children:"Start now"})}),(0,E.jsx)("a",{href:"https://rxdb.info/newsletter.html",rel:"noopener",target:"_blank",onClick:()=>(0,I.X)("get_newsletter",.4),children:(0,E.jsx)("div",{className:"button",style:{left:"25%",marginLeft:"-90px"},children:"Get the Newsletter"})}),(0,E.jsx)("a",{href:"https://rxdb.info/chat.html",rel:"noopener",target:"_blank",onClick:()=>(0,I.X)("join_chat",.4),children:(0,E.jsx)("div",{className:"button",style:{left:"77%",top:"6%",marginLeft:"-70.5px"},children:"Join the Chat"})}),(0,E.jsx)("a",{href:"/premium",onClick:()=>(0,I.X)("premium_request",1),children:(0,E.jsx)("div",{className:"button",style:{top:"40%",left:"20%",marginLeft:"-70.5px"},children:"Get Premium"})}),(0,E.jsx)("a",{href:"https://twitter.com/intent/user?screen_name=rxdbjs",rel:"noopener",target:"_blank",onClick:()=>(0,I.X)("follow_twitter",.4),children:(0,E.jsx)("div",{className:"button",style:{top:"44%",left:"73%",marginLeft:"-85px"},children:"Follow on Twitter"})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb",rel:"noopener",target:"_blank",onClick:()=>(0,I.X)("goto_code",.4),children:(0,E.jsx)("div",{className:"button",style:{top:"54%",left:"32%",marginLeft:"-70px"},children:"Get the Code"})})]})]})})]})})]})}const S=["NoSQL","OfflineFirst","JavaScript","observable","reactive","realtime","client side","fast"],P=["for the Web","for Node.js","for Browsers","for Capacitor","for Electron","for hybrid apps","for PWAs","for React Native","for NativeScript","for UI apps","you deserve","that syncs"],B=851;function $(){const e=((new Date).getTime()-196e7)/B,t=Math.floor(e);return{ratio:e,period:t,timeToNextPeriod:(e-t)*B}}const T=22,q=-1*T;function M(e){return eT?T:e}function A(){return Math.random()<.5}function L(e,t){let r,a,n=(e=e.slice(0)).length;for(;n;)a=Math.floor(Q(t)*n--),r=e[n],e[n]=e[a],e[a]=r,++t;return e}function Q(e){const t=1e4*Math.sin(e++);return t-Math.floor(t)}function W(e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}},6087:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function s(e){return Array.isArray(e)}function i(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;as,Nb:()=>l,S7:()=>i,SI:()=>a,gu:()=>c,qo:()=>n,r0:()=>o})},7400:(e,t,r)=>{function a(e){if(!e)throw new Error("ensureNotFalsy() is falsy");return e}r.d(t,{Is:()=>a,kv:()=>n});var n={bufferSize:1,refCount:!0}},4419:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$Y:()=>o,C2:()=>u,Y3:()=>a,YB:()=>n,Ze:()=>h,kZ:()=>s,m5:()=>i,y$:()=>c});Promise.resolve(!0);var s=Promise.resolve(!1),i=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var l=o;function u(e){return void 0===e&&(e=void 0),l=l.then((()=>c(e)))}function h(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},984:(e,t,r)=>{r.d(t,{z:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/1df93b7f.2b3be9a8.js b/docs/assets/js/1df93b7f.2b3be9a8.js new file mode 100644 index 00000000000..645963d932f --- /dev/null +++ b/docs/assets/js/1df93b7f.2b3be9a8.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[3237],{5921:(e,t,r)=>{r.d(t,{O9:()=>zr,N8:()=>Hr,dZ:()=>Fr});var a=r(8061);function n(e,t){var r=e.get(t);if(void 0===r)throw new Error("missing value from map "+t);return r}function s(e,t,r,a){var n=e.get(t);return void 0===n?(n=r(),e.set(t,n)):a&&a(n),n}function i(e){return Object.assign({},e)}function o(e,t){if(void 0===t&&(t=!1),!e)return e;if(!t&&Array.isArray(e))return e.sort(((e,t)=>"string"==typeof e&&"string"==typeof t?e.localeCompare(t):"object"==typeof e?1:-1)).map((e=>o(e,t)));if("object"==typeof e&&!Array.isArray(e)){var r={};return Object.keys(e).sort(((e,t)=>e.localeCompare(t))).forEach((a=>{r[a]=o(e[a],t)})),r}return e}var c=function e(t){if(!t)return t;if(null===t||"object"!=typeof t)return t;if(Array.isArray(t)){for(var r=new Array(t.length),a=r.length;a--;)r[a]=e(t[a]);return r}var n={};for(var s in t)n[s]=e(t[s]);return n};function l(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var u=e=>{var t=typeof e;return null!==e&&("object"===t||"function"===t)},h=new Set(["__proto__","prototype","constructor"]),d=new Set("0123456789");function m(e){var t=[],r="",a="start",n=!1;for(var s of e)switch(s){case"\\":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");n&&(r+=s),a="property",n=!n;break;case".":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="property";break}if(n){n=!1,r+=s;break}if(h.has(r))return[];t.push(r),r="",a="property";break;case"[":if("index"===a)throw new Error("Invalid character in an index");if("indexEnd"===a){a="index";break}if(n){n=!1,r+=s;break}if("property"===a){if(h.has(r))return[];t.push(r),r=""}a="index";break;case"]":if("index"===a){t.push(Number.parseInt(r,10)),r="",a="indexEnd";break}if("indexEnd"===a)throw new Error("Invalid character after an index");default:if("index"===a&&!d.has(s))throw new Error("Invalid character in an index");if("indexEnd"===a)throw new Error("Invalid character after an index");"start"===a&&(a="property"),n&&(n=!1,r+="\\"),r+=s}switch(n&&(r+="\\"),a){case"property":if(h.has(r))return[];t.push(r);break;case"index":throw new Error("Index was not closed");case"start":t.push("")}return t}function p(e,t){if("number"!=typeof t&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function f(e,t){if(p(e,t))throw new Error("Cannot use string index")}function v(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!u(e)||"string"!=typeof t)return void 0===r?e:r;var a=m(t);if(0===a.length)return r;for(var n=0;n!1,deepFreezeWhenDevMode:e=>e,tunnelErrorMessage:e=>"RxDB Error-Code "+e+".\n Error messages are not included in RxDB core to reduce build size.\n - To find out what this error means, either use the dev-mode-plugin https://rxdb.info/dev-mode.html\n - or search for the error code here: https://github.com/pubkey/rxdb/search?q="+e+"\n "};function k(e,t,r){return"RxError ("+t+"):\n"+e+"\n"+function(e){var t="";return 0===Object.keys(e).length?t:(t+="Given parameters: {\n",t+=Object.keys(e).map((t=>{var r="[object Object]";try{r="errors"===t?e[t].map((e=>JSON.stringify(e,Object.getOwnPropertyNames(e)))):JSON.stringify(e[t],(function(e,t){return void 0===t?null:t}),2)}catch(a){}return t+":"+r})).join("\n"),t+="}")}(r)}var _=function(e){function t(t,r,a){var n;void 0===a&&(a={});var s=k(r,t,a);return(n=e.call(this,s)||this).code=t,n.message=s,n.parameters=a,n.rxdb=!0,n}return(0,x.Z)(t,e),t.prototype.toString=function(){return this.message},(0,b.Z)(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}]),t}((0,w.Z)(Error)),D=function(e){function t(t,r,a){var n;void 0===a&&(a={});var s=k(r,t,a);return(n=e.call(this,s)||this).code=t,n.message=s,n.parameters=a,n.rxdb=!0,n}return(0,x.Z)(t,e),t.prototype.toString=function(){return this.message},(0,b.Z)(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}]),t}((0,w.Z)(TypeError));function N(e,t){return new _(e,j.tunnelErrorMessage(e),t)}function I(e,t){return new D(e,j.tunnelErrorMessage(e),t)}function E(e){return!(!e||409!==e.status)&&e}var C={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};var R=/\./g,O="abcdefghijklmnopqrstuvwxyz";function S(e){void 0===e&&(e=10);for(var t="",r=0;r{var r=v(t,e);if(void 0===r)throw N("DOC18",{args:{field:e,documentData:t}});return r})).join(r.separator)}function Q(e){var t=A((e=i(e)).primaryKey);e.properties=i(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=W,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=F(e);(0,y.gu)(e.required,r),e.required=e.required.filter((e=>!e.includes("."))).filter(((e,t,r)=>r.indexOf(e)===t)),e.version=e.version||0;var a=e.indexes.map((e=>{var r=(0,y.AD)(e)?e.slice(0):[e];return r.includes(t)||r.push(t),"_deleted"!==r[0]&&r.unshift("_deleted"),r}));0===a.length&&a.push(function(e){return["_deleted",e]}(t)),a.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map((e=>{a.push(e)}));var n=new Set;return a.filter((e=>{var t=e.join(",");return!n.has(t)&&(n.add(t),!0)})),e.indexes=a,e}var W={type:"object",properties:{lwt:{type:"number",minimum:$,maximum:1e15,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function F(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}var H="docs",z="changes",K="attachments",U="dexie",Z=new Map,J=new Map;var V="__";function X(e){var t=e.split(".");if(t.length>1)return t.map((e=>X(e))).join(".");if(e.startsWith("|")){var r=e.substring(1);return V+r}return e}function Y(e){var t=e.split(".");return t.length>1?t.map((e=>Y(e))).join("."):e.startsWith(V)?"|"+e.substring(V.length):e}function G(e,t){return t?(t=te(t=i(t)),e.forEach((e=>{var r=v(t,e);g(t,e,r?"1":"0")})),t):t}function ee(e,t){return t?(t=re(t=i(t)),e.forEach((e=>{var r=v(t,e);g(t,e,"1"===r)})),t):t}function te(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>te(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((e=>{let[r,a]=e;"object"==typeof a&&(a=te(a)),t[X(r)]=a})),t}}function re(e){if(!e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>re(e)));if("object"==typeof e){var t={};return Object.entries(e).forEach((r=>{let[a,n]=r;("object"==typeof n||Array.isArray(e))&&(n=re(n)),t[Y(a)]=n})),t}}function ae(e){var t=[],r=A(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach((e=>{var r=(0,y.qo)(e);t.push(r)})),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]);var a=(t=t.map((e=>e.map((e=>X(e)))))).map((e=>1===e.length?e[0]:"["+e.join("+")+"]"));return(a=a.filter(((e,t,r)=>r.indexOf(e)===t))).join(", ")}async function ne(e,t){var r=await e;return(await r.dexieTable.bulkGet(t)).map((e=>ee(r.booleanIndexes,e)))}function se(e,t){return e+"||"+t}function ie(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach((a=>{(0,y.qo)(a).forEach((a=>{t.has(a)||(t.add(a),"boolean"===q(e,a).type&&r.push(a))}))})),r.push("_deleted"),(0,y.Nb)(r)):r}var oe=r(6974),ce=r(984),le=r(7400),ue=String.fromCharCode(65535),he=Number.MIN_SAFE_INTEGER;function de(e,t){var r=t.selector,a=e.indexes?e.indexes.slice(0):[];t.index&&(a=[t.index]);var n=!!t.sort.find((e=>"desc"===Object.values(e)[0])),s=new Set;Object.keys(r).forEach((t=>{var a=q(e,t);a&&"boolean"===a.type&&Object.prototype.hasOwnProperty.call(r[t],"$eq")&&s.add(t)}));var i,o=t.sort.map((e=>Object.keys(e)[0])).filter((e=>!s.has(e))).join(","),c=-1;if(a.forEach((e=>{var a=!0,l=!0,u=e.map((e=>{var t=r[e],n=t?Object.keys(t):[],s={};t&&n.length?n.forEach((e=>{if(me.has(e)){var r=function(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}(e,t[e]);s=Object.assign(s,r)}})):s={startKey:l?he:ue,endKey:a?ue:he,inclusiveStart:!0,inclusiveEnd:!0};return void 0===s.startKey&&(s.startKey=he),void 0===s.endKey&&(s.endKey=ue),void 0===s.inclusiveStart&&(s.inclusiveStart=!0),void 0===s.inclusiveEnd&&(s.inclusiveEnd=!0),l&&!s.inclusiveStart&&(l=!1),a&&!s.inclusiveEnd&&(a=!1),s})),h=u.map((e=>e.startKey)),d=u.map((e=>e.endKey)),m={index:e,startKeys:h,endKeys:d,inclusiveEnd:a,inclusiveStart:l,sortSatisfiedByIndex:!n&&o===e.filter((e=>!s.has(e))).join(","),selectorSatisfiedByIndex:ve(e,t.selector,h,d)},p=function(e,t,r){var a=0,n=e=>{e>0&&(a+=e)},s=10,i=(0,y.r0)(r.startKeys,(e=>e!==he&&e!==ue));n(i*s);var o=(0,y.r0)(r.startKeys,(e=>e!==ue&&e!==he));n(o*s);var c=(0,y.r0)(r.startKeys,((e,t)=>e===r.endKeys[t]));n(c*s*1.5);var l=r.sortSatisfiedByIndex?5:0;return n(l),a}(0,0,m);(p>=c||t.index)&&(c=p,i=m)})),!i)throw N("SNH",{query:t});return i}var me=new Set(["$eq","$gt","$gte","$lt","$lte"]),pe=new Set(["$eq","$gt","$gte"]),fe=new Set(["$eq","$lt","$lte"]);function ve(e,t,r,a){var n=Object.entries(t).find((t=>{let[r,a]=t;return!e.includes(r)||Object.entries(a).find((e=>{let[t,r]=e;return!me.has(t)}))}));if(n)return!1;if(t.$and||t.$or)return!1;var s=[],i=new Set;for(var[o,c]of Object.entries(t)){if(!e.includes(o))return!1;var l=Object.keys(c).filter((e=>pe.has(e)));if(l.length>1)return!1;var u=l[0];if(u&&i.add(o),"$eq"!==u){if(s.length>0)return!1;s.push(u)}}var h=[],d=new Set;for(var[m,p]of Object.entries(t)){if(!e.includes(m))return!1;var f=Object.keys(p).filter((e=>fe.has(e)));if(f.length>1)return!1;var v=f[0];if(v&&d.add(m),"$eq"!==v){if(h.length>0)return!1;h.push(v)}}var g=0;for(var y of e){for(var b of[i,d]){if(!b.has(y)&&b.size>0)return!1;b.delete(y)}if(r[g]!==a[g]&&i.size>0&&d.size>0)return!1;g++}return!0}var ge=r(6250),ye=r(7761),be=r(7132),xe=r(6496),we=r(6851),je=r(3516),ke=r(8039),_e=r(5308),De=r(2106),Ne=!1;function Ie(e){return Ne||((0,ye.Qs)(ye.$M.PIPELINE,{$sort:xe.E3,$project:xe.FM}),(0,ye.Qs)(ye.$M.QUERY,{$and:we.h$,$eq:je.l3,$elemMatch:_e.rr,$exists:De.G,$gt:je.ok,$gte:je.m9,$in:je.FI,$lt:je.Ty,$lte:je.HG,$ne:je.ny,$nin:je.IS,$mod:ke.JD,$nor:we.ps,$not:we._w,$or:we.Ko,$regex:ke.GO,$size:_e.QH,$type:De.e}),Ne=!0),new be.A(e)}function Ee(e,t){var r=A(e.primaryKey);t=i(t);var a=c(t);if("number"!=typeof a.skip&&(a.skip=0),a.selector?(a.selector=a.selector,Object.entries(a.selector).forEach((e=>{let[t,r]=e;"object"==typeof r&&null!==r||(a.selector[t]={$eq:r})}))):a.selector={},a.index){var n=(0,y.qo)(a.index);n.includes(r)||n.push(r),a.index=n}if(a.sort)a.sort.find((e=>{return t=e,Object.keys(t)[0]===r;var t}))||(a.sort=a.sort.slice(0),a.sort.push({[r]:"asc"}));else if(a.index)a.sort=a.index.map((e=>({[e]:"asc"})));else{if(e.indexes){var s=new Set;Object.entries(a.selector).forEach((e=>{let[t,r]=e;("object"!=typeof r||null===r||!!Object.keys(r).find((e=>me.has(e))))&&s.add(t)}));var o,l=-1;e.indexes.forEach((e=>{var t=(0,y.AD)(e)?e:[e],r=t.findIndex((e=>!s.has(e)));r>0&&r>l&&(l=r,o=t)})),o&&(a.sort=o.map((e=>({[e]:"asc"}))))}a.sort||(a.sort=[{[r]:"asc"}])}return a}function Ce(e,t){if(!t.sort)throw N("SNH",{query:t});var r=[];t.sort.forEach((e=>{var t,a,n,s=Object.keys(e)[0],i=Object.values(e)[0];r.push({key:s,direction:i,getValueFn:(t=s,a=t.split("."),n=a.length,1===n?e=>e[t]:e=>{for(var t=e,r=0;r{for(var a=0;ar.test(e)}function Oe(e){return e===he?-1/0:e}function Se(e,t,r){return e.includes(t)?r===ue||!0===r?"1":"0":r}function Pe(e,t,r){if(!r){if("undefined"==typeof window)throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var a=t.startKeys.map(((r,a)=>{var n=t.index[a];return Se(e,n,r)})).map(Oe),n=t.endKeys.map(((r,a)=>{var n=t.index[a];return Se(e,n,r)})).map(Oe);return r.bound(a,n,!t.inclusiveStart,!t.inclusiveEnd)}async function Be(e,t){var r=await e.internals,a=t.query,n=a.skip?a.skip:0,s=n+(a.limit?a.limit:1/0),i=t.queryPlan,o=!1;i.selectorSatisfiedByIndex||(o=Re(e.schema,t.query));var c=Pe(r.booleanIndexes,i,r.dexieDb._options.IDBKeyRange),l=i.index,u=[];if(await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,a=e.idbtrans.objectStore(H);t="["+l.map((e=>X(e))).join("+")+"]";var n=a.index(t).openCursor(c);await new Promise((e=>{n.onsuccess=function(t){var a=t.target.result;if(a){var n=ee(r.booleanIndexes,a.value);o&&!o(n)||u.push(n),i.sortSatisfiedByIndex&&u.length===s?e():a.continue()}else e()}}))})),!i.sortSatisfiedByIndex){var h=Ce(e.schema,t.query);u=u.sort(h)}return{documents:u=u.slice(n,s)}}function $e(e){var t=e.split("-");if(2!==t.length)throw new Error("malformatted revision: "+e);return{height:parseInt(t[0],10),hash:t[1]}}function Te(e){return parseInt(e.split("-")[0],10)}function qe(e,t){var r=t?t._rev:null;return(r?$e(r).height:0)+1+"-"+e}var Me="_rxdb_internal";async function Ae(e,t){var r=(await e.findDocumentsById([t],!1))[0];return r||void 0}async function Le(e,t,r){var a=await e.bulkWrite([t],r);if(a.error.length>0)throw a.error[0];return a.success[0]}function Qe(e,t,r){var a=t.documentData,n=t.previousDocumentData;return{documentId:t.documentId,collectionName:r?r.name:void 0,isLocal:e,operation:t.operation,documentData:j.deepFreezeWhenDevMode(a),previousDocumentData:j.deepFreezeWhenDevMode(n)}}function We(e,t,r,a){if(a)throw 409===a.status?N("CONFLICT",{collection:e.name,id:t,writeError:a,data:r}):422===a.status?N("VD2",{collection:e.name,id:t,writeError:a,data:r}):a}function Fe(e){return{previous:e.previous,document:He(e.document)}}function He(e){if(!e._attachments||0===Object.keys(e._attachments).length)return e;var t=i(e);return t._attachments={},Object.entries(e._attachments).forEach((e=>{let[r,a]=e;var n,s,i;t._attachments[r]=(i=(n=a).data)?{length:(s=i,atob(s).length),digest:n.digest,type:n.type}:n})),t}function ze(e){var t=i(e);return t._meta=i(e._meta),t}function Ke(e,t,r){j.deepFreezeWhenDevMode(r);var a=A(r.primaryKey);var n={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,bulkWrite(n,s){var o=n.map((n=>function(n){var s=i(n.document);if(s._meta=i(s._meta),j.isDevMode()){s=M(a,r,s);try{"function"==typeof structuredClone?structuredClone(n):JSON.parse(JSON.stringify(n))}catch(o){throw N("DOC24",{collection:t.collectionName,document:n.document})}n.previous,n.previous&&Object.keys(n.previous._meta).forEach((e=>{if(!Object.prototype.hasOwnProperty.call(n.document._meta,e))throw N("SNH",{dataBefore:n.previous,dataAfter:n.document})}))}return s._meta.lwt=(0,ce.z)(),s._rev=qe(e.token,n.previous),{document:s,previous:n.previous}}(n)));return e.lockedRun((()=>t.bulkWrite(o,s))).then((r=>{var a={error:[],success:r.success.slice(0)},n=r.error.filter((e=>!(409!==e.status||e.writeRow.previous||e.writeRow.document._deleted||!(0,le.Is)(e.documentInDb)._deleted)||(a.error.push(e),!1)));if(n.length>0){var i=n.map((t=>({previous:t.documentInDb,document:Object.assign({},t.writeRow.document,{_rev:qe(e.token,t.documentInDb)})})));return e.lockedRun((()=>t.bulkWrite(i,s))).then((e=>((0,y.gu)(a.error,e.error),(0,y.gu)(a.success,e.success),a)))}return r}))},query:r=>e.lockedRun((()=>t.query(r))),count:r=>e.lockedRun((()=>t.count(r))),findDocumentsById:(r,a)=>e.lockedRun((()=>t.findDocumentsById(r,a))),getAttachmentData:(r,a,n)=>e.lockedRun((()=>t.getAttachmentData(r,a,n))),getChangedDocumentsSince:t.getChangedDocumentsSince?(r,a)=>e.lockedRun((()=>t.getChangedDocumentsSince((0,le.Is)(r),a))):void 0,cleanup:r=>e.lockedRun((()=>t.cleanup(r))),remove:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.remove()))),close:()=>(e.storageInstances.delete(n),e.lockedRun((()=>t.close()))),changeStream:()=>t.changeStream(),conflictResultionTasks:()=>t.conflictResultionTasks(),resolveConflictResultionTask(e){if(e.output.isEqual)return t.resolveConflictResultionTask(e);var r=i(Object.assign({},e.output.documentData,{_meta:T(),_rev:"",_attachments:{}}));return delete r._meta,delete r._rev,delete r._attachments,t.resolveConflictResultionTask({id:e.id,output:{isEqual:!1,documentData:r}})}};return e.storageInstances.add(n),n}var Ue=r(5677),Ze=r(3981),Je=new Map;function Ve(e,t){var r=Je.get(e);if(r)return r.refs.delete(t),0===r.refs.size?(Je.delete(e),r.bc.close()):void 0}function Xe(e,t,r,a){if(t.multiInstance){var n=a||function(e,t,r,a){var n=Je.get(t);return n||(n={bc:new Ze.g0(["RxDB:",e,r].join("|")),refs:new Set},Je.set(t,n)),n.refs.add(a),n.bc}(e,t.databaseInstanceToken,r.databaseName,r),s=new oe.x,i=r=>{r.storageName===e&&r.databaseName===t.databaseName&&r.collectionName===t.collectionName&&r.version===t.schema.version&&s.next(r.eventBulk)};n.addEventListener("message",i);var o=r.changeStream(),c=!1,l=o.subscribe((r=>{c||n.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:r})}));r.changeStream=function(){return s.asObservable().pipe((0,Ue.b)(o))};var u=r.close.bind(r);r.close=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",i),a||await Ve(t.databaseInstanceToken,r),u()};var h=r.remove.bind(r);r.remove=async function(){return c=!0,l.unsubscribe(),n.removeEventListener("message",i),a||await Ve(t.databaseInstanceToken,r),h()}}}var Ye=(0,ce.z)(),Ge=function(){function e(e,t,r,a,n,s,i){this.changes$=new oe.x,this.instanceId=Ye++,this.storage=e,this.databaseName=t,this.collectionName=r,this.schema=a,this.internals=n,this.options=s,this.settings=i,this.primaryPath=A(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(e,t){tt(this),e.forEach((e=>{if(!e.document._rev||e.previous&&!e.previous._rev)throw N("SNH",{args:{row:e}})}));var r,a=await this.internals,n={success:[],error:[]},s=e.map((e=>e.document[this.primaryPath]));if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,(async()=>{var i=new Map;(await ne(this.internals,s)).forEach((e=>{var t=e;return t&&i.set(t[this.primaryPath],t),t})),r=function(e,t,r,a,n,s,i){for(var o,c=!!e.schema.attachments,l=[],u=[],h=[],d={id:S(10),events:[],checkpoint:null,context:n,startTime:(0,ce.z)(),endTime:0},m=d.events,p=[],f=[],v=[],g=r.size>0,y=a.length,b=function(){var e,n=a[x],d=n.document,y=n.previous,b=d[t],w=d._deleted,j=y&&y._deleted,k=void 0;if(g&&(k=r.get(b)),k){var _=k._rev;if(!y||y&&_!==y._rev){var D={isError:!0,status:409,documentId:b,writeRow:n,documentInDb:k};return h.push(D),1}var I=c?Fe(n):n;c&&(w?y&&Object.keys(y._attachments).forEach((e=>{f.push({documentId:b,attachmentId:e,digest:(0,le.Is)(y)._attachments[e].digest})})):(Object.entries(d._attachments).find((t=>{let[r,a]=t;return(y?y._attachments[r]:void 0)||a.data||(e={documentId:b,documentInDb:k,isError:!0,status:510,writeRow:n,attachmentId:r}),!0})),e||Object.entries(d._attachments).forEach((e=>{let[t,r]=e;var a=y?y._attachments[t]:void 0;if(a){var n=I.document._attachments[t].digest;r.data&&a.digest!==n&&v.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})}else p.push({documentId:b,attachmentId:t,attachmentData:r,digest:r.digest})})))),e?h.push(e):(c?(u.push(Fe(I)),i&&i(d)):(u.push(I),i&&i(d)),o=I);var E=null,C=null,R=null;if(j&&!w)R="INSERT",E=c?He(d):d;else if(!y||j||w){if(!w)throw N("SNH",{args:{writeRow:n}});R="DELETE",E=(0,le.Is)(d),C=y}else R="UPDATE",E=c?He(d):d,C=y;var O={documentId:b,documentData:E,previousDocumentData:C,operation:R};m.push(O)}else{var S=!!w;if(c&&Object.entries(d._attachments).forEach((t=>{let[r,a]=t;a.data?p.push({documentId:b,attachmentId:r,attachmentData:a,digest:a.digest}):(e={documentId:b,isError:!0,status:510,writeRow:n,attachmentId:r},h.push(e))})),e||(c?(l.push(Fe(n)),s&&s(d)):(l.push(n),s&&s(d)),o=n),!S){var P={documentId:b,operation:"INSERT",documentData:c?He(d):d,previousDocumentData:c&&y?He(y):y};m.push(P)}}},x=0;x{n.success.push(e.document),o.push(e.document)})),r.bulkUpdateDocs.forEach((e=>{n.success.push(e.document),o.push(e.document)})),(o=o.map((e=>G(a.booleanIndexes,e)))).length>0&&await a.dexieTable.bulkPut(o);var c=[];r.attachmentsAdd.forEach((e=>{c.push({id:se(e.documentId,e.attachmentId),data:e.attachmentData.data})})),r.attachmentsUpdate.forEach((e=>{c.push({id:se(e.documentId,e.attachmentId),data:e.attachmentData.data})})),await a.dexieAttachmentsTable.bulkPut(c),await a.dexieAttachmentsTable.bulkDelete(r.attachmentsRemove.map((e=>se(e.documentId,e.attachmentId))))})),(r=(0,le.Is)(r)).eventBulk.events.length>0){var i=(0,le.Is)(r.newestRow).document;r.eventBulk.checkpoint={id:i[this.primaryPath],lwt:i._meta.lwt},r.eventBulk.endTime=(0,ce.z)(),this.changes$.next(r.eventBulk)}return n},t.findDocumentsById=async function(e,t){tt(this);var r=await this.internals,a=[];return await r.dexieDb.transaction("r",r.dexieTable,(async()=>{(await ne(this.internals,e)).forEach((e=>{!e||e._deleted&&!t||a.push(e)}))})),a},t.query=function(e){return tt(this),Be(this,e)},t.count=async function(e){if(e.queryPlan.selectorSatisfiedByIndex){var t=await async function(e,t){var r=await e.internals,a=t.queryPlan,n=a.index,s=Pe(r.booleanIndexes,a,r.dexieDb._options.IDBKeyRange),i=-1;return await r.dexieDb.transaction("r",r.dexieTable,(async e=>{var t,r=e.idbtrans.objectStore(H);t="["+n.map((e=>X(e))).join("+")+"]";var a=r.index(t).count(s);i=await new Promise(((e,t)=>{a.onsuccess=function(){e(a.result)},a.onerror=e=>t(e)}))})),i}(this,e);return{count:t,mode:"fast"}}return{count:(await Be(this,e)).documents.length,mode:"slow"}},t.changeStream=function(){return tt(this),this.changes$.asObservable()},t.cleanup=async function(e){tt(this);var t=await this.internals;return await t.dexieDb.transaction("rw",t.dexieTable,(async()=>{var r=(0,ce.z)()-e,a=await t.dexieTable.where("_meta.lwt").below(r).toArray(),n=[];a.forEach((e=>{"1"===e._deleted&&n.push(e[this.primaryPath])})),await t.dexieTable.bulkDelete(n)})),!0},t.getAttachmentData=async function(e,t,r){tt(this);var a=await this.internals,n=se(e,t);return await a.dexieDb.transaction("r",a.dexieAttachmentsTable,(async()=>{var r=await a.dexieAttachmentsTable.get(n);if(r)return r.data;throw new Error("attachment missing documentId: "+e+" attachmentId: "+t)}))},t.remove=async function(){tt(this);var e=await this.internals;return await e.dexieTable.clear(),this.close()},t.close=function(){return this.closed||(this.closed=(async()=>{this.changes$.complete(),await async function(e){var t=await e,r=J.get(e)-1;0===r?(t.dexieDb.close(),J.delete(e)):J.set(e,r)}(this.internals)})()),this.closed},t.conflictResultionTasks=function(){return new oe.x},t.resolveConflictResultionTask=async function(e){},e}();async function et(e,t,r){var n=function(e,t,r,n){var o="rxdb-dexie-"+e+"--"+n.version+"--"+t,c=s(Z,o,(()=>{var e=(async()=>{var e=i(r);e.autoOpen=!1;var t=new a.U(o,e),s={[H]:ae(n),[z]:"++sequence, id",[K]:"id"};return t.version(1).stores(s),await t.open(),{dexieDb:t,dexieTable:t[H],dexieAttachmentsTable:t[K],booleanIndexes:ie(n)}})();return Z.set(o,c),J.set(c,0),e}));return c}(t.databaseName,t.collectionName,r,t.schema),o=new Ge(e,t.databaseName,t.collectionName,t.schema,n,t.options,r);return await Xe(U,t,o),Promise.resolve(o)}function tt(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var rt="15.4.0",at=function(){function e(e){this.name=U,this.rxdbVersion=rt,this.settings=e}return e.prototype.createStorageInstance=function(e){return function(e){if(e.schema.keyCompression)throw N("UT5",{args:{params:e}});if((t=e.schema).encrypted&&t.encrypted.length>0||t.attachments&&t.attachments.encrypted)throw N("UT6",{args:{params:e}});var t;if(e.schema.attachments&&e.schema.attachments.compression)throw N("UT7",{args:{params:e}})}(e),et(this,e,this.settings)},e}();function nt(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;var r,a;if(Array.isArray(e)){if((r=e.length)!==t.length)return!1;for(a=r;0!=a--;)if(!nt(e[a],t[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var n=Object.keys(e);if((r=n.length)!==Object.keys(t).length)return!1;for(a=r;0!=a--;)if(!Object.prototype.hasOwnProperty.call(t,n[a]))return!1;for(a=r;0!=a--;){var s=n[a];if(!nt(e[s],t[s]))return!1}return!0}return e!=e&&t!=t}var st={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],postDestroyRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preMigrateDocument:[],postMigrateDocument:[],preDestroyRxDatabase:[],postRemoveRxDatabase:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function it(e,t){st[e]&&st[e].forEach((e=>e(t)))}function ot(e,t){return Promise.all(st[e].map((e=>e(t))))}var ct=function(){function e(e,t){this.jsonSchema=e,this.hashFunction=t,this.indexes=function(e){return(e.indexes||[]).map((e=>(0,y.AD)(e)?e:[e]))}(this.jsonSchema),this.primaryPath=A(this.jsonSchema.primaryKey),this.finalFields=F(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(e,t){this.finalFields.forEach((r=>{if(!nt(e[r],t[r]))throw N("DOC9",{dataBefore:e,dataAfter:t,fieldName:r,schema:this.jsonSchema})}))},t.getDocumentPrototype=function(){var e={},t=q(this.jsonSchema,"");return Object.keys(t).forEach((t=>{var r=t;e.__defineGetter__(t,(function(){if(this.get&&"function"==typeof this.get)return this.get(r)})),Object.defineProperty(e,t+"$",{get:function(){return this.get$(r)},enumerable:!1,configurable:!1}),Object.defineProperty(e,t+"_",{get:function(){return this.populate(r)},enumerable:!1,configurable:!1})})),l(this,"getDocumentPrototype",(()=>e)),e},t.getPrimaryOfDocumentData=function(e){return L(this.jsonSchema,e)},(0,b.Z)(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var e={};return Object.entries(this.jsonSchema.properties).filter((e=>{let[,t]=e;return Object.prototype.hasOwnProperty.call(t,"default")})).forEach((t=>{let[r,a]=t;return e[r]=a.default})),l(this,"defaultValues",e)}},{key:"hash",get:function(){return l(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}]),e}();function lt(e,t,r){void 0===r&&(r=!0),r&&it("preCreateRxSchema",e);var a=Q(e);a=function(e){return o(e,!0)}(a),j.deepFreezeWhenDevMode(a);var n=new ct(a,t);return it("createRxSchema",n),n}var ut=r(598),ht=r(6621),dt=r(6728),mt=r(6005),pt=r(7570),ft=r(4419);function vt(e){var t=e.split("-"),r="RxDB";return t.forEach((e=>{r+=P(e)})),r+="Plugin",new Error("You are using a function which must be overwritten by a plugin.\n You should either prevent the usage of this function or add the plugin via:\n import { "+r+" } from 'rxdb/plugins/"+e+"';\n addRxPlugin("+r+");\n ")}function gt(e){return e.documentData?e.documentData:e.previousDocumentData}var yt=function(){function e(e,t,r,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=e,this.primaryPath=t,this.preWrite=r,this.postWrite=a}var t=e.prototype;return t.addWrite=function(e,t){var r=e[this.primaryPath],a=s(this.queueByDocId,r,(()=>[]));return new Promise(((r,n)=>{var s={lastKnownDocumentState:e,modifier:t,resolve:r,reject:n};(0,le.Is)(a).push(s),this.triggerRun()}))},t.triggerRun=async function(){if(!0!==this.isRunning&&0!==this.queueByDocId.size){this.isRunning=!0;var e=[],t=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(t.entries()).map((async t=>{let[r,a]=t;var n,s,i,o=(n=a.map((e=>e.lastKnownDocumentState)),s=n[0],i=$e(s._rev).height,n.forEach((e=>{var t=$e(e._rev).height;t>i&&(s=e,i=t)})),s),l=o;for(var u of a)try{l=await u.modifier(c(l))}catch(h){u.reject(h),u.reject=()=>{},u.resolve=()=>{}}try{await this.preWrite(l,o)}catch(h){return void a.forEach((e=>e.reject(h)))}e.push({previous:o,document:l})})));var r=e.length>0?await this.storageInstance.bulkWrite(e,"incremental-write"):{error:[],success:[]};return await Promise.all(r.success.map((e=>{var r=e[this.primaryPath];this.postWrite(e),n(t,r).forEach((t=>t.resolve(e)))}))),r.error.forEach((e=>{var r,a=e.documentId,i=n(t,a),o=E(e);if(o){var c=s(this.queueByDocId,a,(()=>[]));i.reverse().forEach((e=>{e.lastKnownDocumentState=(0,le.Is)(o.documentInDb),(0,le.Is)(c).unshift(e)}))}else{var l=N("COL20",{name:C[(r=e).status],document:r.documentId,writeError:r});i.forEach((e=>e.reject(l)))}})),this.isRunning=!1,this.triggerRun()}},e}();function bt(e){return async t=>{var r=function(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}(t);r._deleted=t._deleted;var a=await e(r),n=Object.assign({},a,{_meta:t._meta,_attachments:t._attachments,_rev:t._rev,_deleted:void 0!==a._deleted?a._deleted:t._deleted});return void 0===n._deleted&&(n._deleted=!1),n}}var xt={get primaryPath(){if(this.isInstanceOfRxDocument)return this.collection.schema.primaryPath},get primary(){var e=this;if(e.isInstanceOfRxDocument)return e._data[e.primaryPath]},get revision(){if(this.isInstanceOfRxDocument)return this._data._rev},get deleted$(){if(this.isInstanceOfRxDocument)return this.$.pipe((0,ut.U)((e=>e._data._deleted)))},get deleted(){if(this.isInstanceOfRxDocument)return this._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){return this.collection.$.pipe((0,ht.h)((e=>!e.isLocal)),(0,ht.h)((e=>e.documentId===this.primary)),(0,ut.U)((e=>gt(e))),(0,dt.O)(this.collection._docCache.getLatestDocumentData(this.primary)),(0,mt.x)(((e,t)=>e._rev===t._rev)),(0,ut.U)((e=>this.collection._docCache.getCachedRxDocument(e))),(0,pt.d)(le.kv))},get$(e){if(j.isDevMode()){if(e.includes(".item."))throw N("DOC1",{path:e});if(e===this.primaryPath)throw N("DOC2");if(this.collection.schema.finalFields.includes(e))throw N("DOC3",{path:e});if(!q(this.collection.schema.jsonSchema,e))throw N("DOC4",{path:e})}return this.$.pipe((0,ut.U)((t=>v(t,e))),(0,mt.x)())},populate(e){var t=q(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return ft.m5;if(!t)throw N("DOC5",{path:e});if(!t.ref)throw N("DOC6",{path:e,schemaObj:t});var a=this.collection.database.collections[t.ref];if(!a)throw N("DOC7",{ref:t.ref,path:e,schemaObj:t});return"array"===t.type?a.findByIds(r).exec().then((e=>{var t=e.values();return Array.from(t)})):a.findOne(r).exec()},get(e){return s(this._propertyCache,e,(()=>{var t=v(this._data,e);if("object"!=typeof t||null===t||Array.isArray(t))return j.deepFreezeWhenDevMode(t);var r=this;return new Proxy(i(t),{get(t,a){if("string"!=typeof a)return t[a];var n=a.charAt(a.length-1);if("$"===n){var s=a.slice(0,-1);return r.get$(B(e+"."+s))}if("_"===n){var i=a.slice(0,-1);return r.populate(B(e+"."+i))}return r.get(B(e+"."+a))}})}))},toJSON(e){if(void 0===e&&(e=!1),e)return j.deepFreezeWhenDevMode(this._data);var t=i(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,j.deepFreezeWhenDevMode(t)},toMutableJSON(e){return void 0===e&&(e=!1),c(this.toJSON(e))},update(e){throw vt("update")},incrementalUpdate(e){throw vt("update")},updateCRDT(e){throw vt("crdt")},putAttachment(){throw vt("attachments")},getAttachment(){throw vt("attachments")},allAttachments(){throw vt("attachments")},get allAttachments$(){throw vt("attachments")},async modify(e,t){var r=this._data,a=await bt(e)(r);return this._saveData(a,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,bt(e)).then((e=>this.collection._docCache.getCachedRxDocument(e)))},patch(e){var t=this._data,r=c(t);return Object.entries(e).forEach((e=>{let[t,a]=e;r[t]=a})),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e,t){if(e=i(e),this._data._deleted)throw N("DOC11",{id:this.primary,document:this});await jt(this.collection,e,t);var r=await this.collection.storageInstance.bulkWrite([{previous:t,document:e}],"rx-document-save-data"),a=r.error[0];return We(this.collection,this.primary,e,a),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(r.success[0])},remove(){var e=this.collection;if(this.deleted)return Promise.reject(N("DOC13",{document:this,id:this.primary}));var t,r=i(this._data);return e._runHooks("pre","remove",r,this).then((async()=>{r._deleted=!0;var t=await e.storageInstance.bulkWrite([{previous:this._data,document:r}],"rx-document-remove"),a=t.error[0];return We(e,this.primary,r,a),t.success[0]})).then((e=>(t=e,this.collection._runHooks("post","remove",r,this)))).then((()=>this.collection._docCache.getCachedRxDocument(t)))},incrementalRemove(){return this.incrementalModify((async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e))).then((async e=>(await this.collection._runHooks("post","remove",e._data,e),e)))},destroy(){throw N("DOC14")}};function wt(e){void 0===e&&(e=xt);var t=function(e,t){this.collection=e,this._data=t,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function jt(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),j.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}var kt=r(10),_t=r(6871),Dt=r(3028),Nt=r(1556),It=r(8456);function Et(e,t){return t.sort&&0!==t.sort.length?t.sort.map((e=>Object.keys(e)[0])):[e]}var Ct=new WeakMap;function Rt(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};var r=function(e){return s(Ct,e,(()=>{var t=e.collection,r=Ee(t.storageInstance.schema,c(e.mangoQuery)),a=t.schema.primaryPath,n=Ce(t.schema.jsonSchema,r),s=Re(t.schema.jsonSchema,r);return{primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:Et(a,r),sortComparator:(t,r)=>{var a={docA:t,docB:r,rxQuery:e};return n(a.docA,a.docB)},queryMatcher:t=>s({doc:t,rxQuery:e}.doc)}}))}(e),a=(0,le.Is)(e._result).docsData.slice(0),n=(0,le.Is)(e._result).docsDataMap,i=!1;return t.map((e=>function(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:j.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}(e))).filter(y.S7).find((e=>{var t={queryParams:r,changeEvent:e,previousResults:a,keyDocumentMap:n},s=(0,It.Rf)(t);return"runFullQueryAgain"===s||("doNothing"!==s?(i=!0,(0,It.wu)(s,r,e,a,n),!1):void 0)}))?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:i,newResults:a}}var Ot=function(){function e(){this._map=new Map}return e.prototype.getByQuery=function(e){var t=e.toString();return s(this._map,t,(()=>e))},e}();function St(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function Pt(e){return e.refCount$.observers.length}var Bt,$t,Tt=(Bt=100,$t=3e4,(e,t)=>{if(!(t._map.size0||(0===s._lastEnsureEqual&&s._creationTimee._lastEnsureEqual-t._lastEnsureEqual)).slice(0,i).forEach((e=>St(t,e)))}}),qt=new WeakSet;var Mt=function(){function e(e,t,r){this.cacheItemByDocId=new Map,this.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry((e=>{var t=e.docId,r=this.cacheItemByDocId.get(t);r&&(r.byRev.delete(e.revisionHeight),0===r.byRev.size&&this.cacheItemByDocId.delete(t))})):void 0,this.registerIdleTasks=[],this.primaryPath=e,this.changes$=t,this.documentCreator=r,t.subscribe((e=>{var t=e.documentId,r=this.cacheItemByDocId.get(t);if(r){var a=gt(e);r.last=a}}))}var t=e.prototype;return t.getLatestDocumentData=function(e){return n(this.cacheItemByDocId,e).last},t.getLatestDocumentDataIfExists=function(e){var t=this.cacheItemByDocId.get(e);if(t)return t.last},(0,b.Z)(e,[{key:"getCachedRxDocument",get:function(){return l(this,"getCachedRxDocument",function(e){var t=e.primaryPath,r=e.cacheItemByDocId,a=e.registry,n=j.deepFreezeWhenDevMode,i=e.documentCreator,o=o=>{var c=o[t],l=Te(o._rev),u=s(r,c,(()=>function(e){return{byRev:new Map,last:e}}(o))),h=u.byRev,d=h.get(l),m=d?d.deref():void 0;return m||(o=n(o),m=i(o),h.set(l,Lt(m)),a&&(e.registerIdleTasks.push(m),e.registerIdlePromise||(e.registerIdlePromise=(0,ft.y$)().then((()=>{e.registerIdlePromise=void 0;var t=e.registerIdleTasks;0!==t.length&&(e.registerIdleTasks=[],t.forEach((e=>{a.register(e,{docId:e.primary,revisionHeight:Te(e.revision)})})))}))))),m};return o}(this))}}]),e}();function At(e,t){for(var r=e.getCachedRxDocument,a=[],n=0;ne}};var Qt=function(){function e(e,t,r){this.time=(0,ce.z)(),this.collection=e,this.count=r,this.documents=At(this.collection._docCache,t)}return(0,b.Z)(e,[{key:"docsData",get:function(){return l(this,"docsData",this.documents.map((e=>e._data)))}},{key:"docsDataMap",get:function(){var e=new Map;return this.documents.forEach((t=>{e.set(t.primary,t._data)})),l(this,"docsDataMap",e)}},{key:"docsMap",get:function(){for(var e=new Map,t=this.documents,r=0;r"string"!=typeof e)))return r.$eq}return!1}(this.collection.schema.primaryPath,t)}var t=e.prototype;return t._setResultData=function(e){if("number"!=typeof e){e instanceof Map&&(e=Array.from(e.values()));var t=new Qt(this.collection,e,e.length);this._result=t}else this._result=new Qt(this.collection,[],e)},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this._lastExecStart=(0,ce.z)(),"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 N("QU14",{collection:this.collection,queryObj:this.mangoQuery})}if("findByIds"===this.op){var r=(0,le.Is)(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,a=new Map,n=[];if(r.forEach((e=>{var t=this.collection._docCache.getLatestDocumentDataIfExists(e);if(t){if(!t._deleted){var r=this.collection._docCache.getCachedRxDocument(t);a.set(e,r)}}else n.push(e)})),n.length>0)(await this.collection.storageInstance.findDocumentsById(n,!1)).forEach((e=>{var t=this.collection._docCache.getCachedRxDocument(e);a.set(t.primary,t)}));return a}var s=async function(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var a=e.isFindOneByIdQuery;if(a=a.filter((r=>{var a=e.collection._docCache.getLatestDocumentDataIfExists(r);return!a||(a._deleted||t.push(a),!1)})),a.length>0){var n=await r.storageInstance.findDocumentsById(a,!1);(0,y.gu)(t,n)}}else{var s=e.isFindOneByIdQuery,i=e.collection._docCache.getLatestDocumentDataIfExists(s);if(!i){var o=await r.storageInstance.findDocumentsById([s],!1);o[0]&&(i=o[0])}i&&!i._deleted&&t.push(i)}else{var c=e.getPreparedQuery(),l=await r.storageInstance.query(c);t=l.documents}return t}(this);return s.then((e=>(this._lastExecEnd=(0,ce.z)(),e)))},t.exec=function(e){if(e&&"findOne"!==this.op)throw N("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return Kt(this).then((()=>(0,_t.z)(this.$))).then((t=>{if(!t&&e)throw N("QU10",{collection:this.collection.name,query:this.mangoQuery,op:this.op});return t}))},t.toString=function(){var e=o({op:this.op,query:this.mangoQuery,other:this.other},!0),t=JSON.stringify(e);return this.toString=()=>t,t},t.getPreparedQuery=function(){var e={rxQuery:this,mangoQuery:Ee(this.collection.schema.jsonSchema,this.mangoQuery)};e.mangoQuery.selector._deleted={$eq:!1},e.mangoQuery.index&&e.mangoQuery.index.unshift("_deleted"),it("prePrepareQuery",e);var t=Ut(this.collection.schema.jsonSchema,e.mangoQuery);return this.getPreparedQuery=()=>t,t},t.doesDocumentDataMatch=function(e){return!e._deleted&&this.queryMatcher(e)},t.remove=function(){return this.exec().then((e=>Array.isArray(e)?Promise.all(e.map((e=>e.remove()))):e.remove()))},t.update=function(e){throw vt("update")},t.where=function(e){throw vt("query-builder")},t.sort=function(e){throw vt("query-builder")},t.skip=function(e){throw vt("query-builder")},t.limit=function(e){throw vt("query-builder")},(0,b.Z)(e,[{key:"$",get:function(){if(!this._$){var e=this.collection.$.pipe((0,ht.h)((e=>!e.isLocal)),(0,dt.O)(null),(0,Nt.z)((()=>Kt(this))),(0,ut.U)((()=>this._result)),(0,pt.d)(le.kv),(0,mt.x)(((e,t)=>!(!e||e.time!==(0,le.Is)(t).time))),(0,ht.h)((e=>!!e)),(0,ut.U)((e=>{var t=(0,le.Is)(e);return"count"===this.op?t.count:"findOne"===this.op?0===t.documents.length?null:t.documents[0]:"findByIds"===this.op?t.docsMap:t.documents.slice(0)})));this._$=(0,Dt.T)(e,this.refCount$.pipe((0,ht.h)((()=>!1))))}return this._$}},{key:"queryMatcher",get:function(){this.collection.schema.jsonSchema;return l(this,"queryMatcher",Re(0,Ee(this.collection.schema.jsonSchema,this.mangoQuery)))}},{key:"asRxQuery",get:function(){return this}}]),e}();function Ht(e,t,r,a){it("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:a});var n,s,i=new Ft(e,t,r,a);return i=(n=i).collection._queryCache.getByQuery(n),s=r,qt.has(s)||(qt.add(s),(0,ft.Y3)().then((()=>(0,ft.C2)(200))).then((()=>{s.destroyed||s.cacheReplacementPolicy(s,s._queryCache),qt.delete(s)}))),i}function zt(e){var t=e.asRxQuery.collection._changeEventBuffer.counter;return e._latestChangeEvent>=t}function Kt(e){return e.collection.database.destroyed||zt(e)?ft.kZ:(e._ensureEqualQueue=e._ensureEqualQueue.then((()=>function(e){if(e._lastEnsureEqual=(0,ce.z)(),e.collection.database.destroyed||zt(e))return ft.kZ;var t=!1,r=!1;-1===e._latestChangeEvent&&(r=!0);if(!r){var a=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(null===a)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.counter;var n=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(a);if("count"===e.op){var s=(0,le.Is)(e._result).count,i=s;n.forEach((t=>{var r=t.previousDocumentData&&e.doesDocumentDataMatch(t.previousDocumentData),a=e.doesDocumentDataMatch(t.documentData);!r&&a&&i++,r&&!a&&i--})),i!==s&&(t=!0,e._setResultData(i))}else{var o=Rt(e,n);o.runFullQueryAgain?r=!0:o.changed&&(t=!0,e._setResultData(o.newResults))}}}if(r)return e._execOverDatabase().then((r=>(e._latestChangeEvent=e.collection._changeEventBuffer.counter,"number"==typeof r?(e._result&&r===e._result.count||(t=!0,e._setResultData(r)),t):(e._result&&function(e,t,r){if(t.length!==r.length)return!1;for(var a=0,n=t.length;ae.data.name===n)),c=[];o.forEach((e=>{c.push({collectionName:e.data.name,schema:e.data.schema,isCollection:!0}),e.data.connectedStorages.forEach((e=>c.push({collectionName:e.collectionName,isCollection:!1,schema:e.schema})))}));var l=new Set;if(c=c.filter((e=>{var t=e.collectionName+"||"+e.schema.version;return!l.has(t)&&(l.add(t),!0)})),await Promise.all(c.map((async t=>{var i=await e.createStorageInstance({collectionName:t.collectionName,databaseInstanceToken:r,databaseName:a,multiInstance:!1,options:{},schema:t.schema,password:s,devMode:j.isDevMode()});await i.remove(),t.isCollection&&await ot("postRemoveRxCollection",{storage:e,databaseName:a,collectionName:n})}))),i){var u=o.map((e=>{var t=ze(e);return t._deleted=!0,t._meta.lwt=(0,ce.z)(),t._rev=qe(r,e),{previous:e,document:t}}));await t.bulkWrite(u,"rx-database-remove-collection-all")}}var nr=function(){function e(e){this.subs=[],this.limit=100,this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.collection=e,this.subs.push(this.collection.$.pipe((0,ht.h)((e=>!e.isLocal))).subscribe((e=>this._handleChangeEvent(e))))}var t=e.prototype;return t._handleChangeEvent=function(e){for(this.counter++,this.buffer.push(e),this.eventCounterMap.set(e,this.counter);this.buffer.length>this.limit;)this.buffer.shift()},t.getArrayIndexByPointer=function(e){var t=this.buffer[0],r=this.eventCounterMap.get(t);return et(e)))},t.reduceByLastOfDoc=function(e){return e.slice(0)},t.destroy=function(){this.subs.forEach((e=>e.unsubscribe()))},e}();var sr=new WeakMap;function ir(e){var t=e.schema.getDocumentPrototype(),r=function(e){var t={};return Object.entries(e.methods).forEach((e=>{let[r,a]=e;t[r]=a})),t}(e),a={};return[t,r,xt].forEach((e=>{Object.getOwnPropertyNames(e).forEach((t=>{var r=Object.getOwnPropertyDescriptor(e,t),n=!0;(t.startsWith("_")||t.endsWith("_")||t.startsWith("$")||t.endsWith("$"))&&(n=!1),"function"==typeof r.value?Object.defineProperty(a,t,{get(){return r.value.bind(this)},enumerable:n,configurable:!1}):(r.enumerable=n,r.configurable=!1,r.writable&&(r.writable=!1),Object.defineProperty(a,t,r))}))})),a}function or(e,t){var r=function(e,t,r){var a=new e(t,r);return it("createRxDocument",a),a}(function(e){return s(sr,e,(()=>wt(ir(e))))}(e),e,j.deepFreezeWhenDevMode(t));return e._runHooksSync("post","create",t,r),it("postCreateRxDocument",r),r}var cr=function(e,t){return nt(He(e.newDocumentState),He(e.realMasterState))?Promise.resolve({isEqual:!0}):Promise.resolve({isEqual:!1,documentData:e.realMasterState})};var lr=["pre","post"],ur=["insert","save","remove","create"],hr=!1,dr=function(){function e(e,t,r,a,n,s,i,o,c,l,u,h){void 0===n&&(n={}),void 0===s&&(s={}),void 0===i&&(i={}),void 0===o&&(o={}),void 0===c&&(c={}),void 0===l&&(l=Tt),void 0===u&&(u={}),void 0===h&&(h=cr),this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=new Ot,this.$={},this.checkpoint$={},this._changeEventBuffer={},this.onDestroy=[],this.destroyed=!1,this.database=e,this.name=t,this.schema=r,this.internalStorageInstance=a,this.instanceCreationOptions=n,this.migrationStrategies=s,this.methods=i,this.attachments=o,this.options=c,this.cacheReplacementPolicy=l,this.statics=u,this.conflictHandler=h,function(e){if(hr)return;hr=!0;var t=Object.getPrototypeOf(e);ur.forEach((e=>{lr.map((r=>{var a=r+P(e);t[a]=function(t,a){return this.addHook(r,e,t,a)}}))}))}(this.asRxCollection)}var t=e.prototype;return t.prepare=async function(){this.storageInstance=Ke(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new yt(this.storageInstance,this.schema.primaryPath,((e,t)=>jt(this,e,t)),(e=>this._runHooks("post","save",e)));var e,t=this.database.eventBulks$.pipe((0,ht.h)((e=>e.collectionName===this.name)));this.$=t.pipe((0,Nt.z)((e=>e.events))),this.checkpoint$=t.pipe((0,ut.U)((e=>e.checkpoint))),this._changeEventBuffer=(e=this.asRxCollection,new nr(e)),this._docCache=new Mt(this.schema.primaryPath,this.$.pipe((0,ht.h)((e=>!e.isLocal))),(e=>or(this.asRxCollection,e)));var r=await this.database.storageToken,a=this.storageInstance.changeStream().subscribe((e=>{var t={id:e.id,internal:!1,collectionName:this.name,storageToken:r,events:e.events.map((e=>Qe(!1,e,this))),databaseToken:this.database.token,checkpoint:e.checkpoint,context:e.context,endTime:e.endTime,startTime:e.startTime};this.database.$emit(t)}));return this._subs.push(a),this._subs.push(this.storageInstance.conflictResultionTasks().subscribe((e=>{this.conflictHandler(e.input,e.context).then((t=>{this.storageInstance.resolveConflictResultionTask({id:e.id,output:t})}))}))),ft.$Y},t.cleanup=function(e){throw vt("cleanup")},t.migrationNeeded=function(){throw vt("migration-schema")},t.getMigrationState=function(){throw vt("migration-schema")},t.startMigration=function(e){return void 0===e&&(e=10),this.getMigrationState().startMigration(e)},t.migratePromise=function(e){return void 0===e&&(e=10),this.getMigrationState().migratePromise(e)},t.insert=async function(e){var t=await this.bulkInsert([e]),r=t.error[0];return We(this,e[this.schema.primaryPath],e,r),(0,le.Is)(t.success[0])},t.bulkInsert=async function(e){if(0===e.length)return{success:[],error:[]};var t=this.schema.primaryPath,r=e.map((e=>rr(this.schema,e))),a=this.hasHooks("pre","insert")?await Promise.all(r.map((e=>this._runHooks("pre","insert",e).then((()=>e))))):r,n=a.map((e=>({document:e}))),s=await this.storageInstance.bulkWrite(n,"rx-collection-bulk-insert"),i=At(this._docCache,s.success);if(this.hasHooks("post","insert")){var o=new Map;a.forEach((e=>{o.set(e[t],e)})),await Promise.all(i.map((e=>this._runHooks("post","insert",o.get(e.primary),e))))}return{success:i,error:s.error}},t.bulkRemove=async function(e){var t=this.schema.primaryPath;if(0===e.length)return{success:[],error:[]};var r=await this.findByIds(e).exec(),a=[],s=new Map;Array.from(r.values()).forEach((e=>{var t=e.toMutableJSON(!0);a.push(t),s.set(e.primary,t)})),await Promise.all(a.map((e=>{var t=e[this.schema.primaryPath];return this._runHooks("pre","remove",e,r.get(t))})));var o=a.map((e=>{var t=i(e);return t._deleted=!0,{previous:e,document:t}})),c=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-remove"),l=c.success.map((e=>e[t]));return await Promise.all(l.map((e=>this._runHooks("post","remove",s.get(e),r.get(e))))),{success:l.map((e=>n(r,e))),error:c.error}},t.bulkUpsert=async function(e){var t=[],r=new Map;e.forEach((e=>{var a=rr(this.schema,e),n=a[this.schema.primaryPath];if(!n)throw N("COL3",{primaryPath:this.schema.primaryPath,data:a,schema:this.schema.jsonSchema});r.set(n,a),t.push(a)}));var a=await this.bulkInsert(t),s=a.success.slice(0),i=[];return await Promise.all(a.error.map((async e=>{if(409!==e.status)i.push(e);else{var t=e.documentId,a=n(r,t),o=(0,le.Is)(e.documentInDb),c=this._docCache.getCachedRxDocument(o),l=await c.incrementalModify((()=>a));s.push(l)}}))),{error:i,success:s}},t.upsert=async function(e){var t=await this.bulkUpsert([e]);return We(this.asRxCollection,e[this.schema.primaryPath],e,t.error[0]),t.success[0]},t.incrementalUpsert=function(e){var t=rr(this.schema,e),r=t[this.schema.primaryPath];if(!r)throw N("COL4",{data:e});var a=this._incrementalUpsertQueues.get(r);return a||(a=ft.$Y),a=a.then((()=>function(e,t,r){var a=e._docCache.getLatestDocumentDataIfExists(t);if(a)return Promise.resolve({doc:e._docCache.getCachedRxDocument(a),inserted:!1});return e.findOne(t).exec().then((t=>t?{doc:t,inserted:!1}:e.insert(r).then((e=>({doc:e,inserted:!0})))))}(this,r,t))).then((e=>e.inserted?e.doc:function(e,t){return e.incrementalModify((e=>t))}(e.doc,t))),this._incrementalUpsertQueues.set(r,a),a},t.find=function(e){if("string"==typeof e)throw N("COL5",{queryObj:e});return e||(e={selector:{}}),Ht("find",e,this)},t.findOne=function(e){if("number"==typeof e||Array.isArray(e))throw I("COL6",{queryObj:e});var t;if("string"==typeof e)t=Ht("findOne",{selector:{[this.schema.primaryPath]:e},limit:1},this);else{if(e||(e={selector:{}}),e.limit)throw N("QU6");(e=i(e)).limit=1,t=Ht("findOne",e,this)}return t},t.count=function(e){return e||(e={selector:{}}),Ht("count",e,this)},t.findByIds=function(e){return Ht("findByIds",{selector:{[this.schema.primaryPath]:{$in:e.slice(0)}}},this)},t.exportJSON=function(){throw vt("json-dump")},t.importJSON=function(e){throw vt("json-dump")},t.insertCRDT=function(e){throw vt("crdt")},t.addHook=function(e,t,r,a){if(void 0===a&&(a=!1),"function"!=typeof r)throw I("COL7",{key:t,when:e});if(!lr.includes(e))throw I("COL8",{key:t,when:e});if(!ur.includes(t))throw N("COL9",{key:t});if("post"===e&&"create"===t&&!0===a)throw N("COL10",{when:e,key:t,parallel:a});var n=r.bind(this),s=a?"parallel":"series";this.hooks[t]=this.hooks[t]||{},this.hooks[t][e]=this.hooks[t][e]||{series:[],parallel:[]},this.hooks[t][e][s].push(n)},t.getHooks=function(e,t){return this.hooks[t]&&this.hooks[t][e]?this.hooks[t][e]:{series:[],parallel:[]}},t.hasHooks=function(e,t){var r=this.getHooks(e,t);return!!r&&(r.series.length>0||r.parallel.length>0)},t._runHooks=function(e,t,r,a){var n=this.getHooks(e,t);if(!n)return ft.$Y;var s=n.series.map((e=>()=>e(r,a)));return(0,ft.Ze)(s).then((()=>Promise.all(n.parallel.map((e=>e(r,a))))))},t._runHooksSync=function(e,t,r,a){var n=this.getHooks(e,t);n&&n.series.forEach((e=>e(r,a)))},t.promiseWait=function(e){return new Promise((t=>{var r=setTimeout((()=>{this.timeouts.delete(r),t()}),e);this.timeouts.add(r)}))},t.destroy=function(){return this.destroyed?ft.kZ:(this.destroyed=!0,Array.from(this.timeouts).forEach((e=>clearTimeout(e))),this._changeEventBuffer&&this._changeEventBuffer.destroy(),this.database.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>this.storageInstance.close())).then((()=>(this._subs.forEach((e=>e.unsubscribe())),delete this.database.collections[this.name],ot("postDestroyRxCollection",this).then((()=>!0))))))},t.remove=async function(){await this.destroy(),await ar(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.password,this.database.hashFunction)},(0,b.Z)(e,[{key:"insert$",get:function(){return this.$.pipe((0,ht.h)((e=>"INSERT"===e.operation)))}},{key:"update$",get:function(){return this.$.pipe((0,ht.h)((e=>"UPDATE"===e.operation)))}},{key:"remove$",get:function(){return this.$.pipe((0,ht.h)((e=>"DELETE"===e.operation)))}},{key:"asRxCollection",get:function(){return this}}]),e}();var mr=r(7782),pr=r(6753);var fr="undefined"!=typeof crypto&&void 0!==crypto.subtle&&"function"==typeof crypto.subtle.digest?async function(e){var t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.prototype.map.call(new Uint8Array(r),(e=>("00"+e.toString(16)).slice(-2))).join("")}:function(e){return Promise.resolve((0,pr.JQ)(e))},vr=r(5898),gr=new Set,yr=function(){function e(e,t,r,a,n,s,i,o,c,l,u,h){void 0===i&&(i=!1),void 0===o&&(o={}),this.idleQueue=new mr.F,this.rxdbVersion=rt,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onDestroy=[],this.destroyed=!1,this.collections={},this.eventBulks$=new oe.x,this.observable$=this.eventBulks$.pipe((0,Nt.z)((e=>e.events))),this.storageToken=ft.kZ,this.storageTokenDocument=ft.kZ,this.emittedEventBulkIds=new vr.i(6e4),this.name=e,this.token=t,this.storage=r,this.instanceCreationOptions=a,this.password=n,this.multiInstance=s,this.eventReduce=i,this.options=o,this.internalStore=c,this.hashFunction=l,this.cleanupPolicy=u,this.allowSlowCount=h,"pseudoInstance"!==this.name&&(this.internalStore=Ke(this.asRxDatabase,c,Vt),this.storageTokenDocument=async function(e){var t=S(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,a={id:er,context:Jt,key:Gt,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:T(),_rev:"",_attachments:{}},n=await e.internalStore.bulkWrite([{document:a}],"internal-add-storage-token");if(n.success[0])return n.success[0];var s=(0,le.Is)(n.error[0]);if(s.isError&&E(s)){var i=s;if(c=i.documentInDb.data.rxdbVersion,l=e.rxdbVersion,!c||l.includes("beta")&&l!==c||c.split(".")[0]!==l.split(".")[0])throw N("DM5",{args:{database:e.name,databaseStateVersion:i.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==i.documentInDb.data.passwordHash)throw N("DB1",{passwordHash:r,existingPasswordHash:i.documentInDb.data.passwordHash});var o=i.documentInDb;return(0,le.Is)(o)}var c,l;throw s}(this.asRxDatabase).catch((e=>this.startupErrors.push(e))),this.storageToken=this.storageTokenDocument.then((e=>e.data.token)).catch((e=>this.startupErrors.push(e))))}var t=e.prototype;return t.$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 Ae(this.internalStore,Xt(tr(e,t),Zt));if(!r)throw N("SNH",{name:e,schema:t});var a=ze(r);a._deleted=!0,await this.internalStore.bulkWrite([{document:a,previous:r}],"rx-database-remove-collection")},t.addCollections=async function(e){var t={},r={},a=[],n={};await Promise.all(Object.entries(e).map((async e=>{let[s,o]=e;var c=s,l=o.schema;t[c]=l;var u=lt(l,this.hashFunction);if(r[c]=u,this.collections[s])throw N("DB3",{name:s});var h=tr(s,l),d={id:Xt(h,Zt),key:h,context:Zt,data:{name:c,schemaHash:await u.hash,schema:u.jsonSchema,version:u.version,connectedStorages:[]},_deleted:!1,_meta:T(),_rev:"",_attachments:{}};a.push({document:d});var m=Object.assign({},o,{name:c,schema:u,database:this}),p=i(o);p.database=this,p.name=s,it("preCreateRxCollection",p),m.conflictHandler=p.conflictHandler,n[c]=m})));var s=await this.internalStore.bulkWrite(a,"rx-database-add-collection");await async function(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}(this),await Promise.all(s.error.map((async e=>{if(409!==e.status)throw N("DB12",{database:this.name,writeError:e});var a=(0,le.Is)(e.documentInDb),n=a.data.name,s=r[n];if(a.data.schemaHash!==await s.hash)throw N("DB6",{database:this.name,collection:n,previousSchemaHash:a.data.schemaHash,schemaHash:await s.hash,previousSchema:a.data.schema,schema:(0,le.Is)(t[n])})})));var o={};return await Promise.all(Object.keys(e).map((async e=>{var t=n[e],r=await function(e){let{database:t,name:r,schema:a,instanceCreationOptions:n={},migrationStrategies:s={},autoMigrate:i=!0,statics:o={},methods:c={},attachments:l={},options:u={},localDocuments:h=!1,cacheReplacementPolicy:d=Tt,conflictHandler:m=cr}=e;var p={databaseInstanceToken:t.token,databaseName:t.name,collectionName:r,schema:a.jsonSchema,options:n,multiInstance:t.multiInstance,password:t.password,devMode:j.isDevMode()};return it("preCreateRxStorageInstance",p),async function(e,t){return t.multiInstance=e.multiInstance,await e.storage.createStorageInstance(t)}(t,p).then((e=>{var p=new dr(t,r,a,e,n,s,c,l,u,d,o,m);return p.prepare().then((()=>{Object.entries(o).forEach((e=>{let[t,r]=e;Object.defineProperty(p,t,{get:()=>r.bind(p)})}));var e=ft.$Y;return i&&0!==p.schema.version&&(e=p.migratePromise()),e})).then((()=>(it("createRxCollection",{collection:p,creator:{name:r,schema:a,storageInstance:e,instanceCreationOptions:n,migrationStrategies:s,methods:c,attachments:l,options:u,cacheReplacementPolicy:d,localDocuments:h,statics:o}}),p))).catch((t=>e.close().then((()=>Promise.reject(t)))))}))}(t);o[e]=r,this.collections[e]=r,this[e]||Object.defineProperty(this,e,{get:()=>this.collections[e]})}))),o},t.lockedRun=function(e){return this.idleQueue.wrapCall(e)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(e){throw vt("json-dump")},t.importJSON=function(e){throw vt("json-dump")},t.backup=function(e){throw vt("backup")},t.leaderElector=function(){throw vt("leader-election")},t.isLeader=function(){throw vt("leader-election")},t.waitForLeadership=function(){throw vt("leader-election")},t.migrationStates=function(){throw vt("migration-schema")},t.destroy=async function(){return this.destroyed?ft.kZ:(this.destroyed=!0,await ot("preDestroyRxDatabase",this),this.eventBulks$.complete(),this._subs.map((e=>e.unsubscribe())),"pseudoInstance"===this.name?ft.kZ:this.requestIdlePromise().then((()=>Promise.all(this.onDestroy.map((e=>e()))))).then((()=>Promise.all(Object.keys(this.collections).map((e=>this.collections[e])).map((e=>e.destroy()))))).then((()=>this.internalStore.close())).then((()=>gr.delete(this.name))).then((()=>!0)))},t.remove=function(){return this.destroy().then((()=>async function(e,t,r){var a=S(10),n=await br(a,t,e,{},!1,r),s=await Yt(n),i=new Set;s.forEach((e=>i.add(e.data.name)));var o=Array.from(i);return await Promise.all(o.map((s=>ar(t,n,a,e,s,r)))),await ot("postRemoveRxDatabase",{databaseName:e,storage:t}),await n.remove(),o}(this.name,this.storage,this.password)))},(0,b.Z)(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}]),e}();async function br(e,t,r,a,n,s){return await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Me,schema:Vt,options:a,multiInstance:n,password:s,devMode:j.isDevMode()})}function xr(e){let{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s=!0,eventReduce:i=!0,ignoreDuplicate:o=!1,options:c={},cleanupPolicy:l,allowSlowCount:u=!1,localDocuments:h=!1,hashFunction:d=fr}=e;it("preCreateRxDatabase",{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s,eventReduce:i,ignoreDuplicate:o,options:c,localDocuments:h}),o||function(e){if(gr.has(e))throw N("DB8",{name:e,link:"https://pubkey.github.io/rxdb/rx-database.html#ignoreduplicate"})}(a),gr.add(a);var m=S(10);return br(m,t,a,r,s,n).catch((e=>{throw gr.delete(a),e})).then((e=>{var p=new yr(a,m,t,r,n,s,i,c,e,d,l,u);return ot("createRxDatabase",{database:p,creator:{storage:t,instanceCreationOptions:r,name:a,password:n,multiInstance:s,eventReduce:i,ignoreDuplicate:o,options:c,localDocuments:h}}).then((()=>p))}))}var wr={RxSchema:ct.prototype,RxDocument:xt,RxQuery:Ft.prototype,RxCollection:dr.prototype,RxDatabase:yr.prototype},jr=new Set,kr=new Set;var _r=function(e){function t(t,r,a){var n;return(n=e.call(this,null,r)||this).id=t,n.parent=a,n}return(0,x.Z)(t,e),t}(wt()),Dr={get isLocal(){return!0},get allAttachments$(){throw N("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=n(Cr,this.parent);return this.parent.$.pipe((0,ht.h)((e=>e.documentId===this.primary)),(0,ht.h)((e=>e.isLocal)),(0,ut.U)((e=>gt(e))),(0,dt.O)(e.docCache.getLatestDocumentData(this.primary)),(0,mt.x)(((e,t)=>e._rev===t._rev)),(0,ut.U)((t=>e.docCache.getCachedRxDocument(t))),(0,pt.d)(le.kv))},getLatest(){var e=n(Cr,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,this._data){if("string"!=typeof e)throw I("LD2",{objPath:e});var t=v(this._data,e);return t=j.deepFreezeWhenDevMode(t)}},get$(e){if(e="data."+e,j.isDevMode()){if(e.includes(".item."))throw N("LD3",{objPath:e});if(e===this.primaryPath)throw N("LD4")}return this.$.pipe((0,ut.U)((e=>e._data)),(0,ut.U)((t=>v(t,e))),(0,mt.x)())},async incrementalModify(e){var t=await Or(this.parent);return t.incrementalWriteQueue.addWrite(this._data,(async t=>(t.data=await e(t.data,this),t))).then((e=>t.docCache.getCachedRxDocument(e)))},incrementalPatch(e){return this.incrementalModify((t=>(Object.entries(e).forEach((e=>{let[r,a]=e;t[r]=a})),t)))},async _saveData(e){var t=await Or(this.parent),r=this._data;return e.id=this.id,t.storageInstance.bulkWrite([{previous:r,document:e}],"local-document-save-data").then((t=>{var r=t.success[0];if(!r)throw t.error[0];(e=i(e))._rev=r._rev}))},async remove(){var e=await Or(this.parent),t={id:this._data.id,data:{},_deleted:!0,_meta:T(),_rev:"",_attachments:{}};return Le(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then((t=>e.docCache.getCachedRxDocument(t)))}},Nr=!1,Ir=()=>{if(!Nr){Nr=!0;var e=xt;Object.getOwnPropertyNames(e).forEach((t=>{if(!Object.getOwnPropertyDescriptor(Dr,t)){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(Dr,t,r)}}));["populate","update","putAttachment","getAttachment","allAttachments"].forEach((e=>Dr[e]=(e=>()=>{throw N("LD6",{functionName:e})})(e)))}};var Er=new WeakMap,Cr=new WeakMap;function Rr(e){var t=e.database?e.database:e,r=e.database?e.name:"",a=(async()=>{var a=await Sr(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);a=Ke(t,a,Tr);var n=new Mt("id",e.$.pipe((0,ht.h)((e=>e.isLocal))),(t=>function(e,t){Ir();var r=new _r(e.id,e,t);return Object.setPrototypeOf(r,Dr),r.prototype=Dr,r}(t,e))),s=new yt(a,"id",(()=>{}),(()=>{})),i=await t.storageToken,o=a.changeStream().subscribe((r=>{var a={id:r.id,internal:!1,collectionName:e.database?e.name:void 0,storageToken:i,events:r.events.map((t=>Qe(!0,t,e.database?e:void 0))),databaseToken:t.token,checkpoint:r.checkpoint,context:r.context,endTime:r.endTime,startTime:r.startTime};t.$emit(a)}));e._subs.push(o);var c={database:t,parent:e,storageInstance:a,docCache:n,incrementalWriteQueue:s};return Cr.set(e,c),c})();Er.set(e,a)}function Or(e){var t=Er.get(e);if(!t){var r=e.database?e.database:e,a=e.database?e.name:"";throw N("LD8",{database:r.name,collection:a})}return t}function Sr(e,t,r,a,n,s){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:$r(a),schema:Tr,options:n,multiInstance:s,devMode:j.isDevMode()})}function Pr(e){var t=Er.get(e);if(t)return Er.delete(e),t.then((e=>e.storageInstance.close()))}async function Br(e,t,r){var a=S(10),n=await Sr(a,e,t,r,{},!1);await n.remove()}function $r(e){return"plugin-local-documents-"+e}var Tr=Q({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function qr(e,t){var r=await Or(this),a={id:e,data:t,_deleted:!1,_meta:T(),_rev:"",_attachments:{}};return Le(r.storageInstance,{document:a},"local-document-insert").then((e=>r.docCache.getCachedRxDocument(e)))}function Mr(e,t){return this.getLocal(e).then((r=>r?r.incrementalModify((()=>t)):this.insertLocal(e,t)))}async function Ar(e){var t=await Or(this),r=t.docCache,a=r.getLatestDocumentDataIfExists(e);return a?Promise.resolve(r.getCachedRxDocument(a)):Ae(t.storageInstance,e).then((e=>e?t.docCache.getCachedRxDocument(e):null))}function Lr(e){return this.$.pipe((0,dt.O)(null),(0,Nt.z)((async t=>t?{changeEvent:t}:{doc:await this.getLocal(e)})),(0,Nt.z)((async t=>{if(t.changeEvent){var r=t.changeEvent;return r.isLocal&&r.documentId===e?{use:!0,doc:await this.getLocal(e)}:{use:!1}}return{use:!0,doc:t.doc}})),(0,ht.h)((e=>e.use)),(0,ut.U)((e=>e.doc)))}var Qr={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=qr,e.upsertLocal=Mr,e.getLocal=Ar,e.getLocal$=Lr},RxDatabase:e=>{e.insertLocal=qr,e.upsertLocal=Mr,e.getLocal=Ar,e.getLocal$=Lr}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Rr(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Rr(e.collection)}},preDestroyRxDatabase:{after:e=>Pr(e)},postDestroyRxCollection:{after:e=>Pr(e)},postRemoveRxDatabase:{after:e=>Br(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Br(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};let Wr;function Fr(){return"undefined"!=typeof window&&window.indexedDB}function Hr(){return Wr||(Wr=(async()=>{!function(e){if(it("preAddRxPlugin",{plugin:e,plugins:jr}),!jr.has(e)){if(kr.has(e.name))throw N("PL3",{name:e.name,plugin:e});if(jr.add(e),kr.add(e.name),!e.rxdb)throw I("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach((e=>{let[t,r]=e;return r(wr[t])})),e.overwritable&&Object.assign(j,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach((e=>{let[t,r]=e;r.after&&st[t].push(r.after),r.before&&st[t].unshift(r.before)}))}}(Qr);var e;return await xr({name:"rxdb-landing-v3",localDocuments:!0,storage:(void 0===e&&(e={}),new at(e))})})()),Wr}const zr=["#e6008d","#8d2089","#5f2688"]},341:(e,t,r)=>{function a(e,t){if(!window.trigger)throw new Error("window.trigger not defined");return window.trigger(e,t)}r.d(t,{X:()=>a})},1960:(e,t,r)=>{r.r(t),r.d(t,{default:()=>O});var a=r(2263),n=r(3799),s=r(5742),i=r(3028),o=r(5556),c=r(9655),l=r(3784),u=r(1556),h=r(7236),d=r(8804),m=r(598),p=Array.isArray;function f(e){return(0,m.U)((function(t){return function(e,t){return p(t)?e.apply(void 0,(0,o.ev)([],(0,o.CR)(t))):e(t)}(e,t)}))}var v=["addListener","removeListener"],g=["addEventListener","removeEventListener"],y=["on","off"];function b(e,t,r,a){if((0,d.m)(r)&&(a=r,r=void 0),a)return b(e,t,r).pipe(f(a));var n=(0,o.CR)(function(e){return(0,d.m)(e.addEventListener)&&(0,d.m)(e.removeEventListener)}(e)?g.map((function(a){return function(n){return e[a](t,n,r)}})):function(e){return(0,d.m)(e.addListener)&&(0,d.m)(e.removeListener)}(e)?v.map(x(e,t)):function(e){return(0,d.m)(e.on)&&(0,d.m)(e.off)}(e)?y.map(x(e,t)):[],2),s=n[0],i=n[1];if(!s&&(0,h.z)(e))return(0,u.z)((function(e){return b(e,t,r)}))((0,c.Xf)(e));if(!s)throw new TypeError("Invalid event target");return new l.y((function(e){var t=function(){for(var t=[],r=0;r{for(await(0,k.YB)(B);C;){const e=$(),r=(0,k.YB)(e.timeToNextPeriod);if(e.period%2==0)try{await t.incrementalModify((t=>(t.beatPeriod>=e.period||(t.beatPeriod=e.period,t.color=D.O9[e.period%3],e.period%4==0?t.text1=L(S,e.period)[0]:t.text2=L(P,e.period)[0]),t)))}catch(p){}await r}})();const r=await e.upsertLocal("mousepos",{x:0,y:0,time:0});let a=[];window.addEventListener("mousemove",(e=>{a=[e.clientX,e.clientY]})),(0,i.T)(b(window,"mousemove"),b(window,"scroll"),b(window,"resize")).subscribe((()=>{r.incrementalPatch({x:a[0],y:a[1],time:(0,_.z)()})})),function(e){const t=document.getElementsByClassName("tilt-to-mouse"),r=100;function a(e,t,a){const n=a.getBoundingClientRect(),s=-(t-n.y-n.height/2)/r,i=(e-n.x-n.width/2)/r;return`perspective(150px) rotateX(${M(s)}deg) rotateY(${M(i)}deg) `}function n(e,t){e.style.transform=a.apply(null,t)}e.$.subscribe((e=>{e._data.data.time&&Array.from(t).forEach((t=>{if(!W(t))return;n(t,(0,j.Is)([e._data.data.x,e._data.data.y]).concat([t]))}))}))}(r),function(e){const t=document.getElementsByClassName("enlarge-on-mouse");function r(e){const t=e.getBoundingClientRect();return{centerX:t.left+t.width/2,centerY:t.top+t.height/2,width:t.width,height:t.height}}function a(e,t){const r=`scale(${t})`;e.style.transform=r}e.$.pipe((0,m.U)((e=>e._data))).subscribe((e=>{e.data.time&&e.data.x&&e.data.y&&Array.from(t).forEach((t=>{if(!W(t))return;const n=r(t),s=e.data.x-n.centerX,i=e.data.y-n.centerY,o=Math.sqrt(s*s+i*i);function c(e){return 1.9^e}let l=1+n.width/2/c(o+300);l>1.5&&(l=1.5),l<1.01&&(l=1),a(t,l)}))}))}(r);const n=document.getElementsByClassName("beating"),s=document.getElementsByClassName("beating-first"),o=document.getElementsByClassName("beating-second"),c=document.getElementsByClassName("beating-number"),l=document.getElementsByClassName("beating-color"),u=document.getElementsByClassName("beating-color-string"),h=[];let d=0;$(),t.$.pipe((0,m.U)((e=>e._data.data)),(0,w.x)(((e,t)=>JSON.stringify(e)===JSON.stringify(t)))).subscribe((e=>{h.forEach((function(e){e(d)})),d+=1;const t=e.color;Array.from(l).forEach((function(e){e.style.backgroundColor=t})),Array.from(u).forEach((function(e){e.innerHTML=t}))})),h.push((function(){Array.from(n).forEach((function(e){e.style.animationDuration=B+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")})),Array.from(s).forEach((function(e){e.style.animationDuration=B+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")})),Array.from(o).forEach((function(e){e.style.animationDuration=B+"ms",e.classList.remove("animation"),e.offsetWidth,e.classList.add("animation")}))})),h.push((function(){Array.from(c).forEach((function(e){A()&&A()&&setTimeout((function(){const t=parseFloat(e.innerHTML)+1;e.innerHTML=t+""}),105)}))}))}function O(){const{siteConfig:e}=(0,a.Z)();return(0,N.useEffect)((()=>(R(),()=>{console.log("stop animation"),C=!1}))),(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(s.Z,{children:(0,E.jsx)("body",{className:"homepage"})}),(0,E.jsx)(n.Z,{title:`${e.title}`,description:"RxDB is a fast, local-first NoSQL-database for JavaScript Applications like Websites, hybrid Apps, Electron-Apps, Progressive Web Apps and Node.js",children:(0,E.jsxs)("main",{children:[(0,E.jsx)("div",{className:"block first centered",children:(0,E.jsx)("div",{className:"content",children:(0,E.jsxs)("div",{className:"inner",children:[(0,E.jsxs)("div",{className:"half",children:[(0,E.jsx)("br",{}),(0,E.jsxs)("h1",{children:["The local ",(0,E.jsx)("b",{className:"underline",children:"Database"})," for"," ",(0,E.jsx)("b",{className:"underline",children:"JavaScript"})," Applications"]}),(0,E.jsx)("br",{}),(0,E.jsxs)("ul",{className:"checked",children:[(0,E.jsx)("li",{children:"Realtime Queries"}),(0,E.jsx)("li",{children:"Realtime Replication"}),(0,E.jsx)("li",{children:"Works Offline"}),(0,E.jsx)("li",{children:"Supports all JavaScript runtimes"}),(0,E.jsx)("li",{children:"Great Performance"})]}),(0,E.jsx)("a",{className:"button",href:"/quickstart.html",target:"_blank",children:"Get Started"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsx)("div",{className:"half",style:{display:"flex",alignItems:"center",justifyContent:"center"},children:(0,E.jsxs)("div",{className:"content-canvas",style:{marginTop:30,marginBottom:30},children:[(0,E.jsx)("div",{className:"device tablet",style:{marginLeft:481,marginTop:117},children:(0,E.jsx)("div",{className:"beating-color",style:{backgroundColor:"rgb(141, 32, 137)"},children:(0,E.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo animation",alt:"RxDB",style:{animationDuration:"851ms"}})})}),(0,E.jsx)("div",{className:"device desktop",style:{marginTop:"0%"},children:(0,E.jsx)("div",{className:"beating-color",style:{backgroundColor:"rgb(141, 32, 137)"},children:(0,E.jsx)("img",{src:"/files/logo/logo_text.svg",className:"beating logo animation",alt:"RxDB",style:{animationDuration:"851ms",width:"52%"}})})}),(0,E.jsxs)("div",{className:"device server",style:{marginLeft:0,marginTop:168},children:[(0,E.jsx)("div",{className:"beating-color one",style:{backgroundColor:"rgb(141, 32, 137)"}}),(0,E.jsx)("div",{className:"beating-color two",style:{backgroundColor:"rgb(141, 32, 137)"}}),(0,E.jsx)("div",{className:"beating-color three",style:{backgroundColor:"rgb(141, 32, 137)"}})]})]})})]})})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb",onClick:()=>(0,I.X)("github_trophy_click",.2),target:"_blank",children:(0,E.jsxs)("div",{className:"trophy",children:[(0,E.jsx)("img",{src:"./files/icons/github-star-with-logo.svg",alt:"RxDB github star"}),(0,E.jsxs)("div",{style:{flex:1},children:[(0,E.jsx)("div",{className:"subtitle",children:"Open Source on"}),(0,E.jsx)("div",{className:"title",children:"GitHub"})]}),(0,E.jsxs)("div",{children:[(0,E.jsx)("div",{className:"valuetitle",children:"stars"}),(0,E.jsxs)("div",{className:"value",children:["19247",(0,E.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,E.jsx)("div",{className:"block second dark",children:(0,E.jsxs)("div",{className:"content",children:[(0,E.jsxs)("h2",{children:["Realtime applications ",(0,E.jsx)("b",{className:"underline",children:"made easy"})]}),(0,E.jsxs)("p",{children:["From the results of a query, to a single field of a document, with RxDB you can ",(0,E.jsx)("b",{children:"observe everything"}),". This enables you to build realtime applications ",(0,E.jsx)("b",{children:"fast"})," and ",(0,E.jsx)("b",{children:"reliable"}),". It does not matter if the data was changed by"," ",(0,E.jsx)("b",{children:"a user event"}),", ",(0,E.jsx)("b",{children:"another browser tab"})," or by the",(0,E.jsx)("b",{children:" replication"}),"."," ","Whenever your data changes, your UI reflects the new state."]}),(0,E.jsxs)("div",{className:"inner",children:[(0,E.jsxs)("div",{className:"code half",children:[(0,E.jsxs)("fieldset",{className:"samp-wrapper",style:{backgroundColor:"var(--bg-color)"},children:[(0,E.jsx)("legend",{children:"Write"}),(0,E.jsxs)("samp",{children:[(0,E.jsx)("span",{className:"cm-keyword",children:"await "}),(0,E.jsx)("span",{className:"cm-variable",children:"collection"}),".",(0,E.jsx)("span",{className:"cm-method",children:"upsert"}),"(","{",(0,E.jsx)("br",{}),(0,E.jsx)("span",{className:"cm-property",children:"\xa0 id"}),": ",(0,E.jsx)("span",{className:"cm-string",children:"'foobar'"}),",",(0,E.jsx)("br",{}),(0,E.jsx)("span",{className:"cm-property",children:"\xa0 color"}),": ",(0,E.jsxs)("span",{className:"cm-string",children:["'",(0,E.jsx)("span",{className:"beating-color-string beating-color",children:"#e6008d"}),"'"]}),(0,E.jsx)("br",{}),"}",");"]})]}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsxs)("fieldset",{className:"samp-wrapper",style:{backgroundColor:"var(--bg-color)"},children:[(0,E.jsx)("legend",{children:"Observe"}),(0,E.jsxs)("samp",{style:{backgroundColor:"var(--bg-color)"},children:[(0,E.jsx)("span",{className:"cm-keyword",children:"await "}),(0,E.jsx)("span",{className:"cm-variable",children:"collection"}),".",(0,E.jsxs)("span",{className:"cm-method",children:["findOne(",(0,E.jsx)("span",{className:"cm-string",children:"'foobar'"}),")"]}),(0,E.jsx)("br",{}),"\xa0.",(0,E.jsx)("span",{className:"cm-property",children:"$"}),(0,E.jsx)("span",{className:"cm-comment",children:" // get observable"}),(0,E.jsx)("br",{}),"\xa0.",(0,E.jsx)("span",{className:"cm-method",children:"subscribe"}),"(",(0,E.jsx)("span",{className:"cm-def",children:"d"}),(0,E.jsx)("span",{className:"cm-operator",children:" =>"})," ","{",(0,E.jsx)("br",{}),(0,E.jsx)("span",{className:"cm-variable",children:"\xa0\xa0 screen"}),".",(0,E.jsx)("span",{className:"cm-property",children:"backgroundColor"}),(0,E.jsx)("span",{className:"cm-operator",children:" = "}),(0,E.jsx)("span",{className:"cm-variable",children:"d"}),".",(0,E.jsx)("span",{className:"cm-property beating-color",children:"color"}),";",(0,E.jsx)("br",{}),"\xa0","}",");"]})]})]}),(0,E.jsx)("div",{className:"canvas half",children:(0,E.jsxs)("div",{className:"content-canvas",children:[(0,E.jsx)("div",{className:"device tablet",style:{marginLeft:481,marginTop:117},children:(0,E.jsx)("div",{className:"beating-color",children:(0,E.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo",alt:"RxDB"})})}),(0,E.jsx)("div",{className:"device desktop",style:{marginTop:"0%"},children:(0,E.jsx)("div",{className:"beating-color",children:(0,E.jsx)("img",{src:"./files/logo/logo.svg",className:"beating logo",alt:"RxDB"})})}),(0,E.jsxs)("div",{className:"device server",style:{marginLeft:0,marginTop:168},children:[(0,E.jsx)("div",{className:"beating-color one"}),(0,E.jsx)("div",{className:"beating-color two"}),(0,E.jsx)("div",{className:"beating-color three"})]})]})})]})]})}),(0,E.jsx)("a",{href:"https://twitter.com/intent/user?screen_name=rxdbjs",onClick:()=>(0,I.X)("twitter_trophy_click",.2),target:"_blank",children:(0,E.jsxs)("div",{className:"trophy twitter",children:[(0,E.jsx)("img",{src:"./files/icons/twitter-blue.svg",alt:"RxDB Twitter"}),(0,E.jsxs)("div",{style:{flex:1},children:[(0,E.jsx)("div",{className:"subtitle",children:"Follow on"}),(0,E.jsx)("div",{className:"title",children:"Twitter"})]}),(0,E.jsxs)("div",{children:[(0,E.jsx)("div",{className:"valuetitle",children:"followers"}),(0,E.jsxs)("div",{className:"value",children:["2843",(0,E.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,E.jsx)("div",{className:"block replication",children:(0,E.jsxs)("div",{className:"content",children:[(0,E.jsxs)("div",{className:"half left",children:[(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsxs)("h2",{children:["Replicate ",(0,E.jsx)("b",{children:"with your existing infrastructure"})]}),(0,E.jsxs)("p",{children:["RxDB supports replication with a"," ",(0,E.jsx)("a",{href:"/replication-couchdb.html",target:"_blank",children:"CouchDB"})," ","server or any custom"," ",(0,E.jsx)("a",{href:"/replication-graphql.html",target:"_blank",children:"GraphQL"})," ","endpoint which smoothly integrates with your existing infrastructure. Also you can use the replication primitives plugin to create custom replications over any protocol like"," ",(0,E.jsx)("a",{href:"/replication-http.html",target:"_blank",children:"HTTP"}),","," ",(0,E.jsx)("a",{href:"/replication-websocket.html",target:"_blank",children:"Websocket"}),","," ",(0,E.jsx)("a",{href:"/replication-webrtc.html",target:"_blank",children:"WebRTC"})," ","or"," ",(0,E.jsx)("a",{href:"/replication-firestore.html",target:"_blank",children:"Firestore"}),"."]})]}),(0,E.jsx)("div",{className:"half right",children:(0,E.jsxs)("div",{className:"replication-icons",children:[(0,E.jsx)("img",{src:"./files/logo/logo.svg",alt:"RxDB",className:"replicate-logo tilt-to-mouse"}),(0,E.jsx)("a",{href:"/replication-graphql.html",target:"_blank",children:(0,E.jsx)("div",{className:"neumorphism-circle-xl centered replicate-graphql enlarge-on-mouse",children:(0,E.jsx)("img",{src:"./files/icons/graphql-text.svg",alt:"GraphQL",className:"protocol"})})}),(0,E.jsx)("a",{href:"/replication-couchdb.html",target:"_blank",children:(0,E.jsx)("div",{className:"neumorphism-circle-xl centered replicate-couchdb enlarge-on-mouse",children:(0,E.jsx)("img",{src:"./files/icons/couchdb-text.svg",alt:"CouchDB",className:"protocol"})})}),(0,E.jsxs)("div",{className:"neumorphism-circle-xs centered replicate-rest enlarge-on-mouse",children:["{"," REST ","}"]}),(0,E.jsx)("a",{href:"/replication-websocket.html",target:"_blank",children:(0,E.jsx)("div",{className:"neumorphism-circle-xs centered replicate-websocket enlarge-on-mouse",children:"websocket"})}),(0,E.jsx)("a",{href:"/replication-webrtc.html",target:"_blank",children:(0,E.jsx)("div",{className:"neumorphism-circle-xs centered replicate-webrtc enlarge-on-mouse",children:"WebRTC"})})]})}),(0,E.jsx)("div",{className:"clear"})]})}),(0,E.jsx)("a",{href:"https://rxdb.info/chat.html",onClick:()=>(0,I.X)("discord_trophy_click",.2),target:"_blank",children:(0,E.jsxs)("div",{className:"trophy discord",children:[(0,E.jsx)("img",{src:"./files/icons/discord.svg",alt:"RxDB Discord chat"}),(0,E.jsxs)("div",{style:{flex:1},children:[(0,E.jsx)("div",{className:"subtitle",children:"Chat on"}),(0,E.jsx)("div",{className:"title",children:"Discord"})]}),(0,E.jsxs)("div",{children:[(0,E.jsx)("div",{className:"valuetitle",children:"members"}),(0,E.jsxs)("div",{className:"value",children:["414",(0,E.jsx)("div",{className:"arrow-up",children:" "})]})]})]})}),(0,E.jsxs)("div",{className:"block offline-first dark",children:[(0,E.jsx)("div",{className:"offline-image-wrapper",children:(0,E.jsx)("img",{src:"files/icons/wifi/wifi_1a202c.svg",className:"offline-image beating-second",alt:"offline"})}),(0,E.jsxs)("div",{className:"content",children:[(0,E.jsxs)("h2",{children:["Online ",(0,E.jsx)("b",{className:"underline",children:"is optional"})]}),(0,E.jsxs)("div",{className:"full-width",children:[(0,E.jsx)("div",{className:"half left",children:(0,E.jsxs)("p",{children:["RxDB follows the"," ",(0,E.jsx)("a",{href:"/offline-first.html",target:"_blank",children:"Offline First"})," ","paradigm where an application must work as well offline as it does online. This is done by persisting data locally on the client side and replicating it in the background. RxDB can even be used solely on the client side, with no backend at all."]})}),(0,E.jsx)("div",{className:"half right",children:(0,E.jsxs)("ul",{className:"checked",children:[(0,E.jsxs)("li",{children:["Your application still ",(0,E.jsx)("b",{children:"works offline"})]}),(0,E.jsxs)("li",{children:["Increases ",(0,E.jsx)("b",{children:"perceived performance"})]}),(0,E.jsxs)("li",{children:["Easier and ",(0,E.jsx)("b",{children:"faster implementation"})]}),(0,E.jsxs)("li",{children:["Needs less backend resources and ",(0,E.jsx)("b",{children:"scales better"})]})]})})]})]})]}),(0,E.jsx)("div",{className:"block frameworks",children:(0,E.jsxs)("div",{className:"content",children:[(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/angular",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"-10%",left:"10%"},children:[(0,E.jsx)("img",{src:"./files/icons/angular.svg",alt:"angular"}),"Angular"]})}),(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"10%",left:"58%"},children:[(0,E.jsx)("img",{src:"./files/icons/capacitor.svg",alt:"capacitor"}),"Capacitor"]}),(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"-4%",left:"44%"},children:[(0,E.jsx)("img",{src:"./files/icons/deno.svg",alt:"deno"}),"Deno"]}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/node",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"-5%",left:"85%"},children:[(0,E.jsx)("img",{src:"./files/icons/nodejs.svg",alt:"Node.js"}),"Node.js"]})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/react",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"4%",left:"26%"},children:[(0,E.jsx)("img",{src:"./files/icons/react.svg",alt:"React"}),"React"]})}),(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"15%",left:"90%",marginLeft:"-35px"},children:[(0,E.jsx)("img",{src:"./files/icons/svelte.svg",alt:"Svelte"}),"Svelte"]}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsx)("br",{}),(0,E.jsxs)("h2",{children:["Flexible ",(0,E.jsx)("b",{className:"underline",children:"storage layer"})]}),(0,E.jsxs)("p",{children:["RxDB is based on a storage interface that enables you to swap out the underlying storage engine. This increases code reuse because the same database code can be used in ",(0,E.jsx)("b",{children:"any JavaScript runtime"})," ","by just switching out the storage settings.",(0,E.jsx)("br",{})]}),(0,E.jsxs)("div",{className:"below-text",children:[(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/electron",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"2%",left:"18%"},children:[(0,E.jsx)("img",{src:"./files/icons/electron.svg",alt:"electron"}),"Electron"]})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/vue",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"3%",left:"45%"},children:[(0,E.jsx)("img",{src:"./files/icons/vuejs.svg",alt:"Vue.js"}),"Vue.js"]})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/ionic2",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"2%",left:"71%"},children:[(0,E.jsx)("img",{src:"./files/icons/ionic.svg",alt:"ionic"}),"Ionic"]})}),(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"46%",left:"11%"},children:[(0,E.jsx)("img",{src:"./files/icons/nativescript.svg",alt:"NativeScript"}),"NativeScript"]}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/react-native",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"45%",left:"35%"},children:[(0,E.jsx)("img",{src:"./files/icons/react.svg",alt:"React Native"}),"React Native"]})}),(0,E.jsxs)("div",{className:"neumorphism-circle-m circle centered enlarge-on-mouse",style:{top:"45%",left:"62%"},children:[(0,E.jsx)("img",{src:"./files/icons/nextjs.svg",alt:"Next.js"}),"Next.js"]}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb/tree/master/examples/flutter",target:"_blank",children:(0,E.jsxs)("div",{className:"neumorphism-circle-s circle centered enlarge-on-mouse",style:{top:"40%",left:"86%"},children:[(0,E.jsx)("img",{src:"./files/icons/flutter.svg",alt:"Flutter"}),"Flutter"]})})]})]})}),(0,E.jsx)("div",{className:"block fifth dark",children:(0,E.jsx)("div",{className:"content centered",children:(0,E.jsxs)("div",{className:"inner",children:[(0,E.jsxs)("h2",{children:["Trusted and ",(0,E.jsx)("b",{className:"underline",children:"open source"})]}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/github-star.svg",alt:"github star"}),(0,E.jsx)("div",{className:"label",children:"Github Stars"}),(0,E.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb",rel:"noopener",target:"_blank",children:"19247"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/download.svg",alt:"npm downloads"}),(0,E.jsx)("div",{className:"label",children:"npm downloads"}),(0,E.jsx)("a",{className:"value beating-number",href:"https://www.npmjs.com/package/rxdb",rel:"noopener",target:"_blank",children:"238572"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsx)("div",{className:"clear"}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/person.svg",alt:"contributor"}),(0,E.jsx)("div",{className:"label",children:"Contributors"}),(0,E.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/graphs/contributors",rel:"noopener",target:"_blank",children:"133"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/commit.svg",alt:"commit"}),(0,E.jsx)("div",{className:"label",children:"Commits"}),(0,E.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/commits/master",rel:"noopener",target:"_blank",children:"6891"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsx)("div",{className:"clear"}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/gear.svg",alt:"gear"}),(0,E.jsx)("div",{className:"label",children:"Projects build with RxDB"}),(0,E.jsx)("a",{className:"value",href:"https://github.com/pubkey/rxdb/network/dependents?package_id=UGFja2FnZS0xODM0NzAyMw%3D%3D",rel:"noopener",target:"_blank",children:"825"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsxs)("div",{className:"box dark",children:[(0,E.jsx)("img",{src:"files/icons/twitter.svg",alt:"twitter"}),(0,E.jsx)("div",{className:"label",children:"Twitter followers"}),(0,E.jsx)("a",{className:"value",href:"https://twitter.com/intent/user?screen_name=rxdbjs",rel:"noopener",target:"_blank",children:"2843"}),(0,E.jsx)("div",{className:"clear"})]}),(0,E.jsx)("div",{className:"clear"})]})})}),(0,E.jsx)("div",{className:"block sixth",children:(0,E.jsxs)("div",{className:"content",children:[(0,E.jsx)("h2",{children:"Pricing Models"}),(0,E.jsx)("div",{className:"inner",children:(0,E.jsxs)("div",{className:"buy-options",children:[(0,E.jsx)("div",{className:"buy-option bg-gradient-left-top",children:(0,E.jsxs)("div",{className:"buy-option-inner",children:[(0,E.jsxs)("div",{className:"buy-option-title",children:[(0,E.jsx)("h2",{children:"RxDB Basics"}),(0,E.jsx)("div",{className:"price",children:"Free & Open Source"})]}),(0,E.jsx)("div",{className:"buy-option-features",children:(0,E.jsxs)("ul",{children:[(0,E.jsx)("li",{children:"Basic RxStorages"}),(0,E.jsx)("li",{children:"Realtime Replication"}),(0,E.jsx)("li",{children:"Live Queries"}),(0,E.jsx)("li",{children:"Schema Validation"}),(0,E.jsx)("li",{children:"Multi-Tab Support"}),(0,E.jsx)("li",{children:"Encryption"}),(0,E.jsx)("li",{children:"Compression"})]})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb",target:"_blank",rel:"noopener",onClick:()=>(0,I.X)("goto_code",.2),children:(0,E.jsx)("div",{className:"buy-option-action bg-top hover-shadow-top",children:"Get the Code"})})]})}),(0,E.jsx)("div",{className:"buy-option bg-gradient-right-top",children:(0,E.jsxs)("div",{className:"buy-option-inner",children:[(0,E.jsxs)("div",{className:"buy-option-title",children:[(0,E.jsx)("h2",{children:"Premium Plugins"}),(0,E.jsx)("div",{className:"price",children:"for professionals to get the most out of RxDB"})]}),(0,E.jsx)("div",{className:"buy-option-features",children:(0,E.jsxs)("ul",{children:[(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-sqlite.html",target:"_blank",children:"SQLite RxStorage"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-opfs.html",target:"_blank",children:"OPFS RxStorage"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-indexeddb.html",target:"_blank",children:"IndexedDB RxStorage"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-memory-synced.html",target:"_blank",children:"Memory-Synced RxStorage"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-sharding.html",target:"_blank",children:"Sharding Plugin"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/query-optimizer.html",target:"_blank",children:"Query Optimizer"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/migration-storage.html",target:"_blank",children:"Storage Migrator"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-localstorage-meta-optimizer.html",target:"_blank",children:"RxStorage Localstorage Meta Optimizer"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-shared-worker.html",target:"_blank",children:"Shared Worker"})}),(0,E.jsx)("li",{children:(0,E.jsx)("a",{href:"https://rxdb.info/rx-storage-worker.html",target:"_blank",children:"Worker"})})]})}),(0,E.jsx)("a",{href:"/premium",onClick:()=>(0,I.X)("premium_request",1),children:(0,E.jsx)("div",{className:"buy-option-action bg-middle hover-shadow-middle",children:"Request Premium"})})]})}),(0,E.jsx)("div",{className:"buy-option bg-gradient-left-top",children:(0,E.jsxs)("div",{className:"buy-option-inner",children:[(0,E.jsxs)("div",{className:"buy-option-title",children:[(0,E.jsx)("h2",{children:"Consulting Session"}),(0,E.jsx)("div",{className:"price",children:"fast in person consulting"})]}),(0,E.jsx)("div",{className:"buy-option-features",children:(0,E.jsxs)("p",{children:["Book a one hour consulting session with the RxDB maintainer. I will answer all your questions, give proposals for your use case and we can even do a pair programming session if you have a specific problem in your source code.",(0,E.jsx)("br",{}),"You can book this by doing a one-time donation via github sponsors."]})}),(0,E.jsx)("a",{href:"https://github.com/sponsors/pubkey?frequency=one-time&sponsor=pubkey",target:"_blank",onClick:()=>(0,I.X)("consulting_session_request",1.5),children:(0,E.jsx)("div",{className:"buy-option-action bg-bottom hover-shadow-bottom",children:"Book Now"})})]})})]})})]})}),(0,E.jsx)("div",{className:"block last dark",children:(0,E.jsxs)("div",{className:"content",children:[(0,E.jsxs)("h2",{children:["Start using ",(0,E.jsx)("b",{className:"underline",children:"RxDB"})," today"]}),(0,E.jsxs)("div",{className:"buttons full-width",children:[(0,E.jsx)("a",{href:"/quickstart.html",rel:"noopener",target:"_blank",onClick:()=>(0,I.X)("start_now",.4),children:(0,E.jsx)("div",{className:"button get-premium",style:{left:"50%",top:"20%",marginLeft:"-122px"},children:"Start now"})}),(0,E.jsx)("a",{href:"https://rxdb.info/newsletter.html",rel:"noopener",target:"_blank",onClick:()=>(0,I.X)("get_newsletter",.4),children:(0,E.jsx)("div",{className:"button",style:{left:"25%",marginLeft:"-90px"},children:"Get the Newsletter"})}),(0,E.jsx)("a",{href:"https://rxdb.info/chat.html",rel:"noopener",target:"_blank",onClick:()=>(0,I.X)("join_chat",.4),children:(0,E.jsx)("div",{className:"button",style:{left:"77%",top:"6%",marginLeft:"-70.5px"},children:"Join the Chat"})}),(0,E.jsx)("a",{href:"/premium",onClick:()=>(0,I.X)("premium_request",1),children:(0,E.jsx)("div",{className:"button",style:{top:"40%",left:"20%",marginLeft:"-70.5px"},children:"Get Premium"})}),(0,E.jsx)("a",{href:"https://twitter.com/intent/user?screen_name=rxdbjs",rel:"noopener",target:"_blank",onClick:()=>(0,I.X)("follow_twitter",.4),children:(0,E.jsx)("div",{className:"button",style:{top:"44%",left:"73%",marginLeft:"-85px"},children:"Follow on Twitter"})}),(0,E.jsx)("a",{href:"https://github.com/pubkey/rxdb",rel:"noopener",target:"_blank",onClick:()=>(0,I.X)("goto_code",.4),children:(0,E.jsx)("div",{className:"button",style:{top:"54%",left:"32%",marginLeft:"-70px"},children:"Get the Code"})})]})]})})]})})]})}const S=["NoSQL","OfflineFirst","JavaScript","observable","reactive","realtime","client side","fast"],P=["for the Web","for Node.js","for Browsers","for Capacitor","for Electron","for hybrid apps","for PWAs","for React Native","for NativeScript","for UI apps","you deserve","that syncs"],B=851;function $(){const e=((new Date).getTime()-196e7)/B,t=Math.floor(e);return{ratio:e,period:t,timeToNextPeriod:(e-t)*B}}const T=22,q=-1*T;function M(e){return eT?T:e}function A(){return Math.random()<.5}function L(e,t){let r,a,n=(e=e.slice(0)).length;for(;n;)a=Math.floor(Q(t)*n--),r=e[n],e[n]=e[a],e[a]=r,++t;return e}function Q(e){const t=1e4*Math.sin(e++);return t-Math.floor(t)}function W(e){const t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}},6087:(e,t,r)=>{function a(e){return e[e.length-1]}function n(e){return Array.isArray(e)?e.slice(0):[e]}function s(e){return Array.isArray(e)}function i(e){return null!=e}function o(e,t){var r=0,a=-1;for(var n of e){if(!t(n,a+=1))break;r+=1}return r}function c(e,t){for(var r=t.length,a=0;as,Nb:()=>l,S7:()=>i,SI:()=>a,gu:()=>c,qo:()=>n,r0:()=>o})},7400:(e,t,r)=>{function a(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}r.d(t,{Is:()=>a,kv:()=>n});var n={bufferSize:1,refCount:!0}},4419:(e,t,r)=>{function a(){return new Promise((e=>setTimeout(e,0)))}function n(e){return void 0===e&&(e=0),new Promise((t=>setTimeout(t,e)))}r.d(t,{$Y:()=>o,C2:()=>u,Y3:()=>a,YB:()=>n,Ze:()=>h,kZ:()=>s,m5:()=>i,y$:()=>c});Promise.resolve(!0);var s=Promise.resolve(!1),i=Promise.resolve(null),o=Promise.resolve();function c(e){return void 0===e&&(e=1e4),"function"==typeof requestIdleCallback?new Promise((t=>{requestIdleCallback((()=>t()),{timeout:e})})):n(0)}var l=o;function u(e){return void 0===e&&(e=void 0),l=l.then((()=>c(e)))}function h(e,t){return e.reduce(((e,t)=>e.then(t)),Promise.resolve(t))}},984:(e,t,r)=>{r.d(t,{z:()=>n});var a=0;function n(){var e=Date.now();(e+=.01)<=a&&(e=a+.01);var t=parseFloat(e.toFixed(2));return a=t,t}}}]); \ No newline at end of file diff --git a/docs/assets/js/2dc45ced.5d57f1e6.js b/docs/assets/js/2dc45ced.5d57f1e6.js new file mode 100644 index 00000000000..b6d83c4fc7a --- /dev/null +++ b/docs/assets/js/2dc45ced.5d57f1e6.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[1218],{8821:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>o,default:()=>h,frontMatter:()=>s,metadata:()=>a,toc:()=>d});var i=t(5893),r=t(1151);const s={},o="RxDB Server",a={id:"server",title:"RxDB Server",description:"The RxDB Server Plugin makes it possible to spawn a server on top of a RxDB database that offers multiple types of endpoints for various usages. It can spawn basic CRUD REST endpoints or event realtime replication endpoints that can be used by the client devices to replicate data.",source:"@site/docs/server.md",sourceDirName:".",slug:"/server",permalink:"/server",draft:!1,unlisted:!1,editUrl:"https://github.com/pubkey/rxdb/tree/master/docs-src/docs/server.md",tags:[],version:"current",frontMatter:{}},l={},d=[{value:"Missing features",id:"missing-features",level:2}];function c(e){const n={a:"a",code:"code",h1:"h1",h2:"h2",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,r.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(n.h1,{id:"rxdb-server",children:"RxDB Server"}),"\n",(0,i.jsx)(n.p,{children:"The RxDB Server Plugin makes it possible to spawn a server on top of a RxDB database that offers multiple types of endpoints for various usages. It can spawn basic CRUD REST endpoints or event realtime replication endpoints that can be used by the client devices to replicate data."}),"\n",(0,i.jsx)(n.h1,{id:"replication-endpoint",children:"Replication Endpoint"}),"\n",(0,i.jsxs)(n.p,{children:["The replication endpoint allows clients that connect to it to replicate data with the server via the RxDB ",(0,i.jsx)(n.a,{href:"/replication.html",children:"replication protocol"}),". There is also the ",(0,i.jsx)(n.a,{href:"/replication-server",children:"Replication Server"})," plugin that is used on the client side to connect to the endpoint."]}),"\n",(0,i.jsx)(n.h1,{id:"rest-endpoint",children:"REST endpoint"}),"\n",(0,i.jsx)(n.h1,{id:""}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"Authentication (who are you) with the authHandler"}),"\n",(0,i.jsx)(n.li,{children:"authorization with queryModifier and changeValidator"}),"\n",(0,i.jsx)(n.li,{children:"cors"}),"\n",(0,i.jsx)(n.li,{children:"conflict detection with the conflictHandler"}),"\n"]}),"\n",(0,i.jsx)(n.h1,{id:"server-only-indexes",children:"Server-only indexes"}),"\n",(0,i.jsxs)(n.p,{children:["Normal RxDB schema indexes get the ",(0,i.jsx)(n.code,{children:"_deleted"})," field prepended because all ",(0,i.jsx)(n.a,{href:"/rx-query.html",children:"RxQueries"})," automatically only search for documents with ",(0,i.jsx)(n.code,{children:"_deleted=false"}),".\nWhen you use RxDB on a server, this might not be optimal because there can be the need to query for documents where the value of ",(0,i.jsx)(n.code,{children:"_deleted"})," does not mather. Mostly this is required in the ",(0,i.jsx)(n.a,{href:"/replication.html#checkpoint-iteration",children:"pull.stream$"})," of a replication."]}),"\n",(0,i.jsxs)(n.p,{children:["To set indexes without ",(0,i.jsx)(n.code,{children:"_deleted"}),", you can use the ",(0,i.jsx)(n.code,{children:"internalIndexes"})," field of the schema like the following:"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-json",children:' {\n "version": 0,\n "primaryKey": "id",\n "type": "object",\n "properties": {\n "id": {\n "type": "string",\n "maxLength": 100 // <- the primary key must have set maxLength\n },\n "name": {\n "type": "string",\n "maxLength": 100\n }\n },\n "internalIndexes": [\n ["name", "id"]\n ]\n}\n'})}),"\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.strong,{children:"NOTICE:"})," Indexes come with a performance burden. You should only use the indexes you need and make sure you do not accidentally set the ",(0,i.jsx)(n.code,{children:"internalIndexes"})," in your client side ",(0,i.jsx)(n.a,{href:"/rx-collection.html",children:"RxCollections"}),"."]}),"\n",(0,i.jsx)(n.h1,{id:"server-only-fields",children:"Server-only fields"}),"\n",(0,i.jsx)(n.h2,{id:"missing-features",children:"Missing features"}),"\n",(0,i.jsx)(n.p,{children:"The server plugin is in beta mode and some features are still missing. Make a Pull Request when you need them:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{}),"\n"]})]})}function h(e={}){const{wrapper:n}={...(0,r.a)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(c,{...e})}):c(e)}},1151:(e,n,t)=>{t.d(n,{Z:()=>a,a:()=>o});var i=t(7294);const r={},s=i.createContext(r);function o(e){const n=i.useContext(s);return i.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function a(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:o(e.components),i.createElement(s.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/docs/assets/js/55a5b596.77a03f20.js b/docs/assets/js/55a5b596.352c6675.js similarity index 72% rename from docs/assets/js/55a5b596.77a03f20.js rename to docs/assets/js/55a5b596.352c6675.js index 4ca8827a046..7f413ad61aa 100644 --- a/docs/assets/js/55a5b596.77a03f20.js +++ b/docs/assets/js/55a5b596.352c6675.js @@ -1 +1 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[4669],{8021:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>r,default:()=>c,frontMatter:()=>a,metadata:()=>l,toc:()=>h});var i=t(5893),s=t(1151);const a={title:"RxSchema",slug:"rx-schema.html"},r="RxSchema",l={id:"rx-schema",title:"RxSchema",description:"Schemas define the structure of the documents of a collection. Which field should be used as primary, which fields should be used as indexes and what should be encrypted. Every collection has its own schema. With RxDB, schemas are defined with the jsonschema-standard which you might know from other projects.",source:"@site/docs/rx-schema.md",sourceDirName:".",slug:"/rx-schema.html",permalink:"/rx-schema.html",draft:!1,unlisted:!1,editUrl:"https://github.com/pubkey/rxdb/tree/master/docs-src/docs/rx-schema.md",tags:[],version:"current",frontMatter:{title:"RxSchema",slug:"rx-schema.html"},sidebar:"tutorialSidebar",previous:{title:"RxDatabase",permalink:"/rx-database.html"},next:{title:"RxCollection",permalink:"/rx-collection.html"}},o={},h=[{value:"Example",id:"example",level:2},{value:"Create a collection with the schema",id:"create-a-collection-with-the-schema",level:2},{value:"version",id:"version",level:2},{value:"primaryKey",id:"primarykey",level:2},{value:"composite primary key",id:"composite-primary-key",level:3},{value:"Indexes",id:"indexes",level:2},{value:"Index-example",id:"index-example",level:3},{value:"attachments",id:"attachments",level:2},{value:"default",id:"default",level:2},{value:"final",id:"final",level:2},{value:"NOTICE: Not everything within the jsonschema-spec is allowed",id:"notice-not-everything-within-the-jsonschema-spec-is-allowed",level:2}];function d(e){const n={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,s.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(n.h1,{id:"rxschema",children:"RxSchema"}),"\n",(0,i.jsxs)(n.p,{children:["Schemas define the structure of the documents of a collection. Which field should be used as primary, which fields should be used as indexes and what should be encrypted. Every collection has its own schema. With RxDB, schemas are defined with the ",(0,i.jsx)(n.a,{href:"http://json-schema.org/",children:"jsonschema"}),"-standard which you might know from other projects."]}),"\n",(0,i.jsx)(n.h2,{id:"example",children:"Example"}),"\n",(0,i.jsx)(n.p,{children:"In this example-schema we define a hero-collection with the following settings:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"the version-number of the schema is 0"}),"\n",(0,i.jsxs)(n.li,{children:["the name-property is the ",(0,i.jsx)(n.strong,{children:"primaryKey"}),". This means its an unique, indexed, required ",(0,i.jsx)(n.code,{children:"string"})," which can be used to definitely find a single document."]}),"\n",(0,i.jsx)(n.li,{children:"the color-field is required for every document"}),"\n",(0,i.jsx)(n.li,{children:"the healthpoints-field must be a number between 0 and 100"}),"\n",(0,i.jsx)(n.li,{children:"the secret-field stores an encrypted value"}),"\n",(0,i.jsx)(n.li,{children:"the birthyear-field is final which means it is required and cannot be changed"}),"\n",(0,i.jsx)(n.li,{children:"the skills-attribute must be an array with objects which contain the name and the damage-attribute. There is a maximum of 5 skills per hero."}),"\n",(0,i.jsx)(n.li,{children:"Allows adding attachments and store them encrypted"}),"\n"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-json",children:' {\n "title": "hero schema",\n "version": 0,\n "description": "describes a simple hero",\n "primaryKey": "name",\n "type": "object",\n "properties": {\n "name": {\n "type": "string",\n "maxLength": 100 // <- the primary key must have set maxLength\n },\n "color": {\n "type": "string"\n },\n "healthpoints": {\n "type": "number",\n "minimum": 0,\n "maximum": 100\n },\n "secret": {\n "type": "string"\n },\n "birthyear": {\n "type": "number",\n "final": true,\n "minimum": 1900,\n "maximum": 2050\n },\n "skills": {\n "type": "array",\n "maxItems": 5,\n "uniqueItems": true,\n "items": {\n "type": "object",\n "properties": {\n "name": {\n "type": "string"\n },\n "damage": {\n "type": "number"\n }\n }\n }\n }\n },\n "required": [\n "name",\n "color"\n ],\n "encrypted": ["secret"],\n "attachments": {\n "encrypted": true\n }\n }\n'})}),"\n",(0,i.jsx)(n.h2,{id:"create-a-collection-with-the-schema",children:"Create a collection with the schema"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-javascript",children:"await myDatabase.addCollections({\n heroes: {\n schema: myHeroSchema\n }\n});\nconsole.dir(myDatabase.heroes.name);\n// heroes\n"})}),"\n",(0,i.jsx)(n.h2,{id:"version",children:"version"}),"\n",(0,i.jsxs)(n.p,{children:["The ",(0,i.jsx)(n.code,{children:"version"})," field is a number, starting with ",(0,i.jsx)(n.code,{children:"0"}),".\nWhen the version is greater than 0, you have to provide the migrationStrategies to create a collection with this schema."]}),"\n",(0,i.jsx)(n.h2,{id:"primarykey",children:"primaryKey"}),"\n",(0,i.jsxs)(n.p,{children:["The ",(0,i.jsx)(n.code,{children:"primaryKey"})," field contains the fieldname of the property that will be used as primary key for the whole collection.\nThe value of the primary key of the document must be a ",(0,i.jsx)(n.code,{children:"string"}),", unique, final and is required."]}),"\n",(0,i.jsx)(n.h3,{id:"composite-primary-key",children:"composite primary key"}),"\n",(0,i.jsx)(n.p,{children:"You can define a composite primary key which gets composed from multiple properties of the document data."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-javascript",children:"const mySchema = {\n keyCompression: true, // set this to true, to enable the keyCompression\n version: 0,\n title: 'human schema with composite primary',\n primaryKey: {\n // where should the composed string be stored\n key: 'id',\n // fields that will be used to create the composed key\n fields: [\n 'firstName',\n 'lastName'\n ],\n // separator which is used to concat the fields values.\n separator: '|'\n },\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 100 // <- the primary key must have set maxLength\n },\n firstName: {\n type: 'string'\n },\n lastName: {\n type: 'string'\n }\n },\n required: [\n 'id', \n 'firstName',\n 'lastName'\n ]\n};\n"})}),"\n",(0,i.jsx)(n.p,{children:"You can then find a document by using the relevant parts to create the composite primaryKey:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ts",children:"\n// inserting with composite primary\nawait myRxCollection.insert({\n // id, <- do not set the id, it will be filled by RxDB\n firstName: 'foo',\n lastName: 'bar'\n});\n\n// find by composite primary\nconst id = myRxCollection.schema.getPrimaryOfDocumentData({\n firstName: 'foo',\n lastName: 'bar'\n});\nconst myRxDocument = myRxCollection.findOne(id).exec();\n\n"})}),"\n",(0,i.jsx)(n.h2,{id:"indexes",children:"Indexes"}),"\n",(0,i.jsx)(n.p,{children:"RxDB supports secondary indexes which are defined at the schema-level of the collection."}),"\n",(0,i.jsxs)(n.p,{children:["Index is only allowed on field types ",(0,i.jsx)(n.code,{children:"string"}),", ",(0,i.jsx)(n.code,{children:"integer"})," and ",(0,i.jsx)(n.code,{children:"number"}),". Some RxStorages allow to use ",(0,i.jsx)(n.code,{children:"boolean"})," fields as index."]}),"\n",(0,i.jsxs)(n.p,{children:["Depending on the field type, you must have set some meta attributes like ",(0,i.jsx)(n.code,{children:"maxLength"})," or ",(0,i.jsx)(n.code,{children:"minimum"}),". This is required so that RxDB\nis able to know the maximum string representation length of a field, which is needed to craft custom indexes on several ",(0,i.jsx)(n.code,{children:"RxStorage"})," implementations."]}),"\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.strong,{children:"NOTICE:"})," RxDB will always append the ",(0,i.jsx)(n.code,{children:"primaryKey"})," to all indexes to ensure a deterministic sort order of query results. You do not have to add the ",(0,i.jsx)(n.code,{children:"primaryKey"})," to any index."]}),"\n",(0,i.jsx)(n.h3,{id:"index-example",children:"Index-example"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-javascript",children:"const schemaWithIndexes = {\n version: 0,\n title: 'human schema with indexes',\n keyCompression: true,\n primaryKey: 'id',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 100 // <- the primary key must have set maxLength\n },\n firstName: {\n type: 'string',\n maxLength: 100 // <- string-fields that are used as an index, must have set maxLength.\n },\n lastName: {\n type: 'string'\n },\n active: {\n type: 'boolean'\n },\n familyName: {\n type: 'string'\n },\n balance: {\n type: 'number',\n\n // number fields that are used in an index, must have set minimum, maximum and multipleOf\n minimum: 0,\n maximum: 100000,\n multipleOf: 0.01\n },\n creditCards: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n cvc: {\n type: 'number'\n }\n }\n } \n }\n },\n required: [\n 'id',\n 'active' // <- boolean fields that are used in an index, must be required. \n ],\n indexes: [\n 'firstName', // <- this will create a simple index for the `firstName` field\n ['active', 'firstName'], // <- this will create a compound-index for these two fields\n 'active'\n ]\n};\n"})}),"\n",(0,i.jsx)(n.h2,{id:"attachments",children:"attachments"}),"\n",(0,i.jsxs)(n.p,{children:["To use attachments in the collection, you have to add the ",(0,i.jsx)(n.code,{children:"attachments"}),"-attribute to the schema. ",(0,i.jsx)(n.a,{href:"/rx-attachment.html",children:"See RxAttachment"}),"."]}),"\n",(0,i.jsx)(n.h2,{id:"default",children:"default"}),"\n",(0,i.jsx)(n.p,{children:"Default values can only be defined for first-level fields.\nWhenever you insert a document unset fields will be filled with default-values."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-javascript",children:"const schemaWithDefaultAge = {\n version: 0,\n primaryKey: 'id',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 100 // <- the primary key must have set maxLength\n },\n firstName: {\n type: 'string'\n },\n lastName: {\n type: 'string'\n },\n age: {\n type: 'integer',\n default: 20 // <- default will be used\n }\n },\n required: ['id']\n};\n"})}),"\n",(0,i.jsx)(n.h2,{id:"final",children:"final"}),"\n",(0,i.jsxs)(n.p,{children:["By setting a field to ",(0,i.jsx)(n.code,{children:"final"}),", you make sure it cannot be modified later. Final fields are always required.\nFinal fields cannot be observed because they will not change."]}),"\n",(0,i.jsx)(n.p,{children:"Advantages:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"With final fields you can ensure that no-one accidentally modifies the data."}),"\n",(0,i.jsxs)(n.li,{children:["When you enable the ",(0,i.jsx)(n.code,{children:"eventReduce"})," algorithm, some performance-improvements are done."]}),"\n"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-javascript",children:"const schemaWithFinalAge = {\n version: 0,\n primaryKey: 'id',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 100 // <- the primary key must have set maxLength\n },\n firstName: {\n type: 'string'\n },\n lastName: {\n type: 'string'\n },\n age: {\n type: 'integer',\n final: true\n }\n },\n required: ['id']\n};\n"})}),"\n",(0,i.jsx)(n.h2,{id:"notice-not-everything-within-the-jsonschema-spec-is-allowed",children:"NOTICE: Not everything within the jsonschema-spec is allowed"}),"\n",(0,i.jsxs)(n.p,{children:["The schema is not only used to validate objects before they are written into the database, but also used to map getters to observe and populate single fieldnames, keycompression and other things. Therefore you can not use every schema which would be valid for the spec of ",(0,i.jsx)(n.a,{href:"http://json-schema.org/",children:"json-schema.org"}),".\nFor example, fieldnames must match the regex ",(0,i.jsx)(n.code,{children:"^[a-zA-Z][[a-zA-Z0-9_]*]?[a-zA-Z0-9]$"})," and ",(0,i.jsx)(n.code,{children:"additionalProperties"})," is always set to ",(0,i.jsx)(n.code,{children:"false"}),". But don't worry, RxDB will instantly throw an error when you pass an invalid schema into it."]})]})}function c(e={}){const{wrapper:n}={...(0,s.a)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(d,{...e})}):d(e)}},1151:(e,n,t)=>{t.d(n,{Z:()=>l,a:()=>r});var i=t(7294);const s={},a=i.createContext(s);function r(e){const n=i.useContext(a);return i.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function l(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:r(e.components),i.createElement(a.Provider,{value:n},e.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[4669],{8021:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>o,contentTitle:()=>r,default:()=>c,frontMatter:()=>a,metadata:()=>l,toc:()=>h});var i=t(5893),s=t(1151);const a={title:"RxSchema",slug:"rx-schema.html"},r="RxSchema",l={id:"rx-schema",title:"RxSchema",description:"Schemas define the structure of the documents of a collection. Which field should be used as primary, which fields should be used as indexes and what should be encrypted. Every collection has its own schema. With RxDB, schemas are defined with the jsonschema-standard which you might know from other projects.",source:"@site/docs/rx-schema.md",sourceDirName:".",slug:"/rx-schema.html",permalink:"/rx-schema.html",draft:!1,unlisted:!1,editUrl:"https://github.com/pubkey/rxdb/tree/master/docs-src/docs/rx-schema.md",tags:[],version:"current",frontMatter:{title:"RxSchema",slug:"rx-schema.html"},sidebar:"tutorialSidebar",previous:{title:"RxDatabase",permalink:"/rx-database.html"},next:{title:"RxCollection",permalink:"/rx-collection.html"}},o={},h=[{value:"Example",id:"example",level:2},{value:"Create a collection with the schema",id:"create-a-collection-with-the-schema",level:2},{value:"version",id:"version",level:2},{value:"primaryKey",id:"primarykey",level:2},{value:"composite primary key",id:"composite-primary-key",level:3},{value:"Indexes",id:"indexes",level:2},{value:"Index-example",id:"index-example",level:3},{value:"attachments",id:"attachments",level:2},{value:"default",id:"default",level:2},{value:"final",id:"final",level:2},{value:"NOTICE: Not everything within the jsonschema-spec is allowed",id:"notice-not-everything-within-the-jsonschema-spec-is-allowed",level:2}];function d(e){const n={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,s.a)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(n.h1,{id:"rxschema",children:"RxSchema"}),"\n",(0,i.jsxs)(n.p,{children:["Schemas define the structure of the documents of a collection. Which field should be used as primary, which fields should be used as indexes and what should be encrypted. Every collection has its own schema. With RxDB, schemas are defined with the ",(0,i.jsx)(n.a,{href:"http://json-schema.org/",children:"jsonschema"}),"-standard which you might know from other projects."]}),"\n",(0,i.jsx)(n.h2,{id:"example",children:"Example"}),"\n",(0,i.jsx)(n.p,{children:"In this example-schema we define a hero-collection with the following settings:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"the version-number of the schema is 0"}),"\n",(0,i.jsxs)(n.li,{children:["the name-property is the ",(0,i.jsx)(n.strong,{children:"primaryKey"}),". This means its an unique, indexed, required ",(0,i.jsx)(n.code,{children:"string"})," which can be used to definitely find a single document."]}),"\n",(0,i.jsx)(n.li,{children:"the color-field is required for every document"}),"\n",(0,i.jsx)(n.li,{children:"the healthpoints-field must be a number between 0 and 100"}),"\n",(0,i.jsx)(n.li,{children:"the secret-field stores an encrypted value"}),"\n",(0,i.jsx)(n.li,{children:"the birthyear-field is final which means it is required and cannot be changed"}),"\n",(0,i.jsx)(n.li,{children:"the skills-attribute must be an array with objects which contain the name and the damage-attribute. There is a maximum of 5 skills per hero."}),"\n",(0,i.jsx)(n.li,{children:"Allows adding attachments and store them encrypted"}),"\n"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-json",children:' {\n "title": "hero schema",\n "version": 0,\n "description": "describes a simple hero",\n "primaryKey": "name",\n "type": "object",\n "properties": {\n "name": {\n "type": "string",\n "maxLength": 100 // <- the primary key must have set maxLength\n },\n "color": {\n "type": "string"\n },\n "healthpoints": {\n "type": "number",\n "minimum": 0,\n "maximum": 100\n },\n "secret": {\n "type": "string"\n },\n "birthyear": {\n "type": "number",\n "final": true,\n "minimum": 1900,\n "maximum": 2050\n },\n "skills": {\n "type": "array",\n "maxItems": 5,\n "uniqueItems": true,\n "items": {\n "type": "object",\n "properties": {\n "name": {\n "type": "string"\n },\n "damage": {\n "type": "number"\n }\n }\n }\n }\n },\n "required": [\n "name",\n "color"\n ],\n "encrypted": ["secret"],\n "attachments": {\n "encrypted": true\n }\n }\n'})}),"\n",(0,i.jsx)(n.h2,{id:"create-a-collection-with-the-schema",children:"Create a collection with the schema"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-javascript",children:"await myDatabase.addCollections({\n heroes: {\n schema: myHeroSchema\n }\n});\nconsole.dir(myDatabase.heroes.name);\n// heroes\n"})}),"\n",(0,i.jsx)(n.h2,{id:"version",children:"version"}),"\n",(0,i.jsxs)(n.p,{children:["The ",(0,i.jsx)(n.code,{children:"version"})," field is a number, starting with ",(0,i.jsx)(n.code,{children:"0"}),".\nWhen the version is greater than 0, you have to provide the migrationStrategies to create a collection with this schema."]}),"\n",(0,i.jsx)(n.h2,{id:"primarykey",children:"primaryKey"}),"\n",(0,i.jsxs)(n.p,{children:["The ",(0,i.jsx)(n.code,{children:"primaryKey"})," field contains the fieldname of the property that will be used as primary key for the whole collection.\nThe value of the primary key of the document must be a ",(0,i.jsx)(n.code,{children:"string"}),", unique, final and is required."]}),"\n",(0,i.jsx)(n.h3,{id:"composite-primary-key",children:"composite primary key"}),"\n",(0,i.jsx)(n.p,{children:"You can define a composite primary key which gets composed from multiple properties of the document data."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-javascript",children:"const mySchema = {\n keyCompression: true, // set this to true, to enable the keyCompression\n version: 0,\n title: 'human schema with composite primary',\n primaryKey: {\n // where should the composed string be stored\n key: 'id',\n // fields that will be used to create the composed key\n fields: [\n 'firstName',\n 'lastName'\n ],\n // separator which is used to concat the fields values.\n separator: '|'\n },\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 100 // <- the primary key must have set maxLength\n },\n firstName: {\n type: 'string'\n },\n lastName: {\n type: 'string'\n }\n },\n required: [\n 'id', \n 'firstName',\n 'lastName'\n ]\n};\n"})}),"\n",(0,i.jsx)(n.p,{children:"You can then find a document by using the relevant parts to create the composite primaryKey:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ts",children:"\n// inserting with composite primary\nawait myRxCollection.insert({\n // id, <- do not set the id, it will be filled by RxDB\n firstName: 'foo',\n lastName: 'bar'\n});\n\n// find by composite primary\nconst id = myRxCollection.schema.getPrimaryOfDocumentData({\n firstName: 'foo',\n lastName: 'bar'\n});\nconst myRxDocument = myRxCollection.findOne(id).exec();\n\n"})}),"\n",(0,i.jsx)(n.h2,{id:"indexes",children:"Indexes"}),"\n",(0,i.jsx)(n.p,{children:"RxDB supports secondary indexes which are defined at the schema-level of the collection."}),"\n",(0,i.jsxs)(n.p,{children:["Index is only allowed on field types ",(0,i.jsx)(n.code,{children:"string"}),", ",(0,i.jsx)(n.code,{children:"integer"})," and ",(0,i.jsx)(n.code,{children:"number"}),". Some RxStorages allow to use ",(0,i.jsx)(n.code,{children:"boolean"})," fields as index."]}),"\n",(0,i.jsxs)(n.p,{children:["Depending on the field type, you must have set some meta attributes like ",(0,i.jsx)(n.code,{children:"maxLength"})," or ",(0,i.jsx)(n.code,{children:"minimum"}),". This is required so that RxDB\nis able to know the maximum string representation length of a field, which is needed to craft custom indexes on several ",(0,i.jsx)(n.code,{children:"RxStorage"})," implementations."]}),"\n",(0,i.jsxs)(n.p,{children:[(0,i.jsx)(n.strong,{children:"NOTICE:"})," RxDB will always append the ",(0,i.jsx)(n.code,{children:"primaryKey"})," to all indexes to ensure a deterministic sort order of query results. You do not have to add the ",(0,i.jsx)(n.code,{children:"primaryKey"})," to any index."]}),"\n",(0,i.jsx)(n.h3,{id:"index-example",children:"Index-example"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-javascript",children:"const schemaWithIndexes = {\n version: 0,\n title: 'human schema with indexes',\n keyCompression: true,\n primaryKey: 'id',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 100 // <- the primary key must have set maxLength\n },\n firstName: {\n type: 'string',\n maxLength: 100 // <- string-fields that are used as an index, must have set maxLength.\n },\n lastName: {\n type: 'string'\n },\n active: {\n type: 'boolean'\n },\n familyName: {\n type: 'string'\n },\n balance: {\n type: 'number',\n\n // number fields that are used in an index, must have set minimum, maximum and multipleOf\n minimum: 0,\n maximum: 100000,\n multipleOf: 0.01\n },\n creditCards: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n cvc: {\n type: 'number'\n }\n }\n } \n }\n },\n required: [\n 'id',\n 'active' // <- boolean fields that are used in an index, must be required. \n ],\n indexes: [\n 'firstName', // <- this will create a simple index for the `firstName` field\n ['active', 'firstName'], // <- this will create a compound-index for these two fields\n 'active'\n ]\n};\n"})}),"\n",(0,i.jsx)(n.h1,{id:"internalindexes",children:"internalIndexes"}),"\n",(0,i.jsxs)(n.p,{children:["When you use RxDB on the server-side, you might want to use internalIndexes to speed up internal queries. ",(0,i.jsx)(n.a,{href:"/server#server-only-indexes",children:"Read more"})]}),"\n",(0,i.jsx)(n.h2,{id:"attachments",children:"attachments"}),"\n",(0,i.jsxs)(n.p,{children:["To use attachments in the collection, you have to add the ",(0,i.jsx)(n.code,{children:"attachments"}),"-attribute to the schema. ",(0,i.jsx)(n.a,{href:"/rx-attachment.html",children:"See RxAttachment"}),"."]}),"\n",(0,i.jsx)(n.h2,{id:"default",children:"default"}),"\n",(0,i.jsx)(n.p,{children:"Default values can only be defined for first-level fields.\nWhenever you insert a document unset fields will be filled with default-values."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-javascript",children:"const schemaWithDefaultAge = {\n version: 0,\n primaryKey: 'id',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 100 // <- the primary key must have set maxLength\n },\n firstName: {\n type: 'string'\n },\n lastName: {\n type: 'string'\n },\n age: {\n type: 'integer',\n default: 20 // <- default will be used\n }\n },\n required: ['id']\n};\n"})}),"\n",(0,i.jsx)(n.h2,{id:"final",children:"final"}),"\n",(0,i.jsxs)(n.p,{children:["By setting a field to ",(0,i.jsx)(n.code,{children:"final"}),", you make sure it cannot be modified later. Final fields are always required.\nFinal fields cannot be observed because they will not change."]}),"\n",(0,i.jsx)(n.p,{children:"Advantages:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"With final fields you can ensure that no-one accidentally modifies the data."}),"\n",(0,i.jsxs)(n.li,{children:["When you enable the ",(0,i.jsx)(n.code,{children:"eventReduce"})," algorithm, some performance-improvements are done."]}),"\n"]}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-javascript",children:"const schemaWithFinalAge = {\n version: 0,\n primaryKey: 'id',\n type: 'object',\n properties: {\n id: {\n type: 'string',\n maxLength: 100 // <- the primary key must have set maxLength\n },\n firstName: {\n type: 'string'\n },\n lastName: {\n type: 'string'\n },\n age: {\n type: 'integer',\n final: true\n }\n },\n required: ['id']\n};\n"})}),"\n",(0,i.jsx)(n.h2,{id:"notice-not-everything-within-the-jsonschema-spec-is-allowed",children:"NOTICE: Not everything within the jsonschema-spec is allowed"}),"\n",(0,i.jsxs)(n.p,{children:["The schema is not only used to validate objects before they are written into the database, but also used to map getters to observe and populate single fieldnames, keycompression and other things. Therefore you can not use every schema which would be valid for the spec of ",(0,i.jsx)(n.a,{href:"http://json-schema.org/",children:"json-schema.org"}),".\nFor example, fieldnames must match the regex ",(0,i.jsx)(n.code,{children:"^[a-zA-Z][[a-zA-Z0-9_]*]?[a-zA-Z0-9]$"})," and ",(0,i.jsx)(n.code,{children:"additionalProperties"})," is always set to ",(0,i.jsx)(n.code,{children:"false"}),". But don't worry, RxDB will instantly throw an error when you pass an invalid schema into it."]})]})}function c(e={}){const{wrapper:n}={...(0,s.a)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(d,{...e})}):d(e)}},1151:(e,n,t)=>{t.d(n,{Z:()=>l,a:()=>r});var i=t(7294);const s={},a=i.createContext(s);function r(e){const n=i.useContext(a);return i.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function l(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:r(e.components),i.createElement(a.Provider,{value:n},e.children)}}}]); \ No newline at end of file diff --git a/docs/assets/js/6cbff7c2.3557e9bd.js b/docs/assets/js/6cbff7c2.3557e9bd.js deleted file mode 100644 index 85f8ec341b5..00000000000 --- a/docs/assets/js/6cbff7c2.3557e9bd.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[1826],{9829:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>l,contentTitle:()=>o,default:()=>h,frontMatter:()=>n,metadata:()=>a,toc:()=>c});var s=r(5893),i=r(1151);const n={title:"OPFS RxStorage \ud83d\udc51",slug:"rx-storage-opfs.html",description:"Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage"},o="Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage",a={id:"rx-storage-opfs",title:"OPFS RxStorage \ud83d\udc51",description:"Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage",source:"@site/docs/rx-storage-opfs.md",sourceDirName:".",slug:"/rx-storage-opfs.html",permalink:"/rx-storage-opfs.html",draft:!1,unlisted:!1,editUrl:"https://github.com/pubkey/rxdb/tree/master/docs-src/docs/rx-storage-opfs.md",tags:[],version:"current",frontMatter:{title:"OPFS RxStorage \ud83d\udc51",slug:"rx-storage-opfs.html",description:"Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage"},sidebar:"tutorialSidebar",previous:{title:"IndexedDB RxStorage \ud83d\udc51",permalink:"/rx-storage-indexeddb.html"},next:{title:"SQLite RxStorage \ud83d\udc51",permalink:"/rx-storage-sqlite.html"}},l={},c=[{value:"What is OPFS",id:"what-is-opfs",level:2},{value:"OPFS limitations",id:"opfs-limitations",level:3},{value:"How the OPFS API works",id:"how-the-opfs-api-works",level:2},{value:"OPFS performance",id:"opfs-performance",level:2},{value:"Using OPFS as RxStorage in RxDB",id:"using-opfs-as-rxstorage-in-rxdb",level:2},{value:"Building a custom worker.js",id:"building-a-custom-workerjs",level:2},{value:"OPFS in Electron, React-Native or Capacitor.js",id:"opfs-in-electron-react-native-or-capacitorjs",level:2},{value:"Difference between File System Access API and Origin Private File System (OPFS)",id:"difference-between-file-system-access-api-and-origin-private-file-system-opfs",level:2},{value:"Learn more about OPFS:",id:"learn-more-about-opfs",level:2}];function d(e){const t={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,i.a)(),...e.components};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(t.h1,{id:"origin-private-file-system-opfs-database-with-the-rxdb-opfs-rxstorage",children:"Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage"}),"\n",(0,s.jsxs)(t.p,{children:["With the ",(0,s.jsx)(t.a,{href:"https://rxdb.info/",children:"RxDB"})," OPFS storage you can build a fully featured database on top of the Origin Private File System (OPFS) browser API. Compared to other storage solutions, it has a way better performance."]}),"\n",(0,s.jsx)(t.h2,{id:"what-is-opfs",children:"What is OPFS"}),"\n",(0,s.jsxs)(t.p,{children:["The ",(0,s.jsx)(t.strong,{children:"Origin Private File System (OPFS)"})," is a native browser storage API that allows web applications to manage files in a private, sandboxed, ",(0,s.jsx)(t.strong,{children:"origin-specific virtual filesystem"}),". Unlike ",(0,s.jsx)(t.a,{href:"/rx-storage-indexeddb.html",children:"IndexedDB"})," and ",(0,s.jsx)(t.a,{href:"/articles/localstorage.html",children:"LocalStorage"}),", which are optimized as object/key-value storage, OPFS provides more granular control for file operations, enabling byte-by-byte access, file streaming, and even low-level manipulations.\nOPFS is ideal for applications requiring ",(0,s.jsx)(t.strong,{children:"high-performance"})," file operations (",(0,s.jsx)(t.strong,{children:"3x-4x faster compared to IndexedDB"}),") inside of a client-side application, offering advantages like improved speed, more efficient use of resources, and enhanced security and privacy features."]}),"\n",(0,s.jsx)(t.h3,{id:"opfs-limitations",children:"OPFS limitations"}),"\n",(0,s.jsxs)(t.p,{children:["From the beginning of 2023, the Origin Private File System API is supported by ",(0,s.jsx)(t.a,{href:"https://caniuse.com/native-filesystem-api",children:"all modern browsers"})," like Safari, Chrome, Edge and Firefox. Only Internet Explorer is not supported and likely will never get support."]}),"\n",(0,s.jsxs)(t.p,{children:["It is important to know that the OPFS API is ",(0,s.jsxs)(t.strong,{children:["only available inside of a ",(0,s.jsx)(t.a,{href:"/rx-storage-worker.html",children:"WebWorker"})]}),".\nIt cannot be used in the main thread, an iFrame or even a ",(0,s.jsx)(t.a,{href:"/rx-storage-shared-worker.html",children:"SharedWorker"}),".\nIf you call the OPFS ",(0,s.jsx)(t.code,{children:"getFileHandle()"})," function in the main thread, it will throw the error ",(0,s.jsx)(t.code,{children:"Uncaught DOMException: A requested file or directory could not be found at the time an operation was processed."}),"."]}),"\n",(0,s.jsxs)(t.p,{children:["While there is no concrete ",(0,s.jsx)(t.strong,{children:"data size limit"})," defined by the API, browsers will refuse to store more data at some point.\nIf no more data can be written, a ",(0,s.jsx)(t.code,{children:"QuotaExceededError"})," is thrown which should be handled by the application, like showing an error message to the user."]}),"\n",(0,s.jsx)(t.h2,{id:"how-the-opfs-api-works",children:"How the OPFS API works"}),"\n",(0,s.jsxs)(t.p,{children:["The OPFS API is pretty straightforward to use. First you get the root filesystem. Then you can create files and directory on that. Notice that whenever you write to, or read from a file, an ",(0,s.jsx)(t.code,{children:"ArrayBuffer"})," must be used that contains the data. It is not possible to write plain strings or objects into the file. Therefore the ",(0,s.jsx)(t.code,{children:"TextEncoder"})," and ",(0,s.jsx)(t.code,{children:"TextDecoder"})," API must be used."]}),"\n",(0,s.jsxs)(t.p,{children:["Also notice that the methods of ",(0,s.jsx)(t.code,{children:"FileSystemSyncAccessHandle"})," have been asynchronous in the past, but are synchronous since Chromium 108. To make it less confusing, we just use ",(0,s.jsx)(t.code,{children:"await"})," in front of them, so it will work in both cases."]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",children:"// Access the root directory of the origin's private file system\nconst root = await navigator.storage.getDirectory();\n\n// create a subdirectory\nconst diaryDirectory = await root.getDirectoryHandle('subfolder', { create : true });\n\n// Create a new file named 'example.txt'\nconst fileHandle = await diaryDirectory.getFileHandle('example.txt', { create: true });\n\n// Create a FileSystemSyncAccessHandle on the file.\nconst accessHandle = await draftFile.createSyncAccessHandle();\n\n// Get the size of the file.\nconst fileSize = accessHandle.getSize();\n\n// read file and transform data to string\nconst fileSize = await accessHandle.getSize();\nconst readBuffer = new Uint8Array(fileSize);\nawait accessHandle.read(readBuffer, { at: 0 });\nconst contentAsString = new TextDecoder().decode(readBuffer);\n\n// Write a sentence to the end of the file.\nconst writeBuffer = new TextEncoder().encode('Hello from RxDB');\nconst writeSize = await accessHandle.write(writeBuffer, { \"at\" : readSize });\n\n// Truncate file to 10 bytes.\nawait accessHandle.truncate(10);\n\n// Persist changes to disk.\nawait accessHandle.flush();\n\n// Always close FileSystemSyncAccessHandle if done, so others can open the file again.\nawait accessHandle.close();\n"})}),"\n",(0,s.jsxs)(t.p,{children:["Are more detailed description of the OPFS API can be found on mdn ",(0,s.jsx)(t.a,{href:"https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system",children:"here"}),"."]}),"\n",(0,s.jsx)(t.h2,{id:"opfs-performance",children:"OPFS performance"}),"\n",(0,s.jsxs)(t.p,{children:["Because the Origin Private File System API provides low-level access to binary files, it is much faster compared to ",(0,s.jsx)(t.a,{href:"/slow-indexeddb.html",children:"IndexedDB"})," or ",(0,s.jsx)(t.a,{href:"/articles/localstorage.html",children:"localStorage"}),". According to the ",(0,s.jsx)(t.a,{href:"https://pubkey.github.io/client-side-databases/database-comparison/index.html",children:"storage performance test"}),", OPFS is up to 2x times faster on plain inserts when a new file is created on each write. Reads are even faster."]}),"\n",(0,s.jsxs)(t.p,{children:["A good comparison about real world scenarios, are the ",(0,s.jsx)(t.a,{href:"/rx-storage-performance.html",children:"performance results"})," of the various RxDB storages. Here it shows that reads are up to 4x faster compared to IndexedDB, even with complex queries:"]}),"\n",(0,s.jsx)("p",{align:"center",children:(0,s.jsx)("img",{src:"./files/rx-storage-performance-browser.png",alt:"RxStorage performance - browser",width:"700"})}),"\n",(0,s.jsx)(t.h2,{id:"using-opfs-as-rxstorage-in-rxdb",children:"Using OPFS as RxStorage in RxDB"}),"\n",(0,s.jsxs)(t.p,{children:["The OPFS ",(0,s.jsx)(t.a,{href:"/rx-storage.html",children:"RxStorage"})," itself must run inside a WebWorker. Therefore we use the ",(0,s.jsx)(t.a,{href:"/rx-storage-worker.html",children:"Worker RxStorage"})," and let it point to the prebuild ",(0,s.jsx)(t.code,{children:"opfs.worker.js"})," file that comes shipped with \ud83d\udc51 RxDB Premium."]}),"\n",(0,s.jsxs)(t.p,{children:["Notice that the OPFS RxStorage is part of the ",(0,s.jsx)(t.a,{href:"/premium",children:"\ud83d\udc51 RxDB Premium"})," plugin that must be purchased."]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",children:"import {\n createRxDatabase\n} from 'rxdb';\nimport { getRxStorageWorker } from 'rxdb-premium/plugins/storage-worker';\n\nconst database = await createRxDatabase({\n name: 'mydatabase',\n storage: getRxStorageWorker(\n {\n /**\n * This file must be statically served from a webserver.\n * You might want to first copy it somewhere outside of\n * your node_modules folder.\n */\n workerInput: 'node_modules/rxdb-premium/dist/workers/opfs.worker.js'\n }\n )\n});\n"})}),"\n",(0,s.jsxs)(t.h2,{id:"building-a-custom-workerjs",children:["Building a custom ",(0,s.jsx)(t.code,{children:"worker.js"})]}),"\n",(0,s.jsxs)(t.p,{children:["When you want to run additional plugins like storage wrappers or replication ",(0,s.jsx)(t.strong,{children:"inside"})," of the worker, you have to build your own ",(0,s.jsx)(t.code,{children:"worker.js"})," file. You can do that similar to other workers by calling ",(0,s.jsx)(t.code,{children:"exposeWorkerRxStorage"})," like described in the ",(0,s.jsx)(t.a,{href:"/rx-storage-worker.html",children:"worker storage plugin"}),"."]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",children:"// inside of worker.js\nimport { getRxStorageOPFS } from 'rxdb-premium/plugins/storage-opfs';\nimport { exposeWorkerRxStorage } from 'rxdb-premium/plugins/storage-worker';\n\nconst storage = getRxStorageOPFS();\nexposeWorkerRxStorage({\n storage\n});\n"})}),"\n",(0,s.jsx)(t.h2,{id:"opfs-in-electron-react-native-or-capacitorjs",children:"OPFS in Electron, React-Native or Capacitor.js"}),"\n",(0,s.jsx)(t.p,{children:"Origin Private File System is a browser API that is only accessible in browsers. Other JavaScript like React-Native or Node.js, do not support it."}),"\n",(0,s.jsxs)(t.p,{children:[(0,s.jsx)(t.strong,{children:"Electron"})," has two JavaScript contexts: the browser (chromium) context and the Node.js context. While you could use the OPFS API in the browser context, it is not recommended. Instead you should use the Filesystem API of Node.js and then only transfer the relevant data with the ",(0,s.jsx)(t.a,{href:"https://www.electronjs.org/de/docs/latest/api/ipc-renderer",children:"ipcRenderer"}),". With RxDB that is pretty easy to configure:"]}),"\n",(0,s.jsxs)(t.ul,{children:["\n",(0,s.jsxs)(t.li,{children:["In the ",(0,s.jsx)(t.code,{children:"main.js"}),", expose the ",(0,s.jsx)(t.a,{href:"/rx-storage-filesystem-node.html",children:"Node Filesystem"})," storage with the ",(0,s.jsx)(t.code,{children:"exposeIpcMainRxStorage()"})," that comes with the ",(0,s.jsx)(t.a,{href:"/electron.html",children:"electron plugin"})]}),"\n",(0,s.jsxs)(t.li,{children:["In the browser context, access the main storage with the ",(0,s.jsx)(t.code,{children:"getRxStorageIpcRenderer()"})," method."]}),"\n"]}),"\n",(0,s.jsxs)(t.p,{children:[(0,s.jsx)(t.strong,{children:"React Native"})," (and Expo) does not have an OPFS API. You could use the ReactNative Filesystem to directly write data. But to get a fully featured database like RxDB it is easier to use the ",(0,s.jsx)(t.a,{href:"/rx-storage-sqlite.html",children:"SQLite RxStorage"})," which starts an SQLite database inside of the ReactNative app and uses that to do the database operations."]}),"\n",(0,s.jsxs)(t.p,{children:[(0,s.jsx)(t.strong,{children:"Capacitor.js"})," is able to access the OPFS API."]}),"\n",(0,s.jsxs)(t.h2,{id:"difference-between-file-system-access-api-and-origin-private-file-system-opfs",children:["Difference between ",(0,s.jsx)(t.code,{children:"File System Access API"})," and ",(0,s.jsx)(t.code,{children:"Origin Private File System (OPFS)"})]}),"\n",(0,s.jsxs)(t.p,{children:["Often developers are confused with the differences between the ",(0,s.jsx)(t.code,{children:"File System Access API"})," and the ",(0,s.jsx)(t.code,{children:"Origin Private File System (OPFS)"}),"."]}),"\n",(0,s.jsxs)(t.ul,{children:["\n",(0,s.jsxs)(t.li,{children:["The ",(0,s.jsx)(t.code,{children:"File System API"})," provides access to the files on the device file system, like the ones shown in the file explorer of the operating system. To use the ile System API, the user has to actively select the files from a filepicker."]}),"\n",(0,s.jsxs)(t.li,{children:[(0,s.jsx)(t.code,{children:"Origin Private File System (OPFS)"})," is a sub-part of the ",(0,s.jsx)(t.code,{children:"File System API"})," and it only describes the things you can do with the filesystem root from ",(0,s.jsx)(t.code,{children:"navigator.storage.getDirectory()"}),". OPFS writes to a ",(0,s.jsx)(t.strong,{children:"sandboxed"})," filesystem, not visible to the user. Therefore the user does not have to actively select or allow the data access."]}),"\n"]}),"\n",(0,s.jsx)(t.h2,{id:"learn-more-about-opfs",children:"Learn more about OPFS:"}),"\n",(0,s.jsxs)(t.ul,{children:["\n",(0,s.jsx)(t.li,{children:(0,s.jsx)(t.a,{href:"https://webkit.org/blog/12257/the-file-system-access-api-with-origin-private-file-system/",children:"WebKit: The File System API with Origin Private File System"})}),"\n",(0,s.jsx)(t.li,{children:(0,s.jsx)(t.a,{href:"https://caniuse.com/native-filesystem-api",children:"Browser Support"})}),"\n",(0,s.jsx)(t.li,{children:(0,s.jsx)(t.a,{href:"https://pubkey.github.io/client-side-databases/database-comparison/index.html",children:"Performance Test Tool"})}),"\n"]})]})}function h(e={}){const{wrapper:t}={...(0,i.a)(),...e.components};return t?(0,s.jsx)(t,{...e,children:(0,s.jsx)(d,{...e})}):d(e)}},1151:(e,t,r)=>{r.d(t,{Z:()=>a,a:()=>o});var s=r(7294);const i={},n=s.createContext(i);function o(e){const t=s.useContext(n);return s.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function a(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(i):e.components||i:o(e.components),s.createElement(n.Provider,{value:t},e.children)}}}]); \ No newline at end of file diff --git a/docs/assets/js/6cbff7c2.bad7d1a6.js b/docs/assets/js/6cbff7c2.bad7d1a6.js new file mode 100644 index 00000000000..2b670b8661e --- /dev/null +++ b/docs/assets/js/6cbff7c2.bad7d1a6.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[1826],{9829:(e,t,r)=>{r.r(t),r.d(t,{assets:()=>l,contentTitle:()=>n,default:()=>h,frontMatter:()=>o,metadata:()=>a,toc:()=>c});var s=r(5893),i=r(1151);const o={title:"OPFS RxStorage \ud83d\udc51",slug:"rx-storage-opfs.html",description:"Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage"},n="Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage",a={id:"rx-storage-opfs",title:"OPFS RxStorage \ud83d\udc51",description:"Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage",source:"@site/docs/rx-storage-opfs.md",sourceDirName:".",slug:"/rx-storage-opfs.html",permalink:"/rx-storage-opfs.html",draft:!1,unlisted:!1,editUrl:"https://github.com/pubkey/rxdb/tree/master/docs-src/docs/rx-storage-opfs.md",tags:[],version:"current",frontMatter:{title:"OPFS RxStorage \ud83d\udc51",slug:"rx-storage-opfs.html",description:"Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage"},sidebar:"tutorialSidebar",previous:{title:"IndexedDB RxStorage \ud83d\udc51",permalink:"/rx-storage-indexeddb.html"},next:{title:"SQLite RxStorage \ud83d\udc51",permalink:"/rx-storage-sqlite.html"}},l={},c=[{value:"What is OPFS",id:"what-is-opfs",level:2},{value:"OPFS limitations",id:"opfs-limitations",level:3},{value:"How the OPFS API works",id:"how-the-opfs-api-works",level:2},{value:"OPFS performance",id:"opfs-performance",level:2},{value:"Using OPFS as RxStorage in RxDB",id:"using-opfs-as-rxstorage-in-rxdb",level:2},{value:"Building a custom worker.js",id:"building-a-custom-workerjs",level:2},{value:"Setting jsonPositionSize to increase the maximum database size.",id:"setting-jsonpositionsize-to-increase-the-maximum-database-size",level:2},{value:"OPFS in Electron, React-Native or Capacitor.js",id:"opfs-in-electron-react-native-or-capacitorjs",level:2},{value:"Difference between File System Access API and Origin Private File System (OPFS)",id:"difference-between-file-system-access-api-and-origin-private-file-system-opfs",level:2},{value:"Learn more about OPFS:",id:"learn-more-about-opfs",level:2}];function d(e){const t={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,i.a)(),...e.components};return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(t.h1,{id:"origin-private-file-system-opfs-database-with-the-rxdb-opfs-rxstorage",children:"Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage"}),"\n",(0,s.jsxs)(t.p,{children:["With the ",(0,s.jsx)(t.a,{href:"https://rxdb.info/",children:"RxDB"})," OPFS storage you can build a fully featured database on top of the Origin Private File System (OPFS) browser API. Compared to other storage solutions, it has a way better performance."]}),"\n",(0,s.jsx)(t.h2,{id:"what-is-opfs",children:"What is OPFS"}),"\n",(0,s.jsxs)(t.p,{children:["The ",(0,s.jsx)(t.strong,{children:"Origin Private File System (OPFS)"})," is a native browser storage API that allows web applications to manage files in a private, sandboxed, ",(0,s.jsx)(t.strong,{children:"origin-specific virtual filesystem"}),". Unlike ",(0,s.jsx)(t.a,{href:"/rx-storage-indexeddb.html",children:"IndexedDB"})," and ",(0,s.jsx)(t.a,{href:"/articles/localstorage.html",children:"LocalStorage"}),", which are optimized as object/key-value storage, OPFS provides more granular control for file operations, enabling byte-by-byte access, file streaming, and even low-level manipulations.\nOPFS is ideal for applications requiring ",(0,s.jsx)(t.strong,{children:"high-performance"})," file operations (",(0,s.jsx)(t.strong,{children:"3x-4x faster compared to IndexedDB"}),") inside of a client-side application, offering advantages like improved speed, more efficient use of resources, and enhanced security and privacy features."]}),"\n",(0,s.jsx)(t.h3,{id:"opfs-limitations",children:"OPFS limitations"}),"\n",(0,s.jsxs)(t.p,{children:["From the beginning of 2023, the Origin Private File System API is supported by ",(0,s.jsx)(t.a,{href:"https://caniuse.com/native-filesystem-api",children:"all modern browsers"})," like Safari, Chrome, Edge and Firefox. Only Internet Explorer is not supported and likely will never get support."]}),"\n",(0,s.jsxs)(t.p,{children:["It is important to know that the OPFS API is ",(0,s.jsxs)(t.strong,{children:["only available inside of a ",(0,s.jsx)(t.a,{href:"/rx-storage-worker.html",children:"WebWorker"})]}),".\nIt cannot be used in the main thread, an iFrame or even a ",(0,s.jsx)(t.a,{href:"/rx-storage-shared-worker.html",children:"SharedWorker"}),".\nIf you call the OPFS ",(0,s.jsx)(t.code,{children:"getFileHandle()"})," function in the main thread, it will throw the error ",(0,s.jsx)(t.code,{children:"Uncaught DOMException: A requested file or directory could not be found at the time an operation was processed."}),"."]}),"\n",(0,s.jsxs)(t.p,{children:["While there is no concrete ",(0,s.jsx)(t.strong,{children:"data size limit"})," defined by the API, browsers will refuse to store more data at some point.\nIf no more data can be written, a ",(0,s.jsx)(t.code,{children:"QuotaExceededError"})," is thrown which should be handled by the application, like showing an error message to the user."]}),"\n",(0,s.jsx)(t.h2,{id:"how-the-opfs-api-works",children:"How the OPFS API works"}),"\n",(0,s.jsxs)(t.p,{children:["The OPFS API is pretty straightforward to use. First you get the root filesystem. Then you can create files and directory on that. Notice that whenever you write to, or read from a file, an ",(0,s.jsx)(t.code,{children:"ArrayBuffer"})," must be used that contains the data. It is not possible to write plain strings or objects into the file. Therefore the ",(0,s.jsx)(t.code,{children:"TextEncoder"})," and ",(0,s.jsx)(t.code,{children:"TextDecoder"})," API must be used."]}),"\n",(0,s.jsxs)(t.p,{children:["Also notice that the methods of ",(0,s.jsx)(t.code,{children:"FileSystemSyncAccessHandle"})," have been asynchronous in the past, but are synchronous since Chromium 108. To make it less confusing, we just use ",(0,s.jsx)(t.code,{children:"await"})," in front of them, so it will work in both cases."]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",children:"// Access the root directory of the origin's private file system\nconst root = await navigator.storage.getDirectory();\n\n// create a subdirectory\nconst diaryDirectory = await root.getDirectoryHandle('subfolder', { create : true });\n\n// Create a new file named 'example.txt'\nconst fileHandle = await diaryDirectory.getFileHandle('example.txt', { create: true });\n\n// Create a FileSystemSyncAccessHandle on the file.\nconst accessHandle = await draftFile.createSyncAccessHandle();\n\n// Get the size of the file.\nconst fileSize = accessHandle.getSize();\n\n// read file and transform data to string\nconst fileSize = await accessHandle.getSize();\nconst readBuffer = new Uint8Array(fileSize);\nawait accessHandle.read(readBuffer, { at: 0 });\nconst contentAsString = new TextDecoder().decode(readBuffer);\n\n// Write a sentence to the end of the file.\nconst writeBuffer = new TextEncoder().encode('Hello from RxDB');\nconst writeSize = await accessHandle.write(writeBuffer, { \"at\" : readSize });\n\n// Truncate file to 10 bytes.\nawait accessHandle.truncate(10);\n\n// Persist changes to disk.\nawait accessHandle.flush();\n\n// Always close FileSystemSyncAccessHandle if done, so others can open the file again.\nawait accessHandle.close();\n"})}),"\n",(0,s.jsxs)(t.p,{children:["Are more detailed description of the OPFS API can be found on mdn ",(0,s.jsx)(t.a,{href:"https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system",children:"here"}),"."]}),"\n",(0,s.jsx)(t.h2,{id:"opfs-performance",children:"OPFS performance"}),"\n",(0,s.jsxs)(t.p,{children:["Because the Origin Private File System API provides low-level access to binary files, it is much faster compared to ",(0,s.jsx)(t.a,{href:"/slow-indexeddb.html",children:"IndexedDB"})," or ",(0,s.jsx)(t.a,{href:"/articles/localstorage.html",children:"localStorage"}),". According to the ",(0,s.jsx)(t.a,{href:"https://pubkey.github.io/client-side-databases/database-comparison/index.html",children:"storage performance test"}),", OPFS is up to 2x times faster on plain inserts when a new file is created on each write. Reads are even faster."]}),"\n",(0,s.jsxs)(t.p,{children:["A good comparison about real world scenarios, are the ",(0,s.jsx)(t.a,{href:"/rx-storage-performance.html",children:"performance results"})," of the various RxDB storages. Here it shows that reads are up to 4x faster compared to IndexedDB, even with complex queries:"]}),"\n",(0,s.jsx)("p",{align:"center",children:(0,s.jsx)("img",{src:"./files/rx-storage-performance-browser.png",alt:"RxStorage performance - browser",width:"700"})}),"\n",(0,s.jsx)(t.h2,{id:"using-opfs-as-rxstorage-in-rxdb",children:"Using OPFS as RxStorage in RxDB"}),"\n",(0,s.jsxs)(t.p,{children:["The OPFS ",(0,s.jsx)(t.a,{href:"/rx-storage.html",children:"RxStorage"})," itself must run inside a WebWorker. Therefore we use the ",(0,s.jsx)(t.a,{href:"/rx-storage-worker.html",children:"Worker RxStorage"})," and let it point to the prebuild ",(0,s.jsx)(t.code,{children:"opfs.worker.js"})," file that comes shipped with \ud83d\udc51 RxDB Premium."]}),"\n",(0,s.jsxs)(t.p,{children:["Notice that the OPFS RxStorage is part of the ",(0,s.jsx)(t.a,{href:"/premium",children:"\ud83d\udc51 RxDB Premium"})," plugin that must be purchased."]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",children:"import {\n createRxDatabase\n} from 'rxdb';\nimport { getRxStorageWorker } from 'rxdb-premium/plugins/storage-worker';\n\nconst database = await createRxDatabase({\n name: 'mydatabase',\n storage: getRxStorageWorker(\n {\n /**\n * This file must be statically served from a webserver.\n * You might want to first copy it somewhere outside of\n * your node_modules folder.\n */\n workerInput: 'node_modules/rxdb-premium/dist/workers/opfs.worker.js'\n }\n )\n});\n"})}),"\n",(0,s.jsxs)(t.h2,{id:"building-a-custom-workerjs",children:["Building a custom ",(0,s.jsx)(t.code,{children:"worker.js"})]}),"\n",(0,s.jsxs)(t.p,{children:["When you want to run additional plugins like storage wrappers or replication ",(0,s.jsx)(t.strong,{children:"inside"})," of the worker, you have to build your own ",(0,s.jsx)(t.code,{children:"worker.js"})," file. You can do that similar to other workers by calling ",(0,s.jsx)(t.code,{children:"exposeWorkerRxStorage"})," like described in the ",(0,s.jsx)(t.a,{href:"/rx-storage-worker.html",children:"worker storage plugin"}),"."]}),"\n",(0,s.jsx)(t.pre,{children:(0,s.jsx)(t.code,{className:"language-ts",children:"// inside of worker.js\nimport { getRxStorageOPFS } from 'rxdb-premium/plugins/storage-opfs';\nimport { exposeWorkerRxStorage } from 'rxdb-premium/plugins/storage-worker';\n\nconst storage = getRxStorageOPFS();\nexposeWorkerRxStorage({\n storage\n});\n"})}),"\n",(0,s.jsxs)(t.h2,{id:"setting-jsonpositionsize-to-increase-the-maximum-database-size",children:["Setting ",(0,s.jsx)(t.code,{children:"jsonPositionSize"})," to increase the maximum database size."]}),"\n",(0,s.jsxs)(t.p,{children:["By default the ",(0,s.jsx)(t.code,{children:"jsonPositionSize"})," value is set to ",(0,s.jsx)(t.code,{children:"8"})," which allows the database to get up to 100 megabytes in size (per collection).\nThis is ok for most use cases but you might want to just increase ",(0,s.jsx)(t.code,{children:"jsonPositionSize"})," to ",(0,s.jsx)(t.code,{children:"14"}),".\nIn the next major RxDB version the default will be set to ",(0,s.jsx)(t.code,{children:"14"}),", but this was not possible without introducing a breaking change."]}),"\n",(0,s.jsxs)(t.p,{children:["NOTICE: If you have already stored data, you cannot just change the ",(0,s.jsx)(t.code,{children:"jsonPositionSize"})," value because your stored binary data will not be compatible anymore."]}),"\n",(0,s.jsxs)(t.p,{children:["Also there is a ",(0,s.jsx)(t.code,{children:"opfs-big.worker.js"})," file that has ",(0,s.jsx)(t.code,{children:"jsonPositionSize"})," set to ",(0,s.jsx)(t.code,{children:"14"})," already."]}),"\n",(0,s.jsx)(t.h2,{id:"opfs-in-electron-react-native-or-capacitorjs",children:"OPFS in Electron, React-Native or Capacitor.js"}),"\n",(0,s.jsx)(t.p,{children:"Origin Private File System is a browser API that is only accessible in browsers. Other JavaScript like React-Native or Node.js, do not support it."}),"\n",(0,s.jsxs)(t.p,{children:[(0,s.jsx)(t.strong,{children:"Electron"})," has two JavaScript contexts: the browser (chromium) context and the Node.js context. While you could use the OPFS API in the browser context, it is not recommended. Instead you should use the Filesystem API of Node.js and then only transfer the relevant data with the ",(0,s.jsx)(t.a,{href:"https://www.electronjs.org/de/docs/latest/api/ipc-renderer",children:"ipcRenderer"}),". With RxDB that is pretty easy to configure:"]}),"\n",(0,s.jsxs)(t.ul,{children:["\n",(0,s.jsxs)(t.li,{children:["In the ",(0,s.jsx)(t.code,{children:"main.js"}),", expose the ",(0,s.jsx)(t.a,{href:"/rx-storage-filesystem-node.html",children:"Node Filesystem"})," storage with the ",(0,s.jsx)(t.code,{children:"exposeIpcMainRxStorage()"})," that comes with the ",(0,s.jsx)(t.a,{href:"/electron.html",children:"electron plugin"})]}),"\n",(0,s.jsxs)(t.li,{children:["In the browser context, access the main storage with the ",(0,s.jsx)(t.code,{children:"getRxStorageIpcRenderer()"})," method."]}),"\n"]}),"\n",(0,s.jsxs)(t.p,{children:[(0,s.jsx)(t.strong,{children:"React Native"})," (and Expo) does not have an OPFS API. You could use the ReactNative Filesystem to directly write data. But to get a fully featured database like RxDB it is easier to use the ",(0,s.jsx)(t.a,{href:"/rx-storage-sqlite.html",children:"SQLite RxStorage"})," which starts an SQLite database inside of the ReactNative app and uses that to do the database operations."]}),"\n",(0,s.jsxs)(t.p,{children:[(0,s.jsx)(t.strong,{children:"Capacitor.js"})," is able to access the OPFS API."]}),"\n",(0,s.jsxs)(t.h2,{id:"difference-between-file-system-access-api-and-origin-private-file-system-opfs",children:["Difference between ",(0,s.jsx)(t.code,{children:"File System Access API"})," and ",(0,s.jsx)(t.code,{children:"Origin Private File System (OPFS)"})]}),"\n",(0,s.jsxs)(t.p,{children:["Often developers are confused with the differences between the ",(0,s.jsx)(t.code,{children:"File System Access API"})," and the ",(0,s.jsx)(t.code,{children:"Origin Private File System (OPFS)"}),"."]}),"\n",(0,s.jsxs)(t.ul,{children:["\n",(0,s.jsxs)(t.li,{children:["The ",(0,s.jsx)(t.code,{children:"File System API"})," provides access to the files on the device file system, like the ones shown in the file explorer of the operating system. To use the ile System API, the user has to actively select the files from a filepicker."]}),"\n",(0,s.jsxs)(t.li,{children:[(0,s.jsx)(t.code,{children:"Origin Private File System (OPFS)"})," is a sub-part of the ",(0,s.jsx)(t.code,{children:"File System API"})," and it only describes the things you can do with the filesystem root from ",(0,s.jsx)(t.code,{children:"navigator.storage.getDirectory()"}),". OPFS writes to a ",(0,s.jsx)(t.strong,{children:"sandboxed"})," filesystem, not visible to the user. Therefore the user does not have to actively select or allow the data access."]}),"\n"]}),"\n",(0,s.jsx)(t.h2,{id:"learn-more-about-opfs",children:"Learn more about OPFS:"}),"\n",(0,s.jsxs)(t.ul,{children:["\n",(0,s.jsx)(t.li,{children:(0,s.jsx)(t.a,{href:"https://webkit.org/blog/12257/the-file-system-access-api-with-origin-private-file-system/",children:"WebKit: The File System API with Origin Private File System"})}),"\n",(0,s.jsx)(t.li,{children:(0,s.jsx)(t.a,{href:"https://caniuse.com/native-filesystem-api",children:"Browser Support"})}),"\n",(0,s.jsx)(t.li,{children:(0,s.jsx)(t.a,{href:"https://pubkey.github.io/client-side-databases/database-comparison/index.html",children:"Performance Test Tool"})}),"\n"]})]})}function h(e={}){const{wrapper:t}={...(0,i.a)(),...e.components};return t?(0,s.jsx)(t,{...e,children:(0,s.jsx)(d,{...e})}):d(e)}},1151:(e,t,r)=>{r.d(t,{Z:()=>a,a:()=>n});var s=r(7294);const i={},o=s.createContext(i);function n(e){const t=s.useContext(o);return s.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function a(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(i):e.components||i:n(e.components),s.createElement(o.Provider,{value:t},e.children)}}}]); \ No newline at end of file diff --git a/docs/assets/js/935f2afb.d48c48a7.js b/docs/assets/js/935f2afb.d3c0ca9b.js similarity index 74% rename from docs/assets/js/935f2afb.d48c48a7.js rename to docs/assets/js/935f2afb.d3c0ca9b.js index 68485954269..77446864d7a 100644 --- a/docs/assets/js/935f2afb.d48c48a7.js +++ b/docs/assets/js/935f2afb.d3c0ca9b.js @@ -1 +1 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[53],{1109:e=>{e.exports=JSON.parse('{"pluginId":"default","version":"current","label":"Next","banner":null,"badge":false,"noIndex":false,"className":"docs-version-current","isLast":true,"docsSidebars":{"tutorialSidebar":[{"type":"link","label":"\ud83d\ude80 Quickstart","href":"/quickstart.html","docId":"quickstart","unlisted":false},{"type":"link","label":"Installation","href":"/install.html","docId":"install","unlisted":false},{"type":"link","label":"Dev-Mode Plugin","href":"/dev-mode.html","docId":"dev-mode","unlisted":false},{"type":"link","label":"RxDatabase","href":"/rx-database.html","docId":"rx-database","unlisted":false},{"type":"link","label":"RxSchema","href":"/rx-schema.html","docId":"rx-schema","unlisted":false},{"type":"link","label":"RxCollection","href":"/rx-collection.html","docId":"rx-collection","unlisted":false},{"type":"link","label":"RxDocument","href":"/rx-document.html","docId":"rx-document","unlisted":false},{"type":"link","label":"RxQuery","href":"/rx-query.html","docId":"rx-query","unlisted":false},{"type":"link","label":"Attachments","href":"/rx-attachment.html","docId":"rx-attachment","unlisted":false},{"type":"category","label":"\ud83d\udcbe RxStorage","items":[{"type":"link","label":"\u2699\ufe0f Rxstorage Layer","href":"/rx-storage.html","docId":"rx-storage","unlisted":false},{"type":"link","label":"\ud83d\udcc8 RxStorage Performance","href":"/rx-storage-performance.html","docId":"rx-storage-performance","unlisted":false},{"type":"link","label":"Dexie.js RxStorage","href":"/rx-storage-dexie.html","docId":"rx-storage-dexie","unlisted":false},{"type":"link","label":"LokiJS RxStorage","href":"/rx-storage-lokijs.html","docId":"rx-storage-lokijs","unlisted":false},{"type":"link","label":"Memory RxStorage","href":"/rx-storage-memory.html","docId":"rx-storage-memory","unlisted":false},{"type":"link","label":"IndexedDB RxStorage \ud83d\udc51","href":"/rx-storage-indexeddb.html","docId":"rx-storage-indexeddb","unlisted":false},{"type":"link","label":"OPFS RxStorage \ud83d\udc51","href":"/rx-storage-opfs.html","docId":"rx-storage-opfs","unlisted":false},{"type":"link","label":"SQLite RxStorage \ud83d\udc51","href":"/rx-storage-sqlite.html","docId":"rx-storage-sqlite","unlisted":false},{"type":"link","label":"Node.js Filesystem RxStorage \ud83d\udc51","href":"/rx-storage-filesystem-node.html","docId":"rx-storage-filesystem-node","unlisted":false},{"type":"link","label":"MongoDB RxStorage","href":"/rx-storage-mongodb.html","docId":"rx-storage-mongodb","unlisted":false},{"type":"link","label":"DenoKV RxStorage","href":"/rx-storage-denokv.html","docId":"rx-storage-denokv","unlisted":false},{"type":"link","label":"FoundationDB RxStorage","href":"/rx-storage-foundationdb.html","docId":"rx-storage-foundationdb","unlisted":false},{"type":"link","label":"Remote RxStorage","href":"/rx-storage-remote.html","docId":"rx-storage-remote","unlisted":false},{"type":"link","label":"Worker RxStorage \ud83d\udc51","href":"/rx-storage-worker.html","docId":"rx-storage-worker","unlisted":false},{"type":"link","label":"SharedWorker RxStorage \ud83d\udc51","href":"/rx-storage-shared-worker.html","docId":"rx-storage-shared-worker","unlisted":false},{"type":"link","label":"Memory Synced RxStorage \ud83d\udc51","href":"/rx-storage-memory-synced.html","docId":"rx-storage-memory-synced","unlisted":false},{"type":"link","label":"Sharding RxStorage \ud83d\udc51","href":"/rx-storage-sharding.html","docId":"rx-storage-sharding","unlisted":false},{"type":"link","label":"RxStorage Localstorage Meta Optimizer \ud83d\udc51","href":"/rx-storage-localstorage-meta-optimizer.html","docId":"rx-storage-localstorage-meta-optimizer","unlisted":false},{"type":"link","label":"Electron Plugin","href":"/electron.html","docId":"electron","unlisted":false}],"collapsed":true,"collapsible":true},{"type":"category","label":"\ud83d\udd04 Replication","items":[{"type":"link","label":"\u2699\ufe0f Replication Protocol","href":"/replication.html","docId":"replication","unlisted":false},{"type":"link","label":"HTTP Replication","href":"/replication-http.html","docId":"replication-http","unlisted":false},{"type":"link","label":"GraphQL Replication","href":"/replication-graphql.html","docId":"replication-graphql","unlisted":false},{"type":"link","label":"Websocket Replication","href":"/replication-websocket.html","docId":"replication-websocket","unlisted":false},{"type":"link","label":"CouchDB Replication","href":"/replication-couchdb.html","docId":"replication-couchdb","unlisted":false},{"type":"link","label":"WebRTC Replication","href":"/replication-webrtc.html","docId":"replication-webrtc","unlisted":false},{"type":"link","label":"Firestore Replication","href":"/replication-firestore.html","docId":"replication-firestore","unlisted":false},{"type":"link","label":"NATS Replication","href":"/replication-nats.html","docId":"replication-nats","unlisted":false}],"collapsed":true,"collapsible":true},{"type":"category","label":"Migration","items":[{"type":"link","label":"Migration Schema","href":"/migration-schema.html","docId":"migration-schema","unlisted":false},{"type":"link","label":"Migration Storage","href":"/migration-storage.html","docId":"migration-storage","unlisted":false}],"collapsed":true,"collapsible":true},{"type":"link","label":"Encryption","href":"/encryption.html","docId":"encryption","unlisted":false},{"type":"link","label":"Key Compression","href":"/key-compression.html","docId":"key-compression","unlisted":false},{"type":"link","label":"Local Documents","href":"/rx-local-document.html","docId":"rx-local-document","unlisted":false},{"type":"link","label":"Leader Election","href":"/leader-election.html","docId":"leader-election","unlisted":false},{"type":"link","label":"Cleanup","href":"/cleanup.html","docId":"cleanup","unlisted":false},{"type":"link","label":"Backup","href":"/backup.html","docId":"backup","unlisted":false},{"type":"link","label":"Transactions, Conflicts and Revisions","href":"/transactions-conflicts-revisions.html","docId":"transactions-conflicts-revisions","unlisted":false},{"type":"link","label":"Middleware","href":"/middleware.html","docId":"middleware","unlisted":false},{"type":"link","label":"Query Cache","href":"/query-cache.html","docId":"query-cache","unlisted":false},{"type":"link","label":"CRDT - Conflict-free replicated data type","href":"/crdt.html","docId":"crdt","unlisted":false},{"type":"link","label":"Population","href":"/population.html","docId":"population","unlisted":false},{"type":"link","label":"ORM","href":"/orm.html","docId":"orm","unlisted":false},{"type":"link","label":"Query Optimizer \ud83d\udc51","href":"/query-optimizer.html","docId":"query-optimizer","unlisted":false},{"type":"link","label":"Logger \ud83d\udc51","href":"/logger.html","docId":"logger","unlisted":false},{"type":"link","label":"Plugins","href":"/plugins.html","docId":"plugins","unlisted":false},{"type":"link","label":"RxDB NoSQL Performance Tips","href":"/nosql-performance-tips.html","docId":"nosql-performance-tips","unlisted":false},{"type":"link","label":"Third Party Plugins","href":"/third-party-plugins.html","docId":"third-party-plugins","unlisted":false},{"type":"category","label":"Tutorials","items":[{"type":"link","label":"RxDB TypeScript Tutorial","href":"/tutorials/typescript.html","docId":"tutorials/typescript","unlisted":false},{"type":"link","label":"Node.js Database","href":"/nodejs-database.html","docId":"nodejs-database","unlisted":false}],"collapsed":true,"collapsible":true},{"type":"link","label":"Questions and Answers","href":"/questions-answers.html","docId":"questions-answers","unlisted":false},{"type":"link","label":"Contribute to RxDB","href":"/contribution.html","docId":"contribute","unlisted":false},{"type":"category","label":"\ud83c\udd95 Releases","items":[{"type":"link","label":"\ud83c\udd95 RxDB 15.0.0","href":"/releases/15.0.0.html","docId":"releases/15.0.0","unlisted":false},{"type":"link","label":"RxDB 14.0.0","href":"/releases/14.0.0.html","docId":"releases/14.0.0","unlisted":false},{"type":"link","label":"RxDB 13.0.0","href":"/releases/13.0.0.html","docId":"releases/13.0.0","unlisted":false},{"type":"link","label":"RxDB 12.0.0","href":"/releases/12.0.0.html","docId":"releases/12.0.0","unlisted":false},{"type":"link","label":"RxDB 11.0.0","href":"/releases/11.0.0.html","docId":"releases/11.0.0","unlisted":false},{"type":"link","label":"RxDB 10.0.0","href":"/releases/10.0.0.html","docId":"releases/10.0.0","unlisted":false},{"type":"link","label":"RxDB 9.0.0","href":"/releases/9.0.0.html","docId":"releases/9.0.0","unlisted":false},{"type":"link","label":"RxDB 8.0.0","href":"/releases/8.0.0.html","docId":"releases/8.0.0","unlisted":false}],"collapsed":true,"collapsible":true},{"type":"category","label":"Articles","items":[{"type":"link","label":"Local First / Offline First","href":"/offline-first.html","docId":"offline-first","unlisted":false},{"type":"link","label":"Downsides of Local First / Offline First","href":"/downsides-of-offline-first.html","docId":"downsides-of-offline-first","unlisted":false},{"type":"link","label":"Slow IndexedDB","href":"/slow-indexeddb.html","docId":"slow-indexeddb","unlisted":false},{"type":"link","label":"Why NOSQL","href":"/why-nosql.html","docId":"why-nosql","unlisted":false},{"type":"link","label":"React Native Database","href":"/react-native-database.html","docId":"react-native-database","unlisted":false},{"type":"link","label":"Alternatives for realtime offline-first JavaScript applications and local databases","href":"/alternatives.html","docId":"alternatives","unlisted":false},{"type":"link","label":"RxDB as a Database in an Angular Application","href":"/articles/angular-database.html","docId":"articles/angular-database","unlisted":false},{"type":"link","label":"The benefits of Browser Databases and RxDB","href":"/articles/browser-database.html","docId":"articles/browser-database","unlisted":false},{"type":"link","label":"Browser Storage - RxDB as a Database for Browsers","href":"/articles/browser-storage.html","docId":"articles/browser-storage","unlisted":false},{"type":"link","label":"RxDB as a data base - Empowering Web Applications with Reactive Data Handling","href":"/articles/data-base.html","docId":"articles/data-base","unlisted":false},{"type":"link","label":"Using RxDB as an Embedded Database","href":"/articles/embedded-database.html","docId":"articles/embedded-database","unlisted":false},{"type":"link","label":"RxDB as a Database in a Flutter Application","href":"/articles/flutter-database.html","docId":"articles/flutter-database","unlisted":false},{"type":"link","label":"RxDB JavaScript Frontend Database - Efficient Data Storage in Frontend Applications","href":"/articles/frontend-database.html","docId":"articles/frontend-database","unlisted":false},{"type":"link","label":"RxDB as In-memory NoSQL Database - Empowering Real-Time Applications","href":"/articles/in-memory-nosql-database.html","docId":"articles/in-memory-nosql-database","unlisted":false},{"type":"link","label":"Ionic Storage - RxDB as database for hybrid apps","href":"/articles/ionic-database.html","docId":"articles/ionic-database","unlisted":false},{"type":"link","label":"RxDB - JSON Database for JavaScript","href":"/articles/json-database.html","docId":"articles/json-database","unlisted":false},{"type":"link","label":"Using localStorage in Modern Applications - A Comprehensive Guide","href":"/articles/localstorage.html","docId":"articles/localstorage","unlisted":false},{"type":"link","label":"Mobile Database - RxDB as Database for Mobile Applications","href":"/articles/mobile-database.html","docId":"articles/mobile-database","unlisted":false},{"type":"link","label":"RxDB as a Database for Progressive Web Apps (PWA)","href":"/articles/progressive-web-app-database.html","docId":"articles/progressive-web-app-database","unlisted":false},{"type":"link","label":"RxDB as a Database for React Applications","href":"/articles/react-database.html","docId":"articles/react-database","unlisted":false},{"type":"link","label":"What is a realtime database?","href":"/articles/realtime-database.html","docId":"articles/realtime-database","unlisted":false},{"type":"link","label":"Capacitor Database","href":"/capacitor-database.html","docId":"capacitor-database","unlisted":false},{"type":"link","label":"Electron Database - Storage adapters for SQLite, Filesystem and In-Memory","href":"/electron-database.html","docId":"electron-database","unlisted":false}],"collapsed":true,"collapsible":true}]},"docs":{"adapters":{"id":"adapters","title":"PouchDB Adapters","description":"When you use PouchDB RxStorage, there are many adapters that define where the data has to be stored."},"alternatives":{"id":"alternatives","title":"Alternatives for realtime offline-first JavaScript applications and local databases","description":"Explore real-time, offline-first JS alternatives to RxDB. Compare Firebase, Meteor, AWS, CouchDB, and more for robust, seamless web/mobile app development.","sidebar":"tutorialSidebar"},"articles/angular-database":{"id":"articles/angular-database","title":"RxDB as a Database in an Angular Application","description":"Discover the RxDB Revolution for Angular Apps! \ud83d\ude80 Learn how to supercharge your web applications with RxDB\'s reactive, offline-first database capabilities. Master real-time data synchronization and build ultra-responsive Angular applications. Click now for expert tips and techniques that will elevate your development game!","sidebar":"tutorialSidebar"},"articles/browser-database":{"id":"articles/browser-database","title":"The benefits of Browser Databases and RxDB","description":"In the world of web development, efficient data management is a cornerstone of building successful and performant applications. The ability to store data directly in the browser brings numerous advantages, such as caching, offline accessibility, simplified replication of database state, and real-time application development. In this article, we will explore RxDB, a powerful browser JavaScript database, and understand why it is an excellent choice for implementing a browser database solution.","sidebar":"tutorialSidebar"},"articles/browser-storage":{"id":"articles/browser-storage","title":"Browser Storage - RxDB as a Database for Browsers","description":"Explore RxDB for browser storage its advantages, limitations, and why it outperforms SQL databases in web applications for enhanced efficiency","sidebar":"tutorialSidebar"},"articles/data-base":{"id":"articles/data-base","title":"RxDB as a data base - Empowering Web Applications with Reactive Data Handling","description":"In the world of web applications, efficient data management plays a crucial role in delivering a seamless user experience. As mobile applications continue to dominate the digital landscape, the importance of robust data bases becomes evident. In this article, we will explore RxDB as a powerful data base solution for web applications. We will delve into its features, advantages, and advanced techniques, highlighting its ability to handle reactive data and enable an offline-first approach.","sidebar":"tutorialSidebar"},"articles/embedded-database":{"id":"articles/embedded-database","title":"Using RxDB as an Embedded Database","description":"In modern UI applications, efficient data storage is a crucial aspect for seamless user experiences. One powerful solution for achieving this is by utilizing an embedded database. In this article, we will explore the concept of an embedded database and delve into the benefits of using RxDB as an embedded database in UI applications. We will also discuss why RxDB stands out as a robust choice for real-time applications with embedded database functionality.","sidebar":"tutorialSidebar"},"articles/flutter-database":{"id":"articles/flutter-database","title":"RxDB as a Database in a Flutter Application","description":"In the world of mobile application development, Flutter has gained significant popularity due to its cross-platform capabilities and rich UI framework. When it comes to building feature-rich Flutter applications, the choice of a robust and efficient database is crucial. In this article, we will explore RxDB as a database solution for Flutter applications. We\'ll delve into the core features of RxDB, its benefits over other database options, and how to integrate it into a Flutter app.","sidebar":"tutorialSidebar"},"articles/frontend-database":{"id":"articles/frontend-database","title":"RxDB JavaScript Frontend Database - Efficient Data Storage in Frontend Applications","description":"Explore RxDB as simple frontend database - Learn the benefits of offline access, caching, and improved performance in modern web apps, making RxDB a superior choice over traditional SQL databases.","sidebar":"tutorialSidebar"},"articles/in-memory-nosql-database":{"id":"articles/in-memory-nosql-database","title":"RxDB as In-memory NoSQL Database - Empowering Real-Time Applications","description":"Real-time applications have become increasingly popular in today\'s digital landscape. From instant messaging to collaborative editing tools, the demand for responsive and interactive software is on the rise. To meet these requirements, developers need powerful and efficient database solutions that can handle large amounts of data in real-time. RxDB, an javascript NoSQL database, is revolutionizing the way developers build and scale their applications by offering exceptional speed, flexibility, and scalability.","sidebar":"tutorialSidebar"},"articles/ionic-database":{"id":"articles/ionic-database","title":"Ionic Storage - RxDB as database for hybrid apps","description":"In the fast-paced world of mobile app development, hybrid applications have emerged as a versatile solution, offering the best of both worlds - the web and native app experiences. One key challenge these apps face is efficiently storing and querying data on the client\'s device. Enter RxDB, a powerful client-side database tailored for ionic hybrid applications. In this article, we\'ll explore how RxDB addresses the requirements of storing and querying data in ionic apps, and why it stands out as a preferred choice.","sidebar":"tutorialSidebar"},"articles/json-database":{"id":"articles/json-database","title":"RxDB - JSON Database for JavaScript","description":"Storing data as JSON documents in a NoSQL database is not just a trend; it\'s a practical choice. JSON data is highly compatible with various tools and is human-readable, making it an excellent fit for modern applications. JSON documents offer more flexibility compared to traditional SQL table rows, as they can contain nested data structures. This article introduces RxDB, an open-source, flexible, performant, and battle-tested NoSQL JSON database specifically designed for JavaScript applications.","sidebar":"tutorialSidebar"},"articles/localstorage":{"id":"articles/localstorage","title":"Using localStorage in Modern Applications - A Comprehensive Guide","description":"This guide explores localStorage in JavaScript web apps, detailing its usage, limitations, and alternatives like IndexedDB and AsyncStorage.","sidebar":"tutorialSidebar"},"articles/mobile-database":{"id":"articles/mobile-database","title":"Mobile Database - RxDB as Database for Mobile Applications","description":"In today\'s digital landscape, mobile applications have become an integral part of our lives. From social media platforms to e-commerce solutions, mobile apps have transformed the way we interact with digital services. At the heart of any mobile app lies the database, a critical component responsible for storing, retrieving, and managing data efficiently. In this article, we will delve into the world of mobile databases, exploring their significance, challenges, and the emergence of RxDB as a powerful database solution for hybrid app development in frameworks like React Native and Capacitor.","sidebar":"tutorialSidebar"},"articles/progressive-web-app-database":{"id":"articles/progressive-web-app-database","title":"RxDB as a Database for Progressive Web Apps (PWA)","description":"Progressive Web Apps (PWAs) have revolutionized the digital landscape, offering users an immersive blend of web and native app experiences. At the heart of every successful PWA lies effective data management, and this is where RxDB comes into play. In this article, we\'ll explore the dynamic synergy between RxDB, a robust client-side database, and Progressive Web Apps, uncovering how RxDB enhances data handling, synchronization, and overall performance, propelling PWAs into a new era of excellence.","sidebar":"tutorialSidebar"},"articles/react-database":{"id":"articles/react-database","title":"RxDB as a Database for React Applications","description":"Discover how RxDB enhances React applications by offering efficient data management, real-time updates, and offline capabilities. This article explores RxDB\'s integration with React for dynamic, responsive UIs.","sidebar":"tutorialSidebar"},"articles/realtime-database":{"id":"articles/realtime-database","title":"What is a realtime database?","description":"I have been building RxDB, a NoSQL realtime JavaScript database for many years.","sidebar":"tutorialSidebar"},"backup":{"id":"backup","title":"Backup","description":"With the backup plugin you can write the current database state and ongoing changes into folders on the filesystem.","sidebar":"tutorialSidebar"},"capacitor-database":{"id":"capacitor-database","title":"Capacitor Database","description":"Capacitor is an open source native JavaScript runtime to build Web based Native apps. You can use it to create cross-platform iOS, Android, and Progressive Web Apps with the web technologies JavaScript, HTML, and CSS.","sidebar":"tutorialSidebar"},"cleanup":{"id":"cleanup","title":"Cleanup","description":"To make the replication work, and for other reasons, RxDB has to keep deleted documents in the storage.","sidebar":"tutorialSidebar"},"contribute":{"id":"contribute","title":"Contribute to RxDB","description":"We are open to, and grateful for, any contributions made by the community.","sidebar":"tutorialSidebar"},"crdt":{"id":"crdt","title":"CRDT - Conflict-free replicated data type","description":"Explore the beta RxDB CRDT Plugin - A guide to conflict-free data handling in distributed systems with RxDB\'s novel CRDT approach","sidebar":"tutorialSidebar"},"data-migration":{"id":"data-migration","title":"data-migration","description":"This documentation page has been moved to here"},"dev-mode":{"id":"dev-mode","title":"Dev-Mode Plugin","description":"The dev-mode plugin adds many checks and validations to RxDB.","sidebar":"tutorialSidebar"},"downsides-of-offline-first":{"id":"downsides-of-offline-first","title":"Downsides of Local First / Offline First","description":"So you have read all these things about how the local-first (aka offline-first) paradigm makes it easy to create realtime web applications that even work when the user has no internet connection.","sidebar":"tutorialSidebar"},"electron":{"id":"electron","title":"Electron Plugin","description":"RxStorage Electron IpcRenderer & IpcMain","sidebar":"tutorialSidebar"},"electron-database":{"id":"electron-database","title":"Electron Database - Storage adapters for SQLite, Filesystem and In-Memory","description":"SQLite, Filesystem, and In-Memory storage with RxDB for creating robust local-first Electron apps. Perfect for complex, real-time client-side applications","sidebar":"tutorialSidebar"},"encryption":{"id":"encryption","title":"Encryption","description":"Explore RxDB\'s \ud83d\udd12 encryption plugin for enhanced data security in web and native apps, featuring password-based encryption and secure storage.","sidebar":"tutorialSidebar"},"install":{"id":"install","title":"Installation","description":"npm","sidebar":"tutorialSidebar"},"key-compression":{"id":"key-compression","title":"Key Compression","description":"With the key compression plugin, documents will be stored in a compressed format which saves up to 40% disc space.","sidebar":"tutorialSidebar"},"leader-election":{"id":"leader-election","title":"Leader Election","description":"RxDB comes with a leader-election which elects a leading instance between different instances in the same javascript runtime.","sidebar":"tutorialSidebar"},"logger":{"id":"logger","title":"Logger \ud83d\udc51","description":"With the logger plugin you can log all operations to the storage layer of your RxDatabase.","sidebar":"tutorialSidebar"},"middleware":{"id":"middleware","title":"Middleware","description":"RxDB supports middleware-hooks like mongoose.","sidebar":"tutorialSidebar"},"migration-schema":{"id":"migration-schema","title":"Migration Schema","description":"The RxDB Data Migration Plugin helps developers easily update stored data in their apps when they make changes to the data structure by changing the schema of a RxCollection. This is useful when developers release a new version of the app with a different schema.","sidebar":"tutorialSidebar"},"migration-storage":{"id":"migration-storage","title":"Migration Storage","description":"The storage migration plugin can be used to migrate all data from one existing RxStorage into another. This is useful when:","sidebar":"tutorialSidebar"},"nodejs-database":{"id":"nodejs-database","title":"Node.js Database","description":"RxDB is a fast, reactive realtime NoSQL database made for JavaScript applications like Websites, hybrid Apps, Electron-Apps, Progressive Web Apps and Node.js. While RxDB was initially created to be used with UI applications, it has been matured and optimized to make it useful for pure server-side use cases. It can be used as embedded, local database inside of the Node.js JavaScript process, or it can be used similar to a database server that Node.js can connect to. The RxStorage layer makes it possible to switch out the underlying storage engine which makes RxDB a very flexible database that can be optimized for many scenarios.","sidebar":"tutorialSidebar"},"nosql-performance-tips":{"id":"nosql-performance-tips","title":"RxDB NoSQL Performance Tips","description":"Enhance your NoSQL database performance with RxDB creator\'s tips on bulk operations, query optimization, and efficient use of hooks and plugins, perfect for developers looking to improve speed and efficiency","sidebar":"tutorialSidebar"},"offline-first":{"id":"offline-first","title":"Local First / Offline First","description":"Local-First software stores data on client devices for seamless offline and online functionality, enhancing user experience and efficiency.","sidebar":"tutorialSidebar"},"orm":{"id":"orm","title":"ORM","description":"Like mongoose, RxDB has ORM-capabilities which can be used to add specific behavior to documents and collections.","sidebar":"tutorialSidebar"},"plugins":{"id":"plugins","title":"Plugins","description":"Creating your own plugin is very simple. A plugin is basically a javascript-object which overwrites or extends RxDB\'s internal classes, prototypes, and hooks.","sidebar":"tutorialSidebar"},"population":{"id":"population","title":"Population","description":"There are no joins in RxDB but sometimes we still want references to documents in other collections. This is where population comes in. You can specify a relation from one RxDocument to another RxDocument in the same or another RxCollection of the same database.","sidebar":"tutorialSidebar"},"query-cache":{"id":"query-cache","title":"Query Cache","description":"RxDB uses a QueryCache which optimizes the reuse of queries at runtime. This makes sense especially when RxDB is used in UI-applications where people move for- and backwards on different routes or pages and the same queries are used many times. Because of the event-reduce algorithm cached queries are even valuable for optimization, when changes to the database occur between now and the last execution.","sidebar":"tutorialSidebar"},"query-optimizer":{"id":"query-optimizer","title":"Query Optimizer \ud83d\udc51","description":"The query optimizer can be used to determine which index is the best to use for a given query.","sidebar":"tutorialSidebar"},"questions-answers":{"id":"questions-answers","title":"Questions and Answers","description":"Can\'t change the schema of a collection","sidebar":"tutorialSidebar"},"quickstart":{"id":"quickstart","title":"\ud83d\ude80 Quickstart","description":"Welcome to the RxDB Quickstart. Here we\'ll create a simple realtime TODO-app with RxDB to demonstrate the basic concepts.","sidebar":"tutorialSidebar"},"react-native-database":{"id":"react-native-database","title":"React Native Database","description":"Explore React Native database solutions for cross-platform apps - AsyncStorage, SQLite, RxDB, and more. Tailored for iOS, Android, and Windows, ensuring seamless data storage and sync.","sidebar":"tutorialSidebar"},"releases/10.0.0":{"id":"releases/10.0.0","title":"RxDB 10.0.0","description":"RxDB Major Release 10.0.0","sidebar":"tutorialSidebar"},"releases/11.0.0":{"id":"releases/11.0.0","title":"RxDB 11.0.0","description":"RxDB Major Release 11.0.0","sidebar":"tutorialSidebar"},"releases/12.0.0":{"id":"releases/12.0.0","title":"RxDB 12.0.0","description":"RxDB Major Release 12.0.0","sidebar":"tutorialSidebar"},"releases/13.0.0":{"id":"releases/13.0.0","title":"RxDB 13.0.0","description":"RxDB Major Release 13.0.0","sidebar":"tutorialSidebar"},"releases/14.0.0":{"id":"releases/14.0.0","title":"RxDB 14.0.0","description":"RxDB Major Release 14.0.0","sidebar":"tutorialSidebar"},"releases/15.0.0":{"id":"releases/15.0.0","title":"\ud83c\udd95 RxDB 15.0.0","description":"RxDB Major Release 15.0.0","sidebar":"tutorialSidebar"},"releases/8.0.0":{"id":"releases/8.0.0","title":"RxDB 8.0.0","description":"RxDB Major Release 8.0.0","sidebar":"tutorialSidebar"},"releases/9.0.0":{"id":"releases/9.0.0","title":"RxDB 9.0.0","description":"RxDB Major Release 9.0.0","sidebar":"tutorialSidebar"},"replication":{"id":"replication","title":"\u2699\ufe0f Replication Protocol","description":"The RxDB replication protocol provides the ability to replicate the database state in realtime between the clients and the server.","sidebar":"tutorialSidebar"},"replication-couchdb":{"id":"replication-couchdb","title":"CouchDB Replication","description":"A plugin to replicate between a RxCollection and a CouchDB server.","sidebar":"tutorialSidebar"},"replication-firestore":{"id":"replication-firestore","title":"Firestore Replication","description":"With the replication-firestore plugin you can do a two-way realtime replication","sidebar":"tutorialSidebar"},"replication-graphql":{"id":"replication-graphql","title":"GraphQL Replication","description":"The GraphQL replication provides handlers for GraphQL to run replication with GraphQL as the transportation layer.","sidebar":"tutorialSidebar"},"replication-http":{"id":"replication-http","title":"HTTP Replication","description":"Learn how to establish HTTP replication between RxDB clients and a Node.js Express server for data synchronization.","sidebar":"tutorialSidebar"},"replication-nats":{"id":"replication-nats","title":"NATS Replication","description":"With this RxDB plugin you can run a two-way realtime replication with a NATS server.","sidebar":"tutorialSidebar"},"replication-p2p":{"id":"replication-p2p","title":"P2P Replication","description":"The new documentation page has been moved to here"},"replication-webrtc":{"id":"replication-webrtc","title":"WebRTC Replication","description":"In the world of web and mobile development, data synchronization between clients and servers has always been a critical aspect of building real-time JavaScript applications.","sidebar":"tutorialSidebar"},"replication-websocket":{"id":"replication-websocket","title":"Websocket Replication","description":"With the websocket replication plugin, you can spawn a websocket server from a RxDB database in Node.js and replicate with it.","sidebar":"tutorialSidebar"},"rx-attachment":{"id":"rx-attachment","title":"Attachments","description":"Attachments are binary data files that can be attachment to an RxDocument, like a file that is attached to an email.","sidebar":"tutorialSidebar"},"rx-collection":{"id":"rx-collection","title":"RxCollection","description":"A collection stores documents of the same type.","sidebar":"tutorialSidebar"},"rx-database":{"id":"rx-database","title":"RxDatabase","description":"A RxDatabase-Object contains your collections and handles the synchronization of change-events.","sidebar":"tutorialSidebar"},"rx-document":{"id":"rx-document","title":"RxDocument","description":"A document is a single object which is stored in a collection. It can be compared to a single record in a relational database table. You get an RxDocument either as return on inserts, or as result-set of queries.","sidebar":"tutorialSidebar"},"rx-local-document":{"id":"rx-local-document","title":"Local Documents","description":"Local documents are a special class of documents which are used to store local metadata.","sidebar":"tutorialSidebar"},"rx-query":{"id":"rx-query","title":"RxQuery","description":"A query allows to find documents in your collection.","sidebar":"tutorialSidebar"},"rx-schema":{"id":"rx-schema","title":"RxSchema","description":"Schemas define the structure of the documents of a collection. Which field should be used as primary, which fields should be used as indexes and what should be encrypted. Every collection has its own schema. With RxDB, schemas are defined with the jsonschema-standard which you might know from other projects.","sidebar":"tutorialSidebar"},"rx-storage":{"id":"rx-storage","title":"\u2699\ufe0f Rxstorage Layer","description":"RxDB is not a self contained database. Instead the data is stored in an implementation of the RxStorage interface. This allows you to switch out the underlying data layer, depending on the JavaScript environment and performance requirements. For example you can use the SQLite storage for a capacitor app or you can use the Dexie.js RxStorage to store data in IndexedDB in a browser based application. There are also storages for other JavaScript runtimes like Node.js, React-Native, NativeScript and more.","sidebar":"tutorialSidebar"},"rx-storage-denokv":{"id":"rx-storage-denokv","title":"DenoKV RxStorage","description":"With the DenoKV RxStorage layer for RxDB, you can run a fully featured NoSQL database on top of the DenoKV API.","sidebar":"tutorialSidebar"},"rx-storage-dexie":{"id":"rx-storage-dexie","title":"Dexie.js RxStorage","description":"To store the data inside of IndexedDB in the browser, you can also use the Dexie.js RxStorage.","sidebar":"tutorialSidebar"},"rx-storage-filesystem-node":{"id":"rx-storage-filesystem-node","title":"Node.js Filesystem RxStorage \ud83d\udc51","description":"The Filesystem Node RxStorage for RxDB is built on top of the Node.js Filesystem API.","sidebar":"tutorialSidebar"},"rx-storage-foundationdb":{"id":"rx-storage-foundationdb","title":"FoundationDB RxStorage","description":"Explore the advanced features of RxDB with FoundationDB RxStorage - Efficient indexing, complex NoSQL queries, real-time updates, data compression, and attachment management for optimized database performance and scalability","sidebar":"tutorialSidebar"},"rx-storage-indexeddb":{"id":"rx-storage-indexeddb","title":"IndexedDB RxStorage \ud83d\udc51","description":"The IndexedDB RxStorage is based on plain IndexedDB and can be used in browsers, electron or hybrid apps.","sidebar":"tutorialSidebar"},"rx-storage-localstorage-meta-optimizer":{"id":"rx-storage-localstorage-meta-optimizer","title":"RxStorage Localstorage Meta Optimizer \ud83d\udc51","description":"The RxStorage Localstorage Meta Optimizer is a wrapper around any other RxStorage. The wrapper uses the original RxStorage for normal collection documents. But to optimize the initial page load time, it uses localstorage to store the plain key-value metadata that RxDB needs to create databases and collections. This plugin can only be used in browsers.","sidebar":"tutorialSidebar"},"rx-storage-lokijs":{"id":"rx-storage-lokijs","title":"LokiJS RxStorage","description":"The LokiJS RxStorage is based on LokiJS which has the main benefit of having a better performance. It can do this because it is an in-memory database that processes all data in memory and only saves to disc when the app is closed or an interval is reached.","sidebar":"tutorialSidebar"},"rx-storage-memory":{"id":"rx-storage-memory","title":"Memory RxStorage","description":"\x3c!-- keywords:","sidebar":"tutorialSidebar"},"rx-storage-memory-synced":{"id":"rx-storage-memory-synced","title":"Memory Synced RxStorage \ud83d\udc51","description":"The memory synced RxStorage is a wrapper around any other RxStorage. The wrapper creates an in-memory storage that is used for query and write operations. This memory instance is replicated with the underlying storage for persistence.","sidebar":"tutorialSidebar"},"rx-storage-mongodb":{"id":"rx-storage-mongodb","title":"MongoDB RxStorage","description":"RxDB MongoDB RxStorage is an RxDB RxStorage that allows you to use MongoDB as the underlying storage engine for your RxDB database. With this you can take advantage of MongoDB\'s features and scalability while benefiting from RxDB\'s real-time data synchronization capabilities.","sidebar":"tutorialSidebar"},"rx-storage-opfs":{"id":"rx-storage-opfs","title":"OPFS RxStorage \ud83d\udc51","description":"Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage","sidebar":"tutorialSidebar"},"rx-storage-performance":{"id":"rx-storage-performance","title":"\ud83d\udcc8 RxStorage Performance","description":"RxStorage Performance comparison","sidebar":"tutorialSidebar"},"rx-storage-pouchdb":{"id":"rx-storage-pouchdb","title":"PouchDB RxStorage","description":"The PouchDB RxStorage is based on the PouchDB database. It is the most battle proven RxStorage and has a big ecosystem of adapters. PouchDB does a lot of overhead to enable CouchDB replication which makes the PouchDB RxStorage one of the slowest."},"rx-storage-remote":{"id":"rx-storage-remote","title":"Remote RxStorage","description":"The Remote RxStorage is made to use a remote storage and communicate with it over an asynchronous message channel.","sidebar":"tutorialSidebar"},"rx-storage-sharding":{"id":"rx-storage-sharding","title":"Sharding RxStorage \ud83d\udc51","description":"With the sharding plugin, you can improve the write and query times of some RxStorage implementations.","sidebar":"tutorialSidebar"},"rx-storage-shared-worker":{"id":"rx-storage-shared-worker","title":"SharedWorker RxStorage \ud83d\udc51","description":"The SharedWorker RxStorage uses the SharedWorker API to run the storage inside of a separate JavaScript process in browsers. Compared to a normal WebWorker, the SharedWorker is created exactly once, even when there are multiple browser tabs opened. Because of having exactly one worker, multiple performance optimizations can be done because the storage itself does not have to handle multiple opened database connections.","sidebar":"tutorialSidebar"},"rx-storage-sqlite":{"id":"rx-storage-sqlite","title":"SQLite RxStorage \ud83d\udc51","description":"This RxStorage is based on SQLite and is made to work with Node.js, Electron, React Native and Capacitor.","sidebar":"tutorialSidebar"},"rx-storage-worker":{"id":"rx-storage-worker","title":"Worker RxStorage \ud83d\udc51","description":"With the worker plugin, you can put the RxStorage of your database inside of a WebWorker (in browsers) or a Worker Thread (in node.js). By doing so, you can take CPU load from the main process and move it into the worker\'s process which can improve the perceived performance of your application. Notice that for browsers, it is recommend to use the SharedWorker instead to get a better performance.","sidebar":"tutorialSidebar"},"rxdb-tradeoffs":{"id":"rxdb-tradeoffs","title":"RxDB Tradeoffs","description":"RxDB is client-side, offline first Database for JavaScript applications."},"schema-validation":{"id":"schema-validation","title":"Schema Validation","description":"RxDB has multiple validation implementations that can be used to ensure that your document data is always matching the provided JSON"},"slow-indexeddb":{"id":"slow-indexeddb","title":"Slow IndexedDB","description":"So you have a JavaScript web application that needs to store data at the client side, either to make it offline usable, just for caching purposes or for other reasons.","sidebar":"tutorialSidebar"},"third-party-plugins":{"id":"third-party-plugins","title":"Third Party Plugins","description":"* rxdb-hooks A set of hooks to integrate RxDB into react applications.","sidebar":"tutorialSidebar"},"transactions-conflicts-revisions":{"id":"transactions-conflicts-revisions","title":"Transactions, Conflicts and Revisions","description":"In contrast to most SQL databases, RxDB does not have the concept of relational, ACID transactions. Instead, RxDB has to apply different techniques that better suit the offline-first, client side world where it is not possible to create a transaction between multiple maybe-offline client devices.","sidebar":"tutorialSidebar"},"tutorials/typescript":{"id":"tutorials/typescript","title":"RxDB TypeScript Tutorial","description":"In this tutorial you will learn how to use RxDB with TypeScript.","sidebar":"tutorialSidebar"},"why-nosql":{"id":"why-nosql","title":"Why NOSQL","description":"RxDB, a client side, offline first, JavaScript database, is now several years old.","sidebar":"tutorialSidebar"}}}')}}]); \ No newline at end of file +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[53],{1109:e=>{e.exports=JSON.parse('{"pluginId":"default","version":"current","label":"Next","banner":null,"badge":false,"noIndex":false,"className":"docs-version-current","isLast":true,"docsSidebars":{"tutorialSidebar":[{"type":"link","label":"\ud83d\ude80 Quickstart","href":"/quickstart.html","docId":"quickstart","unlisted":false},{"type":"link","label":"Installation","href":"/install.html","docId":"install","unlisted":false},{"type":"link","label":"Dev-Mode Plugin","href":"/dev-mode.html","docId":"dev-mode","unlisted":false},{"type":"link","label":"RxDatabase","href":"/rx-database.html","docId":"rx-database","unlisted":false},{"type":"link","label":"RxSchema","href":"/rx-schema.html","docId":"rx-schema","unlisted":false},{"type":"link","label":"RxCollection","href":"/rx-collection.html","docId":"rx-collection","unlisted":false},{"type":"link","label":"RxDocument","href":"/rx-document.html","docId":"rx-document","unlisted":false},{"type":"link","label":"RxQuery","href":"/rx-query.html","docId":"rx-query","unlisted":false},{"type":"link","label":"Attachments","href":"/rx-attachment.html","docId":"rx-attachment","unlisted":false},{"type":"category","label":"\ud83d\udcbe RxStorage","items":[{"type":"link","label":"\u2699\ufe0f Rxstorage Layer","href":"/rx-storage.html","docId":"rx-storage","unlisted":false},{"type":"link","label":"\ud83d\udcc8 RxStorage Performance","href":"/rx-storage-performance.html","docId":"rx-storage-performance","unlisted":false},{"type":"link","label":"Dexie.js RxStorage","href":"/rx-storage-dexie.html","docId":"rx-storage-dexie","unlisted":false},{"type":"link","label":"LokiJS RxStorage","href":"/rx-storage-lokijs.html","docId":"rx-storage-lokijs","unlisted":false},{"type":"link","label":"Memory RxStorage","href":"/rx-storage-memory.html","docId":"rx-storage-memory","unlisted":false},{"type":"link","label":"IndexedDB RxStorage \ud83d\udc51","href":"/rx-storage-indexeddb.html","docId":"rx-storage-indexeddb","unlisted":false},{"type":"link","label":"OPFS RxStorage \ud83d\udc51","href":"/rx-storage-opfs.html","docId":"rx-storage-opfs","unlisted":false},{"type":"link","label":"SQLite RxStorage \ud83d\udc51","href":"/rx-storage-sqlite.html","docId":"rx-storage-sqlite","unlisted":false},{"type":"link","label":"Node.js Filesystem RxStorage \ud83d\udc51","href":"/rx-storage-filesystem-node.html","docId":"rx-storage-filesystem-node","unlisted":false},{"type":"link","label":"MongoDB RxStorage","href":"/rx-storage-mongodb.html","docId":"rx-storage-mongodb","unlisted":false},{"type":"link","label":"DenoKV RxStorage","href":"/rx-storage-denokv.html","docId":"rx-storage-denokv","unlisted":false},{"type":"link","label":"FoundationDB RxStorage","href":"/rx-storage-foundationdb.html","docId":"rx-storage-foundationdb","unlisted":false},{"type":"link","label":"Remote RxStorage","href":"/rx-storage-remote.html","docId":"rx-storage-remote","unlisted":false},{"type":"link","label":"Worker RxStorage \ud83d\udc51","href":"/rx-storage-worker.html","docId":"rx-storage-worker","unlisted":false},{"type":"link","label":"SharedWorker RxStorage \ud83d\udc51","href":"/rx-storage-shared-worker.html","docId":"rx-storage-shared-worker","unlisted":false},{"type":"link","label":"Memory Synced RxStorage \ud83d\udc51","href":"/rx-storage-memory-synced.html","docId":"rx-storage-memory-synced","unlisted":false},{"type":"link","label":"Sharding RxStorage \ud83d\udc51","href":"/rx-storage-sharding.html","docId":"rx-storage-sharding","unlisted":false},{"type":"link","label":"RxStorage Localstorage Meta Optimizer \ud83d\udc51","href":"/rx-storage-localstorage-meta-optimizer.html","docId":"rx-storage-localstorage-meta-optimizer","unlisted":false},{"type":"link","label":"Electron Plugin","href":"/electron.html","docId":"electron","unlisted":false}],"collapsed":true,"collapsible":true},{"type":"category","label":"\ud83d\udd04 Replication","items":[{"type":"link","label":"\u2699\ufe0f Replication Protocol","href":"/replication.html","docId":"replication","unlisted":false},{"type":"link","label":"HTTP Replication","href":"/replication-http.html","docId":"replication-http","unlisted":false},{"type":"link","label":"GraphQL Replication","href":"/replication-graphql.html","docId":"replication-graphql","unlisted":false},{"type":"link","label":"Websocket Replication","href":"/replication-websocket.html","docId":"replication-websocket","unlisted":false},{"type":"link","label":"CouchDB Replication","href":"/replication-couchdb.html","docId":"replication-couchdb","unlisted":false},{"type":"link","label":"WebRTC Replication","href":"/replication-webrtc.html","docId":"replication-webrtc","unlisted":false},{"type":"link","label":"Firestore Replication","href":"/replication-firestore.html","docId":"replication-firestore","unlisted":false},{"type":"link","label":"NATS Replication","href":"/replication-nats.html","docId":"replication-nats","unlisted":false}],"collapsed":true,"collapsible":true},{"type":"category","label":"Migration","items":[{"type":"link","label":"Migration Schema","href":"/migration-schema.html","docId":"migration-schema","unlisted":false},{"type":"link","label":"Migration Storage","href":"/migration-storage.html","docId":"migration-storage","unlisted":false}],"collapsed":true,"collapsible":true},{"type":"link","label":"Encryption","href":"/encryption.html","docId":"encryption","unlisted":false},{"type":"link","label":"Key Compression","href":"/key-compression.html","docId":"key-compression","unlisted":false},{"type":"link","label":"Local Documents","href":"/rx-local-document.html","docId":"rx-local-document","unlisted":false},{"type":"link","label":"Leader Election","href":"/leader-election.html","docId":"leader-election","unlisted":false},{"type":"link","label":"Cleanup","href":"/cleanup.html","docId":"cleanup","unlisted":false},{"type":"link","label":"Backup","href":"/backup.html","docId":"backup","unlisted":false},{"type":"link","label":"Transactions, Conflicts and Revisions","href":"/transactions-conflicts-revisions.html","docId":"transactions-conflicts-revisions","unlisted":false},{"type":"link","label":"Middleware","href":"/middleware.html","docId":"middleware","unlisted":false},{"type":"link","label":"Query Cache","href":"/query-cache.html","docId":"query-cache","unlisted":false},{"type":"link","label":"CRDT - Conflict-free replicated data type","href":"/crdt.html","docId":"crdt","unlisted":false},{"type":"link","label":"Population","href":"/population.html","docId":"population","unlisted":false},{"type":"link","label":"ORM","href":"/orm.html","docId":"orm","unlisted":false},{"type":"link","label":"Query Optimizer \ud83d\udc51","href":"/query-optimizer.html","docId":"query-optimizer","unlisted":false},{"type":"link","label":"Logger \ud83d\udc51","href":"/logger.html","docId":"logger","unlisted":false},{"type":"link","label":"Plugins","href":"/plugins.html","docId":"plugins","unlisted":false},{"type":"link","label":"RxDB NoSQL Performance Tips","href":"/nosql-performance-tips.html","docId":"nosql-performance-tips","unlisted":false},{"type":"link","label":"Third Party Plugins","href":"/third-party-plugins.html","docId":"third-party-plugins","unlisted":false},{"type":"category","label":"Tutorials","items":[{"type":"link","label":"RxDB TypeScript Tutorial","href":"/tutorials/typescript.html","docId":"tutorials/typescript","unlisted":false},{"type":"link","label":"Node.js Database","href":"/nodejs-database.html","docId":"nodejs-database","unlisted":false}],"collapsed":true,"collapsible":true},{"type":"link","label":"Questions and Answers","href":"/questions-answers.html","docId":"questions-answers","unlisted":false},{"type":"link","label":"Contribute to RxDB","href":"/contribution.html","docId":"contribute","unlisted":false},{"type":"category","label":"\ud83c\udd95 Releases","items":[{"type":"link","label":"\ud83c\udd95 RxDB 15.0.0","href":"/releases/15.0.0.html","docId":"releases/15.0.0","unlisted":false},{"type":"link","label":"RxDB 14.0.0","href":"/releases/14.0.0.html","docId":"releases/14.0.0","unlisted":false},{"type":"link","label":"RxDB 13.0.0","href":"/releases/13.0.0.html","docId":"releases/13.0.0","unlisted":false},{"type":"link","label":"RxDB 12.0.0","href":"/releases/12.0.0.html","docId":"releases/12.0.0","unlisted":false},{"type":"link","label":"RxDB 11.0.0","href":"/releases/11.0.0.html","docId":"releases/11.0.0","unlisted":false},{"type":"link","label":"RxDB 10.0.0","href":"/releases/10.0.0.html","docId":"releases/10.0.0","unlisted":false},{"type":"link","label":"RxDB 9.0.0","href":"/releases/9.0.0.html","docId":"releases/9.0.0","unlisted":false},{"type":"link","label":"RxDB 8.0.0","href":"/releases/8.0.0.html","docId":"releases/8.0.0","unlisted":false}],"collapsed":true,"collapsible":true},{"type":"category","label":"Articles","items":[{"type":"link","label":"Local First / Offline First","href":"/offline-first.html","docId":"offline-first","unlisted":false},{"type":"link","label":"Downsides of Local First / Offline First","href":"/downsides-of-offline-first.html","docId":"downsides-of-offline-first","unlisted":false},{"type":"link","label":"Slow IndexedDB","href":"/slow-indexeddb.html","docId":"slow-indexeddb","unlisted":false},{"type":"link","label":"Why NOSQL","href":"/why-nosql.html","docId":"why-nosql","unlisted":false},{"type":"link","label":"React Native Database","href":"/react-native-database.html","docId":"react-native-database","unlisted":false},{"type":"link","label":"Alternatives for realtime offline-first JavaScript applications and local databases","href":"/alternatives.html","docId":"alternatives","unlisted":false},{"type":"link","label":"RxDB as a Database in an Angular Application","href":"/articles/angular-database.html","docId":"articles/angular-database","unlisted":false},{"type":"link","label":"The benefits of Browser Databases and RxDB","href":"/articles/browser-database.html","docId":"articles/browser-database","unlisted":false},{"type":"link","label":"Browser Storage - RxDB as a Database for Browsers","href":"/articles/browser-storage.html","docId":"articles/browser-storage","unlisted":false},{"type":"link","label":"RxDB as a data base - Empowering Web Applications with Reactive Data Handling","href":"/articles/data-base.html","docId":"articles/data-base","unlisted":false},{"type":"link","label":"Using RxDB as an Embedded Database","href":"/articles/embedded-database.html","docId":"articles/embedded-database","unlisted":false},{"type":"link","label":"RxDB as a Database in a Flutter Application","href":"/articles/flutter-database.html","docId":"articles/flutter-database","unlisted":false},{"type":"link","label":"RxDB JavaScript Frontend Database - Efficient Data Storage in Frontend Applications","href":"/articles/frontend-database.html","docId":"articles/frontend-database","unlisted":false},{"type":"link","label":"RxDB as In-memory NoSQL Database - Empowering Real-Time Applications","href":"/articles/in-memory-nosql-database.html","docId":"articles/in-memory-nosql-database","unlisted":false},{"type":"link","label":"Ionic Storage - RxDB as database for hybrid apps","href":"/articles/ionic-database.html","docId":"articles/ionic-database","unlisted":false},{"type":"link","label":"RxDB - JSON Database for JavaScript","href":"/articles/json-database.html","docId":"articles/json-database","unlisted":false},{"type":"link","label":"Using localStorage in Modern Applications - A Comprehensive Guide","href":"/articles/localstorage.html","docId":"articles/localstorage","unlisted":false},{"type":"link","label":"Mobile Database - RxDB as Database for Mobile Applications","href":"/articles/mobile-database.html","docId":"articles/mobile-database","unlisted":false},{"type":"link","label":"RxDB as a Database for Progressive Web Apps (PWA)","href":"/articles/progressive-web-app-database.html","docId":"articles/progressive-web-app-database","unlisted":false},{"type":"link","label":"RxDB as a Database for React Applications","href":"/articles/react-database.html","docId":"articles/react-database","unlisted":false},{"type":"link","label":"What is a realtime database?","href":"/articles/realtime-database.html","docId":"articles/realtime-database","unlisted":false},{"type":"link","label":"Capacitor Database","href":"/capacitor-database.html","docId":"capacitor-database","unlisted":false},{"type":"link","label":"Electron Database - Storage adapters for SQLite, Filesystem and In-Memory","href":"/electron-database.html","docId":"electron-database","unlisted":false}],"collapsed":true,"collapsible":true}]},"docs":{"adapters":{"id":"adapters","title":"PouchDB Adapters","description":"When you use PouchDB RxStorage, there are many adapters that define where the data has to be stored."},"alternatives":{"id":"alternatives","title":"Alternatives for realtime offline-first JavaScript applications and local databases","description":"Explore real-time, offline-first JS alternatives to RxDB. Compare Firebase, Meteor, AWS, CouchDB, and more for robust, seamless web/mobile app development.","sidebar":"tutorialSidebar"},"articles/angular-database":{"id":"articles/angular-database","title":"RxDB as a Database in an Angular Application","description":"Discover the RxDB Revolution for Angular Apps! \ud83d\ude80 Learn how to supercharge your web applications with RxDB\'s reactive, offline-first database capabilities. Master real-time data synchronization and build ultra-responsive Angular applications. Click now for expert tips and techniques that will elevate your development game!","sidebar":"tutorialSidebar"},"articles/browser-database":{"id":"articles/browser-database","title":"The benefits of Browser Databases and RxDB","description":"In the world of web development, efficient data management is a cornerstone of building successful and performant applications. The ability to store data directly in the browser brings numerous advantages, such as caching, offline accessibility, simplified replication of database state, and real-time application development. In this article, we will explore RxDB, a powerful browser JavaScript database, and understand why it is an excellent choice for implementing a browser database solution.","sidebar":"tutorialSidebar"},"articles/browser-storage":{"id":"articles/browser-storage","title":"Browser Storage - RxDB as a Database for Browsers","description":"Explore RxDB for browser storage its advantages, limitations, and why it outperforms SQL databases in web applications for enhanced efficiency","sidebar":"tutorialSidebar"},"articles/data-base":{"id":"articles/data-base","title":"RxDB as a data base - Empowering Web Applications with Reactive Data Handling","description":"In the world of web applications, efficient data management plays a crucial role in delivering a seamless user experience. As mobile applications continue to dominate the digital landscape, the importance of robust data bases becomes evident. In this article, we will explore RxDB as a powerful data base solution for web applications. We will delve into its features, advantages, and advanced techniques, highlighting its ability to handle reactive data and enable an offline-first approach.","sidebar":"tutorialSidebar"},"articles/embedded-database":{"id":"articles/embedded-database","title":"Using RxDB as an Embedded Database","description":"In modern UI applications, efficient data storage is a crucial aspect for seamless user experiences. One powerful solution for achieving this is by utilizing an embedded database. In this article, we will explore the concept of an embedded database and delve into the benefits of using RxDB as an embedded database in UI applications. We will also discuss why RxDB stands out as a robust choice for real-time applications with embedded database functionality.","sidebar":"tutorialSidebar"},"articles/flutter-database":{"id":"articles/flutter-database","title":"RxDB as a Database in a Flutter Application","description":"In the world of mobile application development, Flutter has gained significant popularity due to its cross-platform capabilities and rich UI framework. When it comes to building feature-rich Flutter applications, the choice of a robust and efficient database is crucial. In this article, we will explore RxDB as a database solution for Flutter applications. We\'ll delve into the core features of RxDB, its benefits over other database options, and how to integrate it into a Flutter app.","sidebar":"tutorialSidebar"},"articles/frontend-database":{"id":"articles/frontend-database","title":"RxDB JavaScript Frontend Database - Efficient Data Storage in Frontend Applications","description":"Explore RxDB as simple frontend database - Learn the benefits of offline access, caching, and improved performance in modern web apps, making RxDB a superior choice over traditional SQL databases.","sidebar":"tutorialSidebar"},"articles/in-memory-nosql-database":{"id":"articles/in-memory-nosql-database","title":"RxDB as In-memory NoSQL Database - Empowering Real-Time Applications","description":"Real-time applications have become increasingly popular in today\'s digital landscape. From instant messaging to collaborative editing tools, the demand for responsive and interactive software is on the rise. To meet these requirements, developers need powerful and efficient database solutions that can handle large amounts of data in real-time. RxDB, an javascript NoSQL database, is revolutionizing the way developers build and scale their applications by offering exceptional speed, flexibility, and scalability.","sidebar":"tutorialSidebar"},"articles/ionic-database":{"id":"articles/ionic-database","title":"Ionic Storage - RxDB as database for hybrid apps","description":"In the fast-paced world of mobile app development, hybrid applications have emerged as a versatile solution, offering the best of both worlds - the web and native app experiences. One key challenge these apps face is efficiently storing and querying data on the client\'s device. Enter RxDB, a powerful client-side database tailored for ionic hybrid applications. In this article, we\'ll explore how RxDB addresses the requirements of storing and querying data in ionic apps, and why it stands out as a preferred choice.","sidebar":"tutorialSidebar"},"articles/json-database":{"id":"articles/json-database","title":"RxDB - JSON Database for JavaScript","description":"Storing data as JSON documents in a NoSQL database is not just a trend; it\'s a practical choice. JSON data is highly compatible with various tools and is human-readable, making it an excellent fit for modern applications. JSON documents offer more flexibility compared to traditional SQL table rows, as they can contain nested data structures. This article introduces RxDB, an open-source, flexible, performant, and battle-tested NoSQL JSON database specifically designed for JavaScript applications.","sidebar":"tutorialSidebar"},"articles/localstorage":{"id":"articles/localstorage","title":"Using localStorage in Modern Applications - A Comprehensive Guide","description":"This guide explores localStorage in JavaScript web apps, detailing its usage, limitations, and alternatives like IndexedDB and AsyncStorage.","sidebar":"tutorialSidebar"},"articles/mobile-database":{"id":"articles/mobile-database","title":"Mobile Database - RxDB as Database for Mobile Applications","description":"In today\'s digital landscape, mobile applications have become an integral part of our lives. From social media platforms to e-commerce solutions, mobile apps have transformed the way we interact with digital services. At the heart of any mobile app lies the database, a critical component responsible for storing, retrieving, and managing data efficiently. In this article, we will delve into the world of mobile databases, exploring their significance, challenges, and the emergence of RxDB as a powerful database solution for hybrid app development in frameworks like React Native and Capacitor.","sidebar":"tutorialSidebar"},"articles/progressive-web-app-database":{"id":"articles/progressive-web-app-database","title":"RxDB as a Database for Progressive Web Apps (PWA)","description":"Progressive Web Apps (PWAs) have revolutionized the digital landscape, offering users an immersive blend of web and native app experiences. At the heart of every successful PWA lies effective data management, and this is where RxDB comes into play. In this article, we\'ll explore the dynamic synergy between RxDB, a robust client-side database, and Progressive Web Apps, uncovering how RxDB enhances data handling, synchronization, and overall performance, propelling PWAs into a new era of excellence.","sidebar":"tutorialSidebar"},"articles/react-database":{"id":"articles/react-database","title":"RxDB as a Database for React Applications","description":"Discover how RxDB enhances React applications by offering efficient data management, real-time updates, and offline capabilities. This article explores RxDB\'s integration with React for dynamic, responsive UIs.","sidebar":"tutorialSidebar"},"articles/realtime-database":{"id":"articles/realtime-database","title":"What is a realtime database?","description":"I have been building RxDB, a NoSQL realtime JavaScript database for many years.","sidebar":"tutorialSidebar"},"backup":{"id":"backup","title":"Backup","description":"With the backup plugin you can write the current database state and ongoing changes into folders on the filesystem.","sidebar":"tutorialSidebar"},"capacitor-database":{"id":"capacitor-database","title":"Capacitor Database","description":"Capacitor is an open source native JavaScript runtime to build Web based Native apps. You can use it to create cross-platform iOS, Android, and Progressive Web Apps with the web technologies JavaScript, HTML, and CSS.","sidebar":"tutorialSidebar"},"cleanup":{"id":"cleanup","title":"Cleanup","description":"To make the replication work, and for other reasons, RxDB has to keep deleted documents in the storage.","sidebar":"tutorialSidebar"},"contribute":{"id":"contribute","title":"Contribute to RxDB","description":"We are open to, and grateful for, any contributions made by the community.","sidebar":"tutorialSidebar"},"crdt":{"id":"crdt","title":"CRDT - Conflict-free replicated data type","description":"Explore the beta RxDB CRDT Plugin - A guide to conflict-free data handling in distributed systems with RxDB\'s novel CRDT approach","sidebar":"tutorialSidebar"},"data-migration":{"id":"data-migration","title":"data-migration","description":"This documentation page has been moved to here"},"dev-mode":{"id":"dev-mode","title":"Dev-Mode Plugin","description":"The dev-mode plugin adds many checks and validations to RxDB.","sidebar":"tutorialSidebar"},"downsides-of-offline-first":{"id":"downsides-of-offline-first","title":"Downsides of Local First / Offline First","description":"So you have read all these things about how the local-first (aka offline-first) paradigm makes it easy to create realtime web applications that even work when the user has no internet connection.","sidebar":"tutorialSidebar"},"electron":{"id":"electron","title":"Electron Plugin","description":"RxStorage Electron IpcRenderer & IpcMain","sidebar":"tutorialSidebar"},"electron-database":{"id":"electron-database","title":"Electron Database - Storage adapters for SQLite, Filesystem and In-Memory","description":"SQLite, Filesystem, and In-Memory storage with RxDB for creating robust local-first Electron apps. Perfect for complex, real-time client-side applications","sidebar":"tutorialSidebar"},"encryption":{"id":"encryption","title":"Encryption","description":"Explore RxDB\'s \ud83d\udd12 encryption plugin for enhanced data security in web and native apps, featuring password-based encryption and secure storage.","sidebar":"tutorialSidebar"},"install":{"id":"install","title":"Installation","description":"npm","sidebar":"tutorialSidebar"},"key-compression":{"id":"key-compression","title":"Key Compression","description":"With the key compression plugin, documents will be stored in a compressed format which saves up to 40% disc space.","sidebar":"tutorialSidebar"},"leader-election":{"id":"leader-election","title":"Leader Election","description":"RxDB comes with a leader-election which elects a leading instance between different instances in the same javascript runtime.","sidebar":"tutorialSidebar"},"logger":{"id":"logger","title":"Logger \ud83d\udc51","description":"With the logger plugin you can log all operations to the storage layer of your RxDatabase.","sidebar":"tutorialSidebar"},"middleware":{"id":"middleware","title":"Middleware","description":"RxDB supports middleware-hooks like mongoose.","sidebar":"tutorialSidebar"},"migration-schema":{"id":"migration-schema","title":"Migration Schema","description":"The RxDB Data Migration Plugin helps developers easily update stored data in their apps when they make changes to the data structure by changing the schema of a RxCollection. This is useful when developers release a new version of the app with a different schema.","sidebar":"tutorialSidebar"},"migration-storage":{"id":"migration-storage","title":"Migration Storage","description":"The storage migration plugin can be used to migrate all data from one existing RxStorage into another. This is useful when:","sidebar":"tutorialSidebar"},"nodejs-database":{"id":"nodejs-database","title":"Node.js Database","description":"RxDB is a fast, reactive realtime NoSQL database made for JavaScript applications like Websites, hybrid Apps, Electron-Apps, Progressive Web Apps and Node.js. While RxDB was initially created to be used with UI applications, it has been matured and optimized to make it useful for pure server-side use cases. It can be used as embedded, local database inside of the Node.js JavaScript process, or it can be used similar to a database server that Node.js can connect to. The RxStorage layer makes it possible to switch out the underlying storage engine which makes RxDB a very flexible database that can be optimized for many scenarios.","sidebar":"tutorialSidebar"},"nosql-performance-tips":{"id":"nosql-performance-tips","title":"RxDB NoSQL Performance Tips","description":"Enhance your NoSQL database performance with RxDB creator\'s tips on bulk operations, query optimization, and efficient use of hooks and plugins, perfect for developers looking to improve speed and efficiency","sidebar":"tutorialSidebar"},"offline-first":{"id":"offline-first","title":"Local First / Offline First","description":"Local-First software stores data on client devices for seamless offline and online functionality, enhancing user experience and efficiency.","sidebar":"tutorialSidebar"},"orm":{"id":"orm","title":"ORM","description":"Like mongoose, RxDB has ORM-capabilities which can be used to add specific behavior to documents and collections.","sidebar":"tutorialSidebar"},"plugins":{"id":"plugins","title":"Plugins","description":"Creating your own plugin is very simple. A plugin is basically a javascript-object which overwrites or extends RxDB\'s internal classes, prototypes, and hooks.","sidebar":"tutorialSidebar"},"population":{"id":"population","title":"Population","description":"There are no joins in RxDB but sometimes we still want references to documents in other collections. This is where population comes in. You can specify a relation from one RxDocument to another RxDocument in the same or another RxCollection of the same database.","sidebar":"tutorialSidebar"},"query-cache":{"id":"query-cache","title":"Query Cache","description":"RxDB uses a QueryCache which optimizes the reuse of queries at runtime. This makes sense especially when RxDB is used in UI-applications where people move for- and backwards on different routes or pages and the same queries are used many times. Because of the event-reduce algorithm cached queries are even valuable for optimization, when changes to the database occur between now and the last execution.","sidebar":"tutorialSidebar"},"query-optimizer":{"id":"query-optimizer","title":"Query Optimizer \ud83d\udc51","description":"The query optimizer can be used to determine which index is the best to use for a given query.","sidebar":"tutorialSidebar"},"questions-answers":{"id":"questions-answers","title":"Questions and Answers","description":"Can\'t change the schema of a collection","sidebar":"tutorialSidebar"},"quickstart":{"id":"quickstart","title":"\ud83d\ude80 Quickstart","description":"Welcome to the RxDB Quickstart. Here we\'ll create a simple realtime TODO-app with RxDB to demonstrate the basic concepts.","sidebar":"tutorialSidebar"},"react-native-database":{"id":"react-native-database","title":"React Native Database","description":"Explore React Native database solutions for cross-platform apps - AsyncStorage, SQLite, RxDB, and more. Tailored for iOS, Android, and Windows, ensuring seamless data storage and sync.","sidebar":"tutorialSidebar"},"releases/10.0.0":{"id":"releases/10.0.0","title":"RxDB 10.0.0","description":"RxDB Major Release 10.0.0","sidebar":"tutorialSidebar"},"releases/11.0.0":{"id":"releases/11.0.0","title":"RxDB 11.0.0","description":"RxDB Major Release 11.0.0","sidebar":"tutorialSidebar"},"releases/12.0.0":{"id":"releases/12.0.0","title":"RxDB 12.0.0","description":"RxDB Major Release 12.0.0","sidebar":"tutorialSidebar"},"releases/13.0.0":{"id":"releases/13.0.0","title":"RxDB 13.0.0","description":"RxDB Major Release 13.0.0","sidebar":"tutorialSidebar"},"releases/14.0.0":{"id":"releases/14.0.0","title":"RxDB 14.0.0","description":"RxDB Major Release 14.0.0","sidebar":"tutorialSidebar"},"releases/15.0.0":{"id":"releases/15.0.0","title":"\ud83c\udd95 RxDB 15.0.0","description":"RxDB Major Release 15.0.0","sidebar":"tutorialSidebar"},"releases/8.0.0":{"id":"releases/8.0.0","title":"RxDB 8.0.0","description":"RxDB Major Release 8.0.0","sidebar":"tutorialSidebar"},"releases/9.0.0":{"id":"releases/9.0.0","title":"RxDB 9.0.0","description":"RxDB Major Release 9.0.0","sidebar":"tutorialSidebar"},"replication":{"id":"replication","title":"\u2699\ufe0f Replication Protocol","description":"The RxDB replication protocol provides the ability to replicate the database state in realtime between the clients and the server.","sidebar":"tutorialSidebar"},"replication-couchdb":{"id":"replication-couchdb","title":"CouchDB Replication","description":"A plugin to replicate between a RxCollection and a CouchDB server.","sidebar":"tutorialSidebar"},"replication-firestore":{"id":"replication-firestore","title":"Firestore Replication","description":"With the replication-firestore plugin you can do a two-way realtime replication","sidebar":"tutorialSidebar"},"replication-graphql":{"id":"replication-graphql","title":"GraphQL Replication","description":"The GraphQL replication provides handlers for GraphQL to run replication with GraphQL as the transportation layer.","sidebar":"tutorialSidebar"},"replication-http":{"id":"replication-http","title":"HTTP Replication","description":"Learn how to establish HTTP replication between RxDB clients and a Node.js Express server for data synchronization.","sidebar":"tutorialSidebar"},"replication-nats":{"id":"replication-nats","title":"NATS Replication","description":"With this RxDB plugin you can run a two-way realtime replication with a NATS server.","sidebar":"tutorialSidebar"},"replication-p2p":{"id":"replication-p2p","title":"P2P Replication","description":"The new documentation page has been moved to here"},"replication-server":{"id":"replication-server","title":"RxDB Server Replication","description":"The Server Replication Plugin connects to the replication endpoint of an RxDB Server and replicates data between the client and the server."},"replication-webrtc":{"id":"replication-webrtc","title":"WebRTC Replication","description":"In the world of web and mobile development, data synchronization between clients and servers has always been a critical aspect of building real-time JavaScript applications.","sidebar":"tutorialSidebar"},"replication-websocket":{"id":"replication-websocket","title":"Websocket Replication","description":"With the websocket replication plugin, you can spawn a websocket server from a RxDB database in Node.js and replicate with it.","sidebar":"tutorialSidebar"},"rx-attachment":{"id":"rx-attachment","title":"Attachments","description":"Attachments are binary data files that can be attachment to an RxDocument, like a file that is attached to an email.","sidebar":"tutorialSidebar"},"rx-collection":{"id":"rx-collection","title":"RxCollection","description":"A collection stores documents of the same type.","sidebar":"tutorialSidebar"},"rx-database":{"id":"rx-database","title":"RxDatabase","description":"A RxDatabase-Object contains your collections and handles the synchronization of change-events.","sidebar":"tutorialSidebar"},"rx-document":{"id":"rx-document","title":"RxDocument","description":"A document is a single object which is stored in a collection. It can be compared to a single record in a relational database table. You get an RxDocument either as return on inserts, or as result-set of queries.","sidebar":"tutorialSidebar"},"rx-local-document":{"id":"rx-local-document","title":"Local Documents","description":"Local documents are a special class of documents which are used to store local metadata.","sidebar":"tutorialSidebar"},"rx-query":{"id":"rx-query","title":"RxQuery","description":"A query allows to find documents in your collection.","sidebar":"tutorialSidebar"},"rx-schema":{"id":"rx-schema","title":"RxSchema","description":"Schemas define the structure of the documents of a collection. Which field should be used as primary, which fields should be used as indexes and what should be encrypted. Every collection has its own schema. With RxDB, schemas are defined with the jsonschema-standard which you might know from other projects.","sidebar":"tutorialSidebar"},"rx-storage":{"id":"rx-storage","title":"\u2699\ufe0f Rxstorage Layer","description":"RxDB is not a self contained database. Instead the data is stored in an implementation of the RxStorage interface. This allows you to switch out the underlying data layer, depending on the JavaScript environment and performance requirements. For example you can use the SQLite storage for a capacitor app or you can use the Dexie.js RxStorage to store data in IndexedDB in a browser based application. There are also storages for other JavaScript runtimes like Node.js, React-Native, NativeScript and more.","sidebar":"tutorialSidebar"},"rx-storage-denokv":{"id":"rx-storage-denokv","title":"DenoKV RxStorage","description":"With the DenoKV RxStorage layer for RxDB, you can run a fully featured NoSQL database on top of the DenoKV API.","sidebar":"tutorialSidebar"},"rx-storage-dexie":{"id":"rx-storage-dexie","title":"Dexie.js RxStorage","description":"To store the data inside of IndexedDB in the browser, you can also use the Dexie.js RxStorage.","sidebar":"tutorialSidebar"},"rx-storage-filesystem-node":{"id":"rx-storage-filesystem-node","title":"Node.js Filesystem RxStorage \ud83d\udc51","description":"The Filesystem Node RxStorage for RxDB is built on top of the Node.js Filesystem API.","sidebar":"tutorialSidebar"},"rx-storage-foundationdb":{"id":"rx-storage-foundationdb","title":"FoundationDB RxStorage","description":"Explore the advanced features of RxDB with FoundationDB RxStorage - Efficient indexing, complex NoSQL queries, real-time updates, data compression, and attachment management for optimized database performance and scalability","sidebar":"tutorialSidebar"},"rx-storage-indexeddb":{"id":"rx-storage-indexeddb","title":"IndexedDB RxStorage \ud83d\udc51","description":"The IndexedDB RxStorage is based on plain IndexedDB and can be used in browsers, electron or hybrid apps.","sidebar":"tutorialSidebar"},"rx-storage-localstorage-meta-optimizer":{"id":"rx-storage-localstorage-meta-optimizer","title":"RxStorage Localstorage Meta Optimizer \ud83d\udc51","description":"The RxStorage Localstorage Meta Optimizer is a wrapper around any other RxStorage. The wrapper uses the original RxStorage for normal collection documents. But to optimize the initial page load time, it uses localstorage to store the plain key-value metadata that RxDB needs to create databases and collections. This plugin can only be used in browsers.","sidebar":"tutorialSidebar"},"rx-storage-lokijs":{"id":"rx-storage-lokijs","title":"LokiJS RxStorage","description":"The LokiJS RxStorage is based on LokiJS which has the main benefit of having a better performance. It can do this because it is an in-memory database that processes all data in memory and only saves to disc when the app is closed or an interval is reached.","sidebar":"tutorialSidebar"},"rx-storage-memory":{"id":"rx-storage-memory","title":"Memory RxStorage","description":"\x3c!-- keywords:","sidebar":"tutorialSidebar"},"rx-storage-memory-synced":{"id":"rx-storage-memory-synced","title":"Memory Synced RxStorage \ud83d\udc51","description":"The memory synced RxStorage is a wrapper around any other RxStorage. The wrapper creates an in-memory storage that is used for query and write operations. This memory instance is replicated with the underlying storage for persistence.","sidebar":"tutorialSidebar"},"rx-storage-mongodb":{"id":"rx-storage-mongodb","title":"MongoDB RxStorage","description":"RxDB MongoDB RxStorage is an RxDB RxStorage that allows you to use MongoDB as the underlying storage engine for your RxDB database. With this you can take advantage of MongoDB\'s features and scalability while benefiting from RxDB\'s real-time data synchronization capabilities.","sidebar":"tutorialSidebar"},"rx-storage-opfs":{"id":"rx-storage-opfs","title":"OPFS RxStorage \ud83d\udc51","description":"Origin Private File System (OPFS) Database with the RxDB OPFS-RxStorage","sidebar":"tutorialSidebar"},"rx-storage-performance":{"id":"rx-storage-performance","title":"\ud83d\udcc8 RxStorage Performance","description":"RxStorage Performance comparison","sidebar":"tutorialSidebar"},"rx-storage-pouchdb":{"id":"rx-storage-pouchdb","title":"PouchDB RxStorage","description":"The PouchDB RxStorage is based on the PouchDB database. It is the most battle proven RxStorage and has a big ecosystem of adapters. PouchDB does a lot of overhead to enable CouchDB replication which makes the PouchDB RxStorage one of the slowest."},"rx-storage-remote":{"id":"rx-storage-remote","title":"Remote RxStorage","description":"The Remote RxStorage is made to use a remote storage and communicate with it over an asynchronous message channel.","sidebar":"tutorialSidebar"},"rx-storage-sharding":{"id":"rx-storage-sharding","title":"Sharding RxStorage \ud83d\udc51","description":"With the sharding plugin, you can improve the write and query times of some RxStorage implementations.","sidebar":"tutorialSidebar"},"rx-storage-shared-worker":{"id":"rx-storage-shared-worker","title":"SharedWorker RxStorage \ud83d\udc51","description":"The SharedWorker RxStorage uses the SharedWorker API to run the storage inside of a separate JavaScript process in browsers. Compared to a normal WebWorker, the SharedWorker is created exactly once, even when there are multiple browser tabs opened. Because of having exactly one worker, multiple performance optimizations can be done because the storage itself does not have to handle multiple opened database connections.","sidebar":"tutorialSidebar"},"rx-storage-sqlite":{"id":"rx-storage-sqlite","title":"SQLite RxStorage \ud83d\udc51","description":"This RxStorage is based on SQLite and is made to work with Node.js, Electron, React Native and Capacitor.","sidebar":"tutorialSidebar"},"rx-storage-worker":{"id":"rx-storage-worker","title":"Worker RxStorage \ud83d\udc51","description":"With the worker plugin, you can put the RxStorage of your database inside of a WebWorker (in browsers) or a Worker Thread (in node.js). By doing so, you can take CPU load from the main process and move it into the worker\'s process which can improve the perceived performance of your application. Notice that for browsers, it is recommend to use the SharedWorker instead to get a better performance.","sidebar":"tutorialSidebar"},"rxdb-tradeoffs":{"id":"rxdb-tradeoffs","title":"RxDB Tradeoffs","description":"RxDB is client-side, offline first Database for JavaScript applications."},"schema-validation":{"id":"schema-validation","title":"Schema Validation","description":"RxDB has multiple validation implementations that can be used to ensure that your document data is always matching the provided JSON"},"server":{"id":"server","title":"RxDB Server","description":"The RxDB Server Plugin makes it possible to spawn a server on top of a RxDB database that offers multiple types of endpoints for various usages. It can spawn basic CRUD REST endpoints or event realtime replication endpoints that can be used by the client devices to replicate data."},"slow-indexeddb":{"id":"slow-indexeddb","title":"Slow IndexedDB","description":"So you have a JavaScript web application that needs to store data at the client side, either to make it offline usable, just for caching purposes or for other reasons.","sidebar":"tutorialSidebar"},"third-party-plugins":{"id":"third-party-plugins","title":"Third Party Plugins","description":"* rxdb-hooks A set of hooks to integrate RxDB into react applications.","sidebar":"tutorialSidebar"},"transactions-conflicts-revisions":{"id":"transactions-conflicts-revisions","title":"Transactions, Conflicts and Revisions","description":"In contrast to most SQL databases, RxDB does not have the concept of relational, ACID transactions. Instead, RxDB has to apply different techniques that better suit the offline-first, client side world where it is not possible to create a transaction between multiple maybe-offline client devices.","sidebar":"tutorialSidebar"},"tutorials/typescript":{"id":"tutorials/typescript","title":"RxDB TypeScript Tutorial","description":"In this tutorial you will learn how to use RxDB with TypeScript.","sidebar":"tutorialSidebar"},"why-nosql":{"id":"why-nosql","title":"Why NOSQL","description":"RxDB, a client side, offline first, JavaScript database, is now several years old.","sidebar":"tutorialSidebar"}}}')}}]); \ No newline at end of file diff --git a/docs/assets/js/a574e172.afb4c9d0.js b/docs/assets/js/a574e172.ef2badac.js similarity index 53% rename from docs/assets/js/a574e172.afb4c9d0.js rename to docs/assets/js/a574e172.ef2badac.js index 93fbfc2cee4..f7402ec8a33 100644 --- a/docs/assets/js/a574e172.afb4c9d0.js +++ b/docs/assets/js/a574e172.ef2badac.js @@ -1 +1 @@ -"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[9153],{2980:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>a,metadata:()=>i,toc:()=>c});var o=n(5893),r=n(1151);const a={title:"HTTP Replication",slug:"replication-http.html",description:"Learn how to establish HTTP replication between RxDB clients and a Node.js Express server for data synchronization."},s="HTTP Replication from a custom server to RxDB clients",i={id:"replication-http",title:"HTTP Replication",description:"Learn how to establish HTTP replication between RxDB clients and a Node.js Express server for data synchronization.",source:"@site/docs/replication-http.md",sourceDirName:".",slug:"/replication-http.html",permalink:"/replication-http.html",draft:!1,unlisted:!1,editUrl:"https://github.com/pubkey/rxdb/tree/master/docs-src/docs/replication-http.md",tags:[],version:"current",frontMatter:{title:"HTTP Replication",slug:"replication-http.html",description:"Learn how to establish HTTP replication between RxDB clients and a Node.js Express server for data synchronization."},sidebar:"tutorialSidebar",previous:{title:"\u2699\ufe0f Replication Protocol",permalink:"/replication.html"},next:{title:"GraphQL Replication",permalink:"/replication-graphql.html"}},l={},c=[{value:"Setup",id:"setup",level:2},{value:"Pull from the server to the client",id:"pull-from-the-server-to-the-client",level:2},{value:"Push from the Client to the Server",id:"push-from-the-client-to-the-server",level:2},{value:"pullStream$ for ongoing changes",id:"pullstream-for-ongoing-changes",level:2},{value:"pullStream$ RESYNC flag",id:"pullstream-resync-flag",level:3},{value:"Missing implementation details",id:"missing-implementation-details",level:2}];function h(e){const t={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,r.a)(),...e.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(t.h1,{id:"http-replication-from-a-custom-server-to-rxdb-clients",children:"HTTP Replication from a custom server to RxDB clients"}),"\n",(0,o.jsxs)(t.p,{children:["While RxDB has a range of backend-specific replication plugins (like ",(0,o.jsx)(t.a,{href:"/replication-graphql.html",children:"GraphQL"})," or ",(0,o.jsx)(t.a,{href:"/replication-firestore.html",children:"Firestore"}),"), the replication is build in a way to make it very easy to replicate data from a custom server to RxDB clients."]}),"\n",(0,o.jsx)("p",{align:"center",children:(0,o.jsx)("img",{src:"./files/icons/with-gradient/replication.svg",alt:"HTTP replication",height:"60"})}),"\n",(0,o.jsxs)(t.p,{children:["Using ",(0,o.jsx)(t.strong,{children:"HTTP"})," as a transport protocol makes it simple to create a compatible backend on top of your existing infrastructure. For events that must be send from the server to to client, we can use ",(0,o.jsx)(t.a,{href:"https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events",children:"Server Send Events"}),"."]}),"\n",(0,o.jsx)(t.p,{children:"In this tutorial we will implement a HTTP replication between an RxDB client and a MongoDB express server. You can adapt this for any other backend database technologie like PostgreSQL or even a non-Node.js server like go or java."}),"\n",(0,o.jsxs)(t.p,{children:["To create a compatible server for replication, we will start a server and implement the correct HTTP routes and replication handlers. We need a push-handler, a pull-handler and for the ongoing changes ",(0,o.jsx)(t.code,{children:"pull.stream"})," we use ",(0,o.jsx)(t.strong,{children:"Server Send Events"}),"."]}),"\n",(0,o.jsx)(t.h2,{id:"setup",children:"Setup"}),"\n",(0,o.jsxs)(t.p,{children:["RxDB does not have a specific HTTP-replication plugin because the ",(0,o.jsx)(t.a,{href:"/replication.html",children:"replication primitives plugin"})," is simple enough to start a HTTP replication on top of it.\nWe import the ",(0,o.jsx)(t.code,{children:"replicateRxCollection"})," function and start the replication from there for a single ",(0,o.jsx)(t.a,{href:"/rx-collection.html",children:"RxCollection"}),"."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\nimport { replicateRxCollection } from 'rxdb/plugins/replication';\nconst replicationState = await replicateRxCollection({\n collection: myRxCollection,\n replicationIdentifier: 'my-http-replication',\n push: { /* add settings from below */ },\n pull: { /* add settings from below */ }\n});\n"})}),"\n",(0,o.jsx)(t.p,{children:"On the server side, we start an express server that has a MongoDB connection and serves the HTTP requests of the client."}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > server.ts\nimport { MongoClient } from 'mongodb';\nimport express from 'express';\nconst mongoClient = new MongoClient('mongodb://localhost:27017/');\nconst mongoConnection = await mongoClient.connect();\nconst mongoDatabase = mongoConnection.db('myDatabase');\nconst mongoCollection = await mongoDatabase.collection('myDocs');\n\nconst app = express();\napp.use(express.json());\n\n/* ... add routes from below */\n\napp.listen(80, () => {\n console.log(`Example app listening on port 80`)\n});\n"})}),"\n",(0,o.jsx)(t.h2,{id:"pull-from-the-server-to-the-client",children:"Pull from the server to the client"}),"\n",(0,o.jsxs)(t.p,{children:["First we need to implement the pull handler. This is used by the RxDB replication to fetch all documents writes that happened after a given ",(0,o.jsx)(t.code,{children:"checkpoint"}),"."]}),"\n",(0,o.jsxs)(t.p,{children:["The ",(0,o.jsx)(t.code,{children:"checkpoint"})," format is not determined by RxDB, instead the server can use any type of changepoint that can be used to iterate across document writes. Here we will just use a unix timestamp ",(0,o.jsx)(t.code,{children:"updatedAt"})," and a string ",(0,o.jsx)(t.code,{children:"id"}),"."]}),"\n",(0,o.jsxs)(t.p,{children:["On the client we add the ",(0,o.jsx)(t.code,{children:"pull.handler"})," to the replication setting. The handler request the correct server url and fetches the documents."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\nconst replicationState = await replicateRxCollection({\n /* ... */\n pull: {\n async handler(checkpointOrNull, batchSize){\n const updatedAt = checkpointOrNull ? checkpointOrNull.updatedAt : 0;\n const id = checkpointOrNull ? checkpointOrNull.id : '';\n const response = await fetch(`https://localhost/pull?updatedAt=${updatedAt}&id=${id}&limit=${batchSize}`);\n const data = await response.json();\n return {\n documents: data.documents,\n checkpoint: data.checkpoint\n };\n }\n \n }\n /* ... */\n});\n"})}),"\n",(0,o.jsx)(t.p,{children:"The server responds with an array of document data based on the given checkpoint and a new checkpoint.\nAlso the server has to respect the batchSize so that RxDB knows when there are no more new documents and the server returns a non-full array."}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > server.ts\nimport { lastOfArray } from 'rxdb/plugins/core';\napp.get('/pull', (req, res) => {\n const id = req.query.id;\n const updatedAt = parseInt(req.query.updatedAt, 10);\n const documents = await mongoCollection.find({\n $or: [\n /**\n * Notice that we have to compare the updatedAt AND the id field\n * because the updateAt field is not unique and when two documents have\n * the same updateAt, we can still \"sort\" them by their id.\n */\n {\n updateAt: { $gt: updatedAt }\n },\n {\n updateAt: { $eq: updatedAt }\n id: { $gt: id }\n }\n ]\n }).limit(parseInt(req.query.batchSize, 10)).toArray();\n const newCheckpoint = documents.length === 0 ? { id, updatedAt } : {\n id: lastOfArray(documents).id,\n updatedAt: lastOfArray(documents).updatedAt\n };\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify({ documents, checkpoint: newCheckpoint }));\n});\n"})}),"\n",(0,o.jsx)(t.h2,{id:"push-from-the-client-to-the-server",children:"Push from the Client to the Server"}),"\n",(0,o.jsxs)(t.p,{children:["To send client side writes to the server, we have to implement the ",(0,o.jsx)(t.code,{children:"push.handler"}),". It gets an array of change rows as input and has to return only the conflicting documents that did not have been written to the server. Each change row contains a ",(0,o.jsx)(t.code,{children:"newDocumentState"})," and an optional ",(0,o.jsx)(t.code,{children:"assumedMasterState"}),"."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\nconst replicationState = await replicateRxCollection({\n /* ... */\n push: {\n async handler(changeRows){\n const rawResponse = await fetch('https://localhost/push', {\n method: 'POST',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({ changeRows })\n });\n const conflictsArray = await rawResponse.json();\n return conflictsArray;\n }\n }\n /* ... */\n});\n"})}),"\n",(0,o.jsxs)(t.p,{children:["On the server we first have to detect if the ",(0,o.jsx)(t.code,{children:"assumedMasterState"}),' is correct for each row. If yes, we have to write the new document state to the database, otherwise we have to return the "real" master state in the conflict array.']}),"\n",(0,o.jsxs)(t.p,{children:[(0,o.jsx)(t.strong,{children:"NOTICE:"})," For simplicity in this tutorial, we do not use transactions. In reality you should run the full push function inside of a MongoDB transaction to ensure that no other process can mix up the document state while the writes are processed. Also you should call batch operations on MongoDB instead of running the operations for each change row."]}),"\n",(0,o.jsxs)(t.p,{children:["The server also creates an ",(0,o.jsx)(t.code,{children:"event"})," that is emitted to the ",(0,o.jsx)(t.code,{children:"pullStream$"})," which is later used in the ",(0,o.jsx)(t.a,{href:"#pullstream-for-ongoing-changes",children:"pull.stream$"}),"."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > server.ts\nimport { lastOfArray } from 'rxdb/plugins/core';\nimport { Subject } from 'rxjs';\n\n// used in the pull.stream$ below\nlet lastEventId = 0;\nconst pullStream$ = new Subject();\n\napp.get('/push', (req, res) => {\n const changeRows = req.body;\n const conflicts = [];\n const event = {\n id: lastEventId++,\n documents: [],\n checkpoint: null\n };\n for(const changeRow of changeRows){\n const realMasterState = mongoCollection.findOne({id: changeRow.newDocumentState.id});\n if(\n realMasterState && !changeRow.assumedMasterState ||\n (\n realMasterState && changeRow.assumedMasterState &&\n /*\n * For simplicity we detect conflicts on the server by only compare the updateAt value.\n * In reality you might want to do a more complex check or do a deep-equal comparison.\n */\n realMasterState.updatedAt !== changeRow.assumedMasterState.updatedAt\n )\n ) {\n // we have a conflict\n conflicts.push(realMasterState);\n } else {\n // no conflict -> write the document\n mongoCollection.updateOne(\n {id: changeRow.newDocumentState.id},\n changeRow.newDocumentState\n );\n event.documents.push(changeRow.newDocumentState);\n event.checkpoint = { id: changeRow.newDocumentState.id, updatedAt: changeRow.newDocumentState.updatedAt };\n }\n }\n if(event.documents.length > 0){\n myPullStream$.next(event);\n }\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify(conflicts));\n});\n"})}),"\n",(0,o.jsx)(t.h2,{id:"pullstream-for-ongoing-changes",children:"pullStream$ for ongoing changes"}),"\n",(0,o.jsxs)(t.p,{children:["While the normal pull handler is used when the replication is in ",(0,o.jsx)(t.a,{href:"/replication.html#checkpoint-iteration",children:"iteration mode"}),", we also need a stream of ongoing changes when the replication is in ",(0,o.jsx)(t.a,{href:"/replication.html#event-observation",children:"event observation mode"}),".\nThe ",(0,o.jsx)(t.code,{children:"pull.stream$"})," is implemented with server send events that are send from the server to the client."]}),"\n",(0,o.jsx)(t.p,{children:"The client connects to an url and receives server-send-events that contain all ongoing writes."}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\nimport { Subject } from 'rxjs';\nconst myPullStream$ = new Subject();\nconst eventSource = new EventSource('http://localhost/pullStream', { withCredentials: true });\nevtSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n myPullStream$.next({\n documents: eventData.documents,\n checkpoint: eventData.checkpoint\n });\n};\n\nconst replicationState = await replicateRxCollection({\n /* ... */\n pull: {\n /* ... */\n stream$: myPullStream$.asObservable()\n }\n /* ... */\n});\n"})}),"\n",(0,o.jsxs)(t.p,{children:["On the server we have to implement the ",(0,o.jsx)(t.code,{children:"pullStream"})," route and emit the events. We use the ",(0,o.jsx)(t.code,{children:"pullStream$"})," observable from ",(0,o.jsx)(t.a,{href:"#push-from-the-client-to-the-server",children:"above"})," to fetch all ongoing events and respond them to the client."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > server.ts\napp.get('/pullStream', (req, res) => {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'no-cache'\n });\n const subscription = pullStream$.subscribe(event => res.write('data: ' + JSON.stringify(event)));\n req.on('close', () => subscription.unsubscribe());\n});\n"})}),"\n",(0,o.jsx)(t.h3,{id:"pullstream-resync-flag",children:"pullStream$ RESYNC flag"}),"\n",(0,o.jsxs)(t.p,{children:["In case the client looses the connection, the EventSource will automatically reconnect but there might have been some changes that have been missed out in the meantime. The replication has to be informed that it might have missed events by emitting a ",(0,o.jsx)(t.code,{children:"RESYNC"})," flag from the ",(0,o.jsx)(t.code,{children:"pull.stream$"}),".\nThe replication will then catch up by switching to the ",(0,o.jsx)(t.a,{href:"/replication.html#checkpoint-iteration",children:"iteration mode"})," until it is in sync with the server again."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\neventSource.onerror = () => myPullStream$.next('RESYNC');\n"})}),"\n",(0,o.jsxs)(t.p,{children:["The purpose of the ",(0,o.jsx)(t.code,{children:"RESYNC"}),' flag is to tell the client that "something might have changed" and then the client can react on that information without having to run operations in an interval.']}),"\n",(0,o.jsx)(t.p,{children:"If your backend is not capable of emitting the actual documents and checkpoint in the pull stream, you could just map all events to the RESYNC flag. This would make the replication work with a slight performance drawback:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\nimport { Subject } from 'rxjs';\nconst myPullStream$ = new Subject();\nconst eventSource = new EventSource('http://localhost/pullStream', { withCredentials: true });\nevtSource.onmessage = () => myPullStream$.next('RESYNC');\nconst replicationState = await replicateRxCollection({\n pull: {\n stream$: myPullStream$.asObservable()\n }\n});\n"})}),"\n",(0,o.jsx)(t.h2,{id:"missing-implementation-details",children:"Missing implementation details"}),"\n",(0,o.jsx)(t.p,{children:"Here we only covered the basics of doing a HTTP replication between RxDB clients and a server. We did not cover the following aspects of the implementation:"}),"\n",(0,o.jsxs)(t.ul,{children:["\n",(0,o.jsx)(t.li,{children:"Authentication: To authenticate the client on the server, you might want to send authentication headers with the HTTP requests"}),"\n",(0,o.jsxs)(t.li,{children:["Skip events on the ",(0,o.jsx)(t.code,{children:"pull.stream$"})," for the client that caused the changes to improve performance."]}),"\n"]})]})}function d(e={}){const{wrapper:t}={...(0,r.a)(),...e.components};return t?(0,o.jsx)(t,{...e,children:(0,o.jsx)(h,{...e})}):h(e)}},1151:(e,t,n)=>{n.d(t,{Z:()=>i,a:()=>s});var o=n(7294);const r={},a=o.createContext(r);function s(e){const t=o.useContext(a);return o.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function i(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:s(e.components),o.createElement(a.Provider,{value:t},e.children)}}}]); \ No newline at end of file +"use strict";(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[9153],{2980:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>d,frontMatter:()=>a,metadata:()=>i,toc:()=>c});var o=n(5893),r=n(1151);const a={title:"HTTP Replication",slug:"replication-http.html",description:"Learn how to establish HTTP replication between RxDB clients and a Node.js Express server for data synchronization."},s="HTTP Replication from a custom server to RxDB clients",i={id:"replication-http",title:"HTTP Replication",description:"Learn how to establish HTTP replication between RxDB clients and a Node.js Express server for data synchronization.",source:"@site/docs/replication-http.md",sourceDirName:".",slug:"/replication-http.html",permalink:"/replication-http.html",draft:!1,unlisted:!1,editUrl:"https://github.com/pubkey/rxdb/tree/master/docs-src/docs/replication-http.md",tags:[],version:"current",frontMatter:{title:"HTTP Replication",slug:"replication-http.html",description:"Learn how to establish HTTP replication between RxDB clients and a Node.js Express server for data synchronization."},sidebar:"tutorialSidebar",previous:{title:"\u2699\ufe0f Replication Protocol",permalink:"/replication.html"},next:{title:"GraphQL Replication",permalink:"/replication-graphql.html"}},l={},c=[{value:"Setup",id:"setup",level:2},{value:"Pull from the server to the client",id:"pull-from-the-server-to-the-client",level:2},{value:"Push from the Client to the Server",id:"push-from-the-client-to-the-server",level:2},{value:"pullStream$ for ongoing changes",id:"pullstream-for-ongoing-changes",level:2},{value:"pullStream$ RESYNC flag",id:"pullstream-resync-flag",level:3},{value:"Missing implementation details",id:"missing-implementation-details",level:2}];function h(e){const t={a:"a",code:"code",h1:"h1",h2:"h2",h3:"h3",li:"li",p:"p",pre:"pre",strong:"strong",ul:"ul",...(0,r.a)(),...e.components};return(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(t.h1,{id:"http-replication-from-a-custom-server-to-rxdb-clients",children:"HTTP Replication from a custom server to RxDB clients"}),"\n",(0,o.jsxs)(t.p,{children:["While RxDB has a range of backend-specific replication plugins (like ",(0,o.jsx)(t.a,{href:"/replication-graphql.html",children:"GraphQL"})," or ",(0,o.jsx)(t.a,{href:"/replication-firestore.html",children:"Firestore"}),"), the replication is build in a way to make it very easy to replicate data from a custom server to RxDB clients."]}),"\n",(0,o.jsx)("p",{align:"center",children:(0,o.jsx)("img",{src:"./files/icons/with-gradient/replication.svg",alt:"HTTP replication",height:"60"})}),"\n",(0,o.jsxs)(t.p,{children:["Using ",(0,o.jsx)(t.strong,{children:"HTTP"})," as a transport protocol makes it simple to create a compatible backend on top of your existing infrastructure. For events that must be send from the server to to client, we can use ",(0,o.jsx)(t.a,{href:"https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events",children:"Server Send Events"}),"."]}),"\n",(0,o.jsx)(t.p,{children:"In this tutorial we will implement a HTTP replication between an RxDB client and a MongoDB express server. You can adapt this for any other backend database technologie like PostgreSQL or even a non-Node.js server like go or java."}),"\n",(0,o.jsxs)(t.p,{children:["To create a compatible server for replication, we will start a server and implement the correct HTTP routes and replication handlers. We need a push-handler, a pull-handler and for the ongoing changes ",(0,o.jsx)(t.code,{children:"pull.stream"})," we use ",(0,o.jsx)(t.strong,{children:"Server Send Events"}),"."]}),"\n",(0,o.jsx)(t.h2,{id:"setup",children:"Setup"}),"\n",(0,o.jsxs)(t.p,{children:["RxDB does not have a specific HTTP-replication plugin because the ",(0,o.jsx)(t.a,{href:"/replication.html",children:"replication primitives plugin"})," is simple enough to start a HTTP replication on top of it.\nWe import the ",(0,o.jsx)(t.code,{children:"replicateRxCollection"})," function and start the replication from there for a single ",(0,o.jsx)(t.a,{href:"/rx-collection.html",children:"RxCollection"}),"."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\nimport { replicateRxCollection } from 'rxdb/plugins/replication';\nconst replicationState = await replicateRxCollection({\n collection: myRxCollection,\n replicationIdentifier: 'my-http-replication',\n push: { /* add settings from below */ },\n pull: { /* add settings from below */ }\n});\n"})}),"\n",(0,o.jsx)(t.p,{children:"On the server side, we start an express server that has a MongoDB connection and serves the HTTP requests of the client."}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > server.ts\nimport { MongoClient } from 'mongodb';\nimport express from 'express';\nconst mongoClient = new MongoClient('mongodb://localhost:27017/');\nconst mongoConnection = await mongoClient.connect();\nconst mongoDatabase = mongoConnection.db('myDatabase');\nconst mongoCollection = await mongoDatabase.collection('myDocs');\n\nconst app = express();\napp.use(express.json());\n\n/* ... add routes from below */\n\napp.listen(80, () => {\n console.log(`Example app listening on port 80`)\n});\n"})}),"\n",(0,o.jsx)(t.h2,{id:"pull-from-the-server-to-the-client",children:"Pull from the server to the client"}),"\n",(0,o.jsxs)(t.p,{children:["First we need to implement the pull handler. This is used by the RxDB replication to fetch all documents writes that happened after a given ",(0,o.jsx)(t.code,{children:"checkpoint"}),"."]}),"\n",(0,o.jsxs)(t.p,{children:["The ",(0,o.jsx)(t.code,{children:"checkpoint"})," format is not determined by RxDB, instead the server can use any type of changepoint that can be used to iterate across document writes. Here we will just use a unix timestamp ",(0,o.jsx)(t.code,{children:"updatedAt"})," and a string ",(0,o.jsx)(t.code,{children:"id"}),"."]}),"\n",(0,o.jsxs)(t.p,{children:["On the client we add the ",(0,o.jsx)(t.code,{children:"pull.handler"})," to the replication setting. The handler request the correct server url and fetches the documents."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\nconst replicationState = await replicateRxCollection({\n /* ... */\n pull: {\n async handler(checkpointOrNull, batchSize){\n const updatedAt = checkpointOrNull ? checkpointOrNull.updatedAt : 0;\n const id = checkpointOrNull ? checkpointOrNull.id : '';\n const response = await fetch(`https://localhost/pull?updatedAt=${updatedAt}&id=${id}&limit=${batchSize}`);\n const data = await response.json();\n return {\n documents: data.documents,\n checkpoint: data.checkpoint\n };\n }\n \n }\n /* ... */\n});\n"})}),"\n",(0,o.jsx)(t.p,{children:"The server responds with an array of document data based on the given checkpoint and a new checkpoint.\nAlso the server has to respect the batchSize so that RxDB knows when there are no more new documents and the server returns a non-full array."}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > server.ts\nimport { lastOfArray } from 'rxdb/plugins/core';\napp.get('/pull', (req, res) => {\n const id = req.query.id;\n const updatedAt = parseInt(req.query.updatedAt, 10);\n const documents = await mongoCollection.find({\n $or: [\n /**\n * Notice that we have to compare the updatedAt AND the id field\n * because the updateAt field is not unique and when two documents have\n * the same updateAt, we can still \"sort\" them by their id.\n */\n {\n updateAt: { $gt: updatedAt }\n },\n {\n updateAt: { $eq: updatedAt }\n id: { $gt: id }\n }\n ]\n }).limit(parseInt(req.query.batchSize, 10)).toArray();\n const newCheckpoint = documents.length === 0 ? { id, updatedAt } : {\n id: lastOfArray(documents).id,\n updatedAt: lastOfArray(documents).updatedAt\n };\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify({ documents, checkpoint: newCheckpoint }));\n});\n"})}),"\n",(0,o.jsx)(t.h2,{id:"push-from-the-client-to-the-server",children:"Push from the Client to the Server"}),"\n",(0,o.jsxs)(t.p,{children:["To send client side writes to the server, we have to implement the ",(0,o.jsx)(t.code,{children:"push.handler"}),". It gets an array of change rows as input and has to return only the conflicting documents that did not have been written to the server. Each change row contains a ",(0,o.jsx)(t.code,{children:"newDocumentState"})," and an optional ",(0,o.jsx)(t.code,{children:"assumedMasterState"}),"."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\nconst replicationState = await replicateRxCollection({\n /* ... */\n push: {\n async handler(changeRows){\n const rawResponse = await fetch('https://localhost/push', {\n method: 'POST',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(changeRows)\n });\n const conflictsArray = await rawResponse.json();\n return conflictsArray;\n }\n }\n /* ... */\n});\n"})}),"\n",(0,o.jsxs)(t.p,{children:["On the server we first have to detect if the ",(0,o.jsx)(t.code,{children:"assumedMasterState"}),' is correct for each row. If yes, we have to write the new document state to the database, otherwise we have to return the "real" master state in the conflict array.']}),"\n",(0,o.jsxs)(t.p,{children:[(0,o.jsx)(t.strong,{children:"NOTICE:"})," For simplicity in this tutorial, we do not use transactions. In reality you should run the full push function inside of a MongoDB transaction to ensure that no other process can mix up the document state while the writes are processed. Also you should call batch operations on MongoDB instead of running the operations for each change row."]}),"\n",(0,o.jsxs)(t.p,{children:["The server also creates an ",(0,o.jsx)(t.code,{children:"event"})," that is emitted to the ",(0,o.jsx)(t.code,{children:"pullStream$"})," which is later used in the ",(0,o.jsx)(t.a,{href:"#pullstream-for-ongoing-changes",children:"pull.stream$"}),"."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > server.ts\nimport { lastOfArray } from 'rxdb/plugins/core';\nimport { Subject } from 'rxjs';\n\n// used in the pull.stream$ below\nlet lastEventId = 0;\nconst pullStream$ = new Subject();\n\napp.get('/push', (req, res) => {\n const changeRows = req.body;\n const conflicts = [];\n const event = {\n id: lastEventId++,\n documents: [],\n checkpoint: null\n };\n for(const changeRow of changeRows){\n const realMasterState = mongoCollection.findOne({id: changeRow.newDocumentState.id});\n if(\n realMasterState && !changeRow.assumedMasterState ||\n (\n realMasterState && changeRow.assumedMasterState &&\n /*\n * For simplicity we detect conflicts on the server by only compare the updateAt value.\n * In reality you might want to do a more complex check or do a deep-equal comparison.\n */\n realMasterState.updatedAt !== changeRow.assumedMasterState.updatedAt\n )\n ) {\n // we have a conflict\n conflicts.push(realMasterState);\n } else {\n // no conflict -> write the document\n mongoCollection.updateOne(\n {id: changeRow.newDocumentState.id},\n changeRow.newDocumentState\n );\n event.documents.push(changeRow.newDocumentState);\n event.checkpoint = { id: changeRow.newDocumentState.id, updatedAt: changeRow.newDocumentState.updatedAt };\n }\n }\n if(event.documents.length > 0){\n myPullStream$.next(event);\n }\n res.setHeader('Content-Type', 'application/json');\n res.end(JSON.stringify(conflicts));\n});\n"})}),"\n",(0,o.jsx)(t.h2,{id:"pullstream-for-ongoing-changes",children:"pullStream$ for ongoing changes"}),"\n",(0,o.jsxs)(t.p,{children:["While the normal pull handler is used when the replication is in ",(0,o.jsx)(t.a,{href:"/replication.html#checkpoint-iteration",children:"iteration mode"}),", we also need a stream of ongoing changes when the replication is in ",(0,o.jsx)(t.a,{href:"/replication.html#event-observation",children:"event observation mode"}),".\nThe ",(0,o.jsx)(t.code,{children:"pull.stream$"})," is implemented with server send events that are send from the server to the client."]}),"\n",(0,o.jsx)(t.p,{children:"The client connects to an url and receives server-send-events that contain all ongoing writes."}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\nimport { Subject } from 'rxjs';\nconst myPullStream$ = new Subject();\nconst eventSource = new EventSource('http://localhost/pullStream', { withCredentials: true });\neventSource.onmessage = event => {\n const eventData = JSON.parse(event.data);\n myPullStream$.next({\n documents: eventData.documents,\n checkpoint: eventData.checkpoint\n });\n};\n\nconst replicationState = await replicateRxCollection({\n /* ... */\n pull: {\n /* ... */\n stream$: myPullStream$.asObservable()\n }\n /* ... */\n});\n"})}),"\n",(0,o.jsxs)(t.p,{children:["On the server we have to implement the ",(0,o.jsx)(t.code,{children:"pullStream"})," route and emit the events. We use the ",(0,o.jsx)(t.code,{children:"pullStream$"})," observable from ",(0,o.jsx)(t.a,{href:"#push-from-the-client-to-the-server",children:"above"})," to fetch all ongoing events and respond them to the client."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > server.ts\napp.get('/pullStream', (req, res) => {\n res.writeHead(200, {\n 'Content-Type': 'text/event-stream',\n 'Connection': 'keep-alive',\n 'Cache-Control': 'no-cache'\n });\n const subscription = pullStream$.subscribe(event => res.write('data: ' + JSON.stringify(event) + '\\n\\n'));\n req.on('close', () => subscription.unsubscribe());\n});\n"})}),"\n",(0,o.jsx)(t.h3,{id:"pullstream-resync-flag",children:"pullStream$ RESYNC flag"}),"\n",(0,o.jsxs)(t.p,{children:["In case the client looses the connection, the EventSource will automatically reconnect but there might have been some changes that have been missed out in the meantime. The replication has to be informed that it might have missed events by emitting a ",(0,o.jsx)(t.code,{children:"RESYNC"})," flag from the ",(0,o.jsx)(t.code,{children:"pull.stream$"}),".\nThe replication will then catch up by switching to the ",(0,o.jsx)(t.a,{href:"/replication.html#checkpoint-iteration",children:"iteration mode"})," until it is in sync with the server again."]}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\neventSource.onerror = () => myPullStream$.next('RESYNC');\n"})}),"\n",(0,o.jsxs)(t.p,{children:["The purpose of the ",(0,o.jsx)(t.code,{children:"RESYNC"}),' flag is to tell the client that "something might have changed" and then the client can react on that information without having to run operations in an interval.']}),"\n",(0,o.jsx)(t.p,{children:"If your backend is not capable of emitting the actual documents and checkpoint in the pull stream, you could just map all events to the RESYNC flag. This would make the replication work with a slight performance drawback:"}),"\n",(0,o.jsx)(t.pre,{children:(0,o.jsx)(t.code,{className:"language-ts",children:"// > client.ts\nimport { Subject } from 'rxjs';\nconst myPullStream$ = new Subject();\nconst eventSource = new EventSource('http://localhost/pullStream', { withCredentials: true });\neventSource.onmessage = () => myPullStream$.next('RESYNC');\nconst replicationState = await replicateRxCollection({\n pull: {\n stream$: myPullStream$.asObservable()\n }\n});\n"})}),"\n",(0,o.jsx)(t.h2,{id:"missing-implementation-details",children:"Missing implementation details"}),"\n",(0,o.jsx)(t.p,{children:"Here we only covered the basics of doing a HTTP replication between RxDB clients and a server. We did not cover the following aspects of the implementation:"}),"\n",(0,o.jsxs)(t.ul,{children:["\n",(0,o.jsx)(t.li,{children:"Authentication: To authenticate the client on the server, you might want to send authentication headers with the HTTP requests"}),"\n",(0,o.jsxs)(t.li,{children:["Skip events on the ",(0,o.jsx)(t.code,{children:"pull.stream$"})," for the client that caused the changes to improve performance."]}),"\n"]})]})}function d(e={}){const{wrapper:t}={...(0,r.a)(),...e.components};return t?(0,o.jsx)(t,{...e,children:(0,o.jsx)(h,{...e})}):h(e)}},1151:(e,t,n)=>{n.d(t,{Z:()=>i,a:()=>s});var o=n(7294);const r={},a=o.createContext(r);function s(e){const t=o.useContext(a);return o.useMemo((function(){return"function"==typeof e?e(t):{...t,...e}}),[t,e])}function i(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:s(e.components),o.createElement(a.Provider,{value:t},e.children)}}}]); \ No newline at end of file diff --git a/docs/assets/js/main.6f2da8fa.js b/docs/assets/js/main.6f2da8fa.js new file mode 100644 index 00000000000..bcf6c13cbdf --- /dev/null +++ b/docs/assets/js/main.6f2da8fa.js @@ -0,0 +1,2 @@ +/*! For license information please see main.6f2da8fa.js.LICENSE.txt */ +(self.webpackChunkrxdb=self.webpackChunkrxdb||[]).push([[179],{723:(e,t,n)=>{"use strict";n.d(t,{Z:()=>p});n(7294);var r=n(8356),a=n.n(r),o=n(6887);const i={"0027230a":[()=>n.e(7729).then(n.bind(n,1314)),"@site/docs/rx-storage-lokijs.md",1314],"01684a0a":[()=>n.e(1705).then(n.bind(n,6262)),"@site/docs/rx-storage-memory-synced.md",6262],"03e37916":[()=>n.e(1920).then(n.bind(n,9593)),"@site/docs/transactions-conflicts-revisions.md",9593],"045bd6f5":[()=>n.e(1314).then(n.bind(n,2203)),"@site/docs/encryption.md",2203],"04b0214f":[()=>n.e(7681).then(n.t.bind(n,5745,19)),"/home/runner/work/rxdb/rxdb/docs-src/.docusaurus/docusaurus-plugin-content-pages/default/plugin-route-context-module-100.json",5745],"0e268d20":[()=>Promise.all([n.e(6560),n.e(2160)]).then(n.bind(n,6451)),"@site/src/pages/premium.tsx",6451],"0e945c41":[()=>n.e(8280).then(n.bind(n,1413)),"@site/docs/replication-server.md",1413],"0f6e10f0":[()=>n.e(8705).then(n.bind(n,7694)),"@site/docs/articles/progressive-web-app-database.md",7694],"118cde4c":[()=>n.e(6267).then(n.bind(n,2171)),"@site/docs/replication-couchdb.md",2171],"14d72841":[()=>n.e(7362).then(n.bind(n,6906)),"@site/src/pages/newsletter.tsx",6906],17896441:[()=>Promise.all([n.e(532),n.e(325),n.e(7918)]).then(n.bind(n,903)),"@theme/DocItem",903],"187b985e":[()=>n.e(8196).then(n.bind(n,4228)),"@site/docs/replication-webrtc.md",4228],"1b0f8c91":[()=>n.e(5489).then(n.bind(n,7693)),"@site/docs/backup.md",7693],"1b238727":[()=>n.e(7018).then(n.bind(n,9003)),"@site/docs/rx-storage-performance.md",9003],"1c0701dd":[()=>n.e(6235).then(n.bind(n,6137)),"@site/docs/middleware.md",6137],"1da545ff":[()=>n.e(432).then(n.bind(n,8942)),"@site/docs/releases/9.0.0.md",8942],"1df93b7f":[()=>Promise.all([n.e(6560),n.e(3237)]).then(n.bind(n,1960)),"@site/src/pages/index.tsx",1960],"1e0353aa":[()=>n.e(5691).then(n.bind(n,7566)),"@site/docs/rx-storage.md",7566],"1f391b9e":[()=>Promise.all([n.e(532),n.e(325),n.e(3085)]).then(n.bind(n,4247)),"@theme/MDXPage",4247],"21fa2740":[()=>n.e(3222).then(n.bind(n,9364)),"@site/docs/releases/15.0.0.md",9364],"2456d5e0":[()=>n.e(4136).then(n.bind(n,8722)),"@site/docs/rx-database.md",8722],"25626d15":[()=>n.e(9468).then(n.bind(n,7833)),"@site/src/pages/chat.tsx",7833],"2564bf4f":[()=>n.e(5729).then(n.bind(n,43)),"@site/docs/rxdb-tradeoffs.md",43],"25a43fd4":[()=>n.e(7739).then(n.bind(n,3797)),"@site/docs/rx-storage-shared-worker.md",3797],"26b8a621":[()=>n.e(529).then(n.bind(n,7597)),"@site/docs/replication-p2p.md",7597],"294ac9d5":[()=>n.e(8856).then(n.bind(n,3274)),"@site/docs/plugins.md",3274],"2dc45ced":[()=>n.e(1218).then(n.bind(n,8821)),"@site/docs/server.md",8821],"2efd0200":[()=>n.e(8306).then(n.bind(n,632)),"@site/docs/tutorials/typescript.md",632],"32667c41":[()=>n.e(2667).then(n.bind(n,5815)),"@site/docs/nosql-performance-tips.md",5815],"326aca46":[()=>n.e(149).then(n.bind(n,4684)),"@site/docs/offline-first.md",4684],"34f94d1b":[()=>n.e(8372).then(n.bind(n,5285)),"@site/docs/electron-database.md",5285],36715375:[()=>n.e(6822).then(n.bind(n,4680)),"@site/src/pages/code.tsx",4680],"380cc66a":[()=>n.e(2038).then(n.bind(n,4919)),"@site/docs/rx-storage-dexie.md",4919],"38bbf12a":[()=>n.e(6467).then(n.bind(n,9086)),"@site/docs/articles/data-base.md",9086],"393be207":[()=>n.e(7414).then(n.bind(n,1181)),"@site/src/pages/markdown-page.md",1181],"39600c95":[()=>n.e(7344).then(n.bind(n,1512)),"@site/docs/rx-query.md",1512],"401008a8":[()=>n.e(4264).then(n.bind(n,9636)),"@site/docs/nodejs-database.md",9636],"41f941a1":[()=>n.e(5687).then(n.bind(n,7315)),"@site/docs/leader-election.md",7315],"432b83f9":[()=>n.e(4843).then(n.bind(n,5807)),"@site/docs/releases/8.0.0.md",5807],"4616b86a":[()=>n.e(6174).then(n.bind(n,2115)),"@site/docs/rx-storage-mongodb.md",2115],"4777fd9a":[()=>n.e(2192).then(n.bind(n,7168)),"@site/docs/alternatives.md",7168],"4adf80bb":[()=>n.e(7532).then(n.bind(n,6203)),"@site/docs/rx-storage-pouchdb.md",6203],"4af60d2e":[()=>n.e(9164).then(n.bind(n,253)),"@site/docs/articles/realtime-database.md",253],"4ba7e5a3":[()=>n.e(9735).then(n.bind(n,2742)),"@site/docs/contribute.md",2742],"4ed9495b":[()=>n.e(3401).then(n.bind(n,4371)),"@site/docs/rx-storage-sqlite.md",4371],"502d8946":[()=>n.e(3636).then(n.bind(n,9739)),"@site/src/pages/legal-notice.tsx",9739],51334108:[()=>n.e(2716).then(n.bind(n,4320)),"@site/docs/articles/mobile-database.md",4320],"55a5b596":[()=>n.e(4669).then(n.bind(n,8021)),"@site/docs/rx-schema.md",8021],"5a273530":[()=>n.e(6082).then(n.bind(n,4995)),"@site/docs/rx-storage-remote.md",4995],"5e95c892":[()=>n.e(9661).then(n.bind(n,1892)),"@theme/DocsRoot",1892],"5e9f5e1a":[()=>Promise.resolve().then(n.bind(n,6809)),"@generated/docusaurus.config",6809],"60c23941":[()=>n.e(6533).then(n.t.bind(n,3769,19)),"/home/runner/work/rxdb/rxdb/docs-src/.docusaurus/docusaurus-plugin-content-docs/default/plugin-route-context-module-100.json",3769],"6187b59a":[()=>n.e(7987).then(n.bind(n,6846)),"@site/docs/rx-storage-worker.md",6846],"68a466be":[()=>n.e(2270).then(n.bind(n,2358)),"@site/docs/downsides-of-offline-first.md",2358],"6ae3580c":[()=>n.e(6330).then(n.bind(n,7260)),"@site/docs/replication.md",7260],"6bfb0089":[()=>n.e(9971).then(n.bind(n,7562)),"@site/docs/adapters.md",7562],"6cbff7c2":[()=>n.e(1826).then(n.bind(n,9829)),"@site/docs/rx-storage-opfs.md",9829],"6fd28feb":[()=>n.e(5333).then(n.bind(n,1850)),"@site/docs/rx-storage-foundationdb.md",1850],"714575d7":[()=>n.e(6493).then(n.bind(n,279)),"@site/docs/rx-local-document.md",279],"77d975e6":[()=>n.e(7564).then(n.bind(n,7831)),"@site/docs/articles/in-memory-nosql-database.md",7831],"7815dd0c":[()=>n.e(1341).then(n.bind(n,8147)),"@site/docs/population.md",8147],"7f02c700":[()=>n.e(7168).then(n.bind(n,2843)),"@site/docs/replication-firestore.md",2843],"8070e160":[()=>n.e(2651).then(n.bind(n,9759)),"@site/docs/quickstart.md",9759],"8288c265":[()=>n.e(871).then(n.bind(n,4442)),"@site/docs/releases/11.0.0.md",4442],"84a3af36":[()=>n.e(8862).then(n.bind(n,7292)),"@site/docs/articles/json-database.md",7292],"84ae55a4":[()=>n.e(4674).then(n.bind(n,544)),"@site/docs/replication-nats.md",544],"86b4e356":[()=>n.e(980).then(n.bind(n,5760)),"@site/docs/orm.md",5760],"8aa53ed7":[()=>n.e(1254).then(n.bind(n,1341)),"@site/docs/articles/angular-database.md",1341],"8b0a0922":[()=>n.e(4869).then(n.bind(n,1028)),"@site/docs/slow-indexeddb.md",1028],"8bc07e20":[()=>n.e(1074).then(n.bind(n,7282)),"@site/docs/capacitor-database.md",7282],"91b454ee":[()=>n.e(5832).then(n.bind(n,3746)),"@site/docs/rx-storage-sharding.md",3746],"924d6dd6":[()=>n.e(3075).then(n.bind(n,1204)),"@site/docs/electron.md",1204],"92698a99":[()=>n.e(3238).then(n.bind(n,814)),"@site/docs/rx-storage-indexeddb.md",814],"931f4566":[()=>n.e(5657).then(n.bind(n,8852)),"@site/docs/schema-validation.md",8852],"935f2afb":[()=>n.e(53).then(n.t.bind(n,1109,19)),"~docs/default/version-current-metadata-prop-751.json",1109],98405524:[()=>n.e(3562).then(n.bind(n,6704)),"@site/src/pages/survey.tsx",6704],"9dd8ea89":[()=>n.e(8814).then(n.bind(n,7854)),"@site/docs/logger.md",7854],"9e91b6f0":[()=>n.e(803).then(n.bind(n,4296)),"@site/docs/why-nosql.md",4296],a406dc27:[()=>n.e(6432).then(n.bind(n,698)),"@site/docs/migration-storage.md",698],a574e172:[()=>n.e(9153).then(n.bind(n,2980)),"@site/docs/replication-http.md",2980],a69eebfc:[()=>n.e(8577).then(n.bind(n,566)),"@site/docs/query-optimizer.md",566],a7bd4aaa:[()=>n.e(8518).then(n.bind(n,8564)),"@theme/DocVersionRoot",8564],a7f10198:[()=>n.e(2566).then(n.bind(n,7164)),"@site/docs/data-migration.md",7164],a94703ab:[()=>Promise.all([n.e(532),n.e(4368)]).then(n.bind(n,2674)),"@theme/DocRoot",2674],aa14e6b1:[()=>n.e(933).then(n.bind(n,8439)),"@site/docs/replication-graphql.md",8439],ab919a1f:[()=>n.e(4133).then(n.bind(n,3372)),"@site/docs/articles/embedded-database.md",3372],ac62b32d:[()=>n.e(4724).then(n.bind(n,5135)),"@site/docs/replication-websocket.md",5135],ad16b3ea:[()=>n.e(4492).then(n.bind(n,3750)),"@site/docs/dev-mode.md",3750],b0889a22:[()=>n.e(606).then(n.bind(n,4530)),"@site/docs/cleanup.md",4530],b30f4f1f:[()=>n.e(1609).then(n.bind(n,2462)),"@site/docs/rx-attachment.md",2462],b8c49ce4:[()=>n.e(7035).then(n.bind(n,7547)),"@site/docs/releases/13.0.0.md",7547],badcd764:[()=>n.e(6071).then(n.bind(n,6651)),"@site/docs/articles/flutter-database.md",6651],c3bc9c50:[()=>n.e(453).then(n.bind(n,8896)),"@site/docs/articles/react-database.md",8896],c4de80f8:[()=>n.e(7943).then(n.bind(n,1378)),"@site/docs/install.md",1378],c6349bb6:[()=>n.e(2191).then(n.bind(n,7557)),"@site/docs/releases/14.0.0.md",7557],c843a053:[()=>n.e(694).then(n.bind(n,408)),"@site/docs/third-party-plugins.md",408],c9c8e0b6:[()=>n.e(7585).then(n.bind(n,7548)),"@site/docs/articles/ionic-database.md",7548],cbbe8f0a:[()=>n.e(9242).then(n.bind(n,5290)),"@site/docs/rx-collection.md",5290],d20e74b4:[()=>n.e(6284).then(n.bind(n,5305)),"@site/docs/crdt.md",5305],d2758528:[()=>n.e(2081).then(n.bind(n,3898)),"@site/docs/articles/browser-storage.md",3898],d4da9db3:[()=>n.e(6017).then(n.bind(n,2443)),"@site/docs/rx-storage-memory.md",2443],d622bd51:[()=>n.e(4431).then(n.bind(n,7798)),"@site/docs/migration-schema.md",7798],dbde2ffe:[()=>n.e(8994).then(n.bind(n,4592)),"@site/docs/rx-document.md",4592],dc42ba65:[()=>n.e(3305).then(n.bind(n,7239)),"@site/docs/key-compression.md",7239],e24529eb:[()=>n.e(5846).then(n.bind(n,1290)),"@site/docs/rx-storage-localstorage-meta-optimizer.md",1290],e6b4453d:[()=>n.e(2908).then(n.bind(n,9644)),"@site/docs/query-cache.md",9644],e7478ff0:[()=>n.e(3442).then(n.bind(n,7706)),"@site/docs/questions-answers.md",7706],eadd9b3c:[()=>n.e(463).then(n.bind(n,5716)),"@site/docs/rx-storage-filesystem-node.md",5716],ebace26e:[()=>n.e(4589).then(n.bind(n,8037)),"@site/docs/releases/10.0.0.md",8037],ec526260:[()=>n.e(4625).then(n.bind(n,500)),"@site/docs/articles/browser-database.md",500],ed2d6610:[()=>n.e(5096).then(n.bind(n,5705)),"@site/docs/releases/12.0.0.md",5705],ee1b9f21:[()=>n.e(7436).then(n.bind(n,7700)),"@site/docs/react-native-database.md",7700],f15938da:[()=>n.e(8053).then(n.bind(n,4953)),"@site/docs/articles/localstorage.md",4953],f44bb875:[()=>n.e(5522).then(n.bind(n,1600)),"@site/docs/articles/frontend-database.md",1600],fe7a07ee:[()=>n.e(3776).then(n.bind(n,1684)),"@site/docs/rx-storage-denokv.md",1684]};var l=n(5893);function s(e){let{error:t,retry:n,pastDelay:r}=e;return t?(0,l.jsxs)("div",{style:{textAlign:"center",color:"#fff",backgroundColor:"#fa383e",borderColor:"#fa383e",borderStyle:"solid",borderRadius:"0.25rem",borderWidth:"1px",boxSizing:"border-box",display:"block",padding:"1rem",flex:"0 0 50%",marginLeft:"25%",marginRight:"25%",marginTop:"5rem",maxWidth:"50%",width:"100%"},children:[(0,l.jsx)("p",{children:String(t)}),(0,l.jsx)("div",{children:(0,l.jsx)("button",{type:"button",onClick:n,children:"Retry"})})]}):r?(0,l.jsx)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100vh"},children:(0,l.jsx)("svg",{id:"loader",style:{width:128,height:110,position:"absolute",top:"calc(100vh - 64%)"},viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",stroke:"#61dafb",children:(0,l.jsxs)("g",{fill:"none",fillRule:"evenodd",transform:"translate(1 1)",strokeWidth:"2",children:[(0,l.jsxs)("circle",{cx:"22",cy:"22",r:"6",strokeOpacity:"0",children:[(0,l.jsx)("animate",{attributeName:"r",begin:"1.5s",dur:"3s",values:"6;22",calcMode:"linear",repeatCount:"indefinite"}),(0,l.jsx)("animate",{attributeName:"stroke-opacity",begin:"1.5s",dur:"3s",values:"1;0",calcMode:"linear",repeatCount:"indefinite"}),(0,l.jsx)("animate",{attributeName:"stroke-width",begin:"1.5s",dur:"3s",values:"2;0",calcMode:"linear",repeatCount:"indefinite"})]}),(0,l.jsxs)("circle",{cx:"22",cy:"22",r:"6",strokeOpacity:"0",children:[(0,l.jsx)("animate",{attributeName:"r",begin:"3s",dur:"3s",values:"6;22",calcMode:"linear",repeatCount:"indefinite"}),(0,l.jsx)("animate",{attributeName:"stroke-opacity",begin:"3s",dur:"3s",values:"1;0",calcMode:"linear",repeatCount:"indefinite"}),(0,l.jsx)("animate",{attributeName:"stroke-width",begin:"3s",dur:"3s",values:"2;0",calcMode:"linear",repeatCount:"indefinite"})]}),(0,l.jsx)("circle",{cx:"22",cy:"22",r:"8",children:(0,l.jsx)("animate",{attributeName:"r",begin:"0s",dur:"1.5s",values:"6;1;2;3;4;5;6",calcMode:"linear",repeatCount:"indefinite"})})]})})}):null}var c=n(9670),u=n(226);function d(e,t){if("*"===e)return a()({loading:s,loader:()=>n.e(930).then(n.bind(n,930)),modules:["@theme/NotFound"],webpack:()=>[930],render(e,t){const n=e.default;return(0,l.jsx)(u.z,{value:{plugin:{name:"native",id:"default"}},children:(0,l.jsx)(n,{...t})})}});const r=o[`${e}-${t}`],d={},p=[],f=[],m=(0,c.Z)(r);return Object.entries(m).forEach((e=>{let[t,n]=e;const r=i[n];r&&(d[t]=r[0],p.push(r[1]),f.push(r[2]))})),a().Map({loading:s,loader:d,modules:p,webpack:()=>f,render(t,n){const a=JSON.parse(JSON.stringify(r));Object.entries(t).forEach((t=>{let[n,r]=t;const o=r.default;if(!o)throw new Error(`The page component at ${e} doesn't have a default export. This makes it impossible to render anything. Consider default-exporting a React component.`);"object"!=typeof o&&"function"!=typeof o||Object.keys(r).filter((e=>"default"!==e)).forEach((e=>{o[e]=r[e]}));let i=a;const l=n.split(".");l.slice(0,-1).forEach((e=>{i=i[e]})),i[l[l.length-1]]=o}));const o=a.__comp;delete a.__comp;const i=a.__context;return delete a.__context,(0,l.jsx)(u.z,{value:i,children:(0,l.jsx)(o,{...a,...n})})}})}const p=[{path:"/chat",component:d("/chat","fd7"),exact:!0},{path:"/code",component:d("/code","8ef"),exact:!0},{path:"/legal-notice",component:d("/legal-notice","cfc"),exact:!0},{path:"/markdown-page",component:d("/markdown-page","784"),exact:!0},{path:"/newsletter",component:d("/newsletter","d15"),exact:!0},{path:"/premium",component:d("/premium","d94"),exact:!0},{path:"/survey",component:d("/survey","9e0"),exact:!0},{path:"/",component:d("/","d82"),exact:!0},{path:"/",component:d("/","77d"),routes:[{path:"/",component:d("/","c0c"),routes:[{path:"/",component:d("/","5d9"),routes:[{path:"/adapters.html",component:d("/adapters.html","fb4"),exact:!0},{path:"/alternatives.html",component:d("/alternatives.html","d53"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/angular-database.html",component:d("/articles/angular-database.html","e30"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/browser-database.html",component:d("/articles/browser-database.html","b0a"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/browser-storage.html",component:d("/articles/browser-storage.html","286"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/data-base.html",component:d("/articles/data-base.html","797"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/embedded-database.html",component:d("/articles/embedded-database.html","596"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/flutter-database.html",component:d("/articles/flutter-database.html","f8a"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/frontend-database.html",component:d("/articles/frontend-database.html","a83"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/in-memory-nosql-database.html",component:d("/articles/in-memory-nosql-database.html","ead"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/ionic-database.html",component:d("/articles/ionic-database.html","df6"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/json-database.html",component:d("/articles/json-database.html","bff"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/localstorage.html",component:d("/articles/localstorage.html","b1b"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/mobile-database.html",component:d("/articles/mobile-database.html","1d7"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/progressive-web-app-database.html",component:d("/articles/progressive-web-app-database.html","862"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/react-database.html",component:d("/articles/react-database.html","179"),exact:!0,sidebar:"tutorialSidebar"},{path:"/articles/realtime-database.html",component:d("/articles/realtime-database.html","bc3"),exact:!0,sidebar:"tutorialSidebar"},{path:"/backup.html",component:d("/backup.html","123"),exact:!0,sidebar:"tutorialSidebar"},{path:"/capacitor-database.html",component:d("/capacitor-database.html","71f"),exact:!0,sidebar:"tutorialSidebar"},{path:"/cleanup.html",component:d("/cleanup.html","d7f"),exact:!0,sidebar:"tutorialSidebar"},{path:"/contribution.html",component:d("/contribution.html","129"),exact:!0,sidebar:"tutorialSidebar"},{path:"/crdt.html",component:d("/crdt.html","c69"),exact:!0,sidebar:"tutorialSidebar"},{path:"/data-migration",component:d("/data-migration","7c7"),exact:!0},{path:"/dev-mode.html",component:d("/dev-mode.html","11d"),exact:!0,sidebar:"tutorialSidebar"},{path:"/downsides-of-offline-first.html",component:d("/downsides-of-offline-first.html","ba4"),exact:!0,sidebar:"tutorialSidebar"},{path:"/electron-database.html",component:d("/electron-database.html","44e"),exact:!0,sidebar:"tutorialSidebar"},{path:"/electron.html",component:d("/electron.html","693"),exact:!0,sidebar:"tutorialSidebar"},{path:"/encryption.html",component:d("/encryption.html","265"),exact:!0,sidebar:"tutorialSidebar"},{path:"/install.html",component:d("/install.html","9ec"),exact:!0,sidebar:"tutorialSidebar"},{path:"/key-compression.html",component:d("/key-compression.html","171"),exact:!0,sidebar:"tutorialSidebar"},{path:"/leader-election.html",component:d("/leader-election.html","9aa"),exact:!0,sidebar:"tutorialSidebar"},{path:"/logger.html",component:d("/logger.html","949"),exact:!0,sidebar:"tutorialSidebar"},{path:"/middleware.html",component:d("/middleware.html","34f"),exact:!0,sidebar:"tutorialSidebar"},{path:"/migration-schema.html",component:d("/migration-schema.html","618"),exact:!0,sidebar:"tutorialSidebar"},{path:"/migration-storage.html",component:d("/migration-storage.html","34a"),exact:!0,sidebar:"tutorialSidebar"},{path:"/nodejs-database.html",component:d("/nodejs-database.html","6a2"),exact:!0,sidebar:"tutorialSidebar"},{path:"/nosql-performance-tips.html",component:d("/nosql-performance-tips.html","fd8"),exact:!0,sidebar:"tutorialSidebar"},{path:"/offline-first.html",component:d("/offline-first.html","e1b"),exact:!0,sidebar:"tutorialSidebar"},{path:"/orm.html",component:d("/orm.html","798"),exact:!0,sidebar:"tutorialSidebar"},{path:"/plugins.html",component:d("/plugins.html","f25"),exact:!0,sidebar:"tutorialSidebar"},{path:"/population.html",component:d("/population.html","b89"),exact:!0,sidebar:"tutorialSidebar"},{path:"/query-cache.html",component:d("/query-cache.html","45f"),exact:!0,sidebar:"tutorialSidebar"},{path:"/query-optimizer.html",component:d("/query-optimizer.html","bd3"),exact:!0,sidebar:"tutorialSidebar"},{path:"/questions-answers.html",component:d("/questions-answers.html","840"),exact:!0,sidebar:"tutorialSidebar"},{path:"/quickstart.html",component:d("/quickstart.html","417"),exact:!0,sidebar:"tutorialSidebar"},{path:"/react-native-database.html",component:d("/react-native-database.html","7b4"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/10.0.0.html",component:d("/releases/10.0.0.html","8ce"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/11.0.0.html",component:d("/releases/11.0.0.html","712"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/12.0.0.html",component:d("/releases/12.0.0.html","a36"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/13.0.0.html",component:d("/releases/13.0.0.html","605"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/14.0.0.html",component:d("/releases/14.0.0.html","14c"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/15.0.0.html",component:d("/releases/15.0.0.html","4dd"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/8.0.0.html",component:d("/releases/8.0.0.html","fdc"),exact:!0,sidebar:"tutorialSidebar"},{path:"/releases/9.0.0.html",component:d("/releases/9.0.0.html","f4b"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-couchdb.html",component:d("/replication-couchdb.html","6d5"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-firestore.html",component:d("/replication-firestore.html","bcb"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-graphql.html",component:d("/replication-graphql.html","a6c"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-http.html",component:d("/replication-http.html","16a"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-nats.html",component:d("/replication-nats.html","ac4"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-p2p.html",component:d("/replication-p2p.html","ec6"),exact:!0},{path:"/replication-server",component:d("/replication-server","ebc"),exact:!0},{path:"/replication-webrtc.html",component:d("/replication-webrtc.html","ff6"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication-websocket.html",component:d("/replication-websocket.html","4f9"),exact:!0,sidebar:"tutorialSidebar"},{path:"/replication.html",component:d("/replication.html","62b"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-attachment.html",component:d("/rx-attachment.html","7d7"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-collection.html",component:d("/rx-collection.html","7dc"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-database.html",component:d("/rx-database.html","e4e"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-document.html",component:d("/rx-document.html","e09"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-local-document.html",component:d("/rx-local-document.html","0db"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-query.html",component:d("/rx-query.html","2cf"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-schema.html",component:d("/rx-schema.html","671"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-denokv.html",component:d("/rx-storage-denokv.html","b6e"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-dexie.html",component:d("/rx-storage-dexie.html","bb3"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-filesystem-node.html",component:d("/rx-storage-filesystem-node.html","a57"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-foundationdb.html",component:d("/rx-storage-foundationdb.html","3c8"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-indexeddb.html",component:d("/rx-storage-indexeddb.html","631"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-localstorage-meta-optimizer.html",component:d("/rx-storage-localstorage-meta-optimizer.html","064"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-lokijs.html",component:d("/rx-storage-lokijs.html","1be"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-memory-synced.html",component:d("/rx-storage-memory-synced.html","65f"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-memory.html",component:d("/rx-storage-memory.html","c21"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-mongodb.html",component:d("/rx-storage-mongodb.html","5ad"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-opfs.html",component:d("/rx-storage-opfs.html","6f7"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-performance.html",component:d("/rx-storage-performance.html","b12"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-pouchdb.html",component:d("/rx-storage-pouchdb.html","d82"),exact:!0},{path:"/rx-storage-remote.html",component:d("/rx-storage-remote.html","5df"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-sharding.html",component:d("/rx-storage-sharding.html","b30"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-shared-worker.html",component:d("/rx-storage-shared-worker.html","0f4"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-sqlite.html",component:d("/rx-storage-sqlite.html","ad7"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage-worker.html",component:d("/rx-storage-worker.html","a4e"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rx-storage.html",component:d("/rx-storage.html","144"),exact:!0,sidebar:"tutorialSidebar"},{path:"/rxdb-tradeoffs.html",component:d("/rxdb-tradeoffs.html","5cb"),exact:!0},{path:"/schema-validation.html",component:d("/schema-validation.html","3f1"),exact:!0},{path:"/server",component:d("/server","73f"),exact:!0},{path:"/slow-indexeddb.html",component:d("/slow-indexeddb.html","a40"),exact:!0,sidebar:"tutorialSidebar"},{path:"/third-party-plugins.html",component:d("/third-party-plugins.html","549"),exact:!0,sidebar:"tutorialSidebar"},{path:"/transactions-conflicts-revisions.html",component:d("/transactions-conflicts-revisions.html","53a"),exact:!0,sidebar:"tutorialSidebar"},{path:"/tutorials/typescript.html",component:d("/tutorials/typescript.html","a33"),exact:!0,sidebar:"tutorialSidebar"},{path:"/why-nosql.html",component:d("/why-nosql.html","ad0"),exact:!0,sidebar:"tutorialSidebar"}]}]}]},{path:"*",component:d("*")}]},8934:(e,t,n)=>{"use strict";n.d(t,{_:()=>o,t:()=>i});var r=n(7294),a=n(5893);const o=r.createContext(!1);function i(e){let{children:t}=e;const[n,i]=(0,r.useState)(!1);return(0,r.useEffect)((()=>{i(!0)}),[]),(0,a.jsx)(o.Provider,{value:n,children:t})}},2679:(e,t,n)=>{"use strict";var r=n(7294),a=n(745),o=n(3727),i=n(405),l=n(412);const s=[n(6657),n(2497),n(3310),n(8320),n(2295)];var c=n(723),u=n(6550),d=n(8790),p=n(2389),f=n(5893);function m(e){let{children:t}=e;const n=(0,p.Z)();return(0,r.useEffect)((()=>{n&&(function(){const e="fixed-chat-button";if(document.getElementById(e))return;const t=document.createElement("a");t.id=e,t.href="/chat",t.target="_blank",t.innerHTML="\ud83d\udcac Community Chat",t.onclick=function(){trigger("join_chat_action",.1)};const n=document.createElement("style");n.type="text/css",n.innerText="#"+e+" {color: white;position: fixed;right: 0;bottom: 0;background-color: var(--color-top);padding-left: 17px;padding-right: 17px;padding-top: 10px;padding-bottom: 5px;text-align: center;margin-right: 50px;font-weight: bold;border-top-left-radius: 9px;border-top-right-radius: 9px;}#fixed-chat-button:hover {box-shadow: 2px 2px 13px #ca007c, -2px -1px 14px #ff009e;text-decoration: underline;z-index: 10;}",document.head.appendChild(n),document.body.appendChild(t)}(),function(){const e=[{text:"Follow",keyword:"@twitter",url:"https://twitter.com/intent/user?screen_name=rxdbjs",icon:"\ud83d\udc26"},{text:"Follow",keyword:"@LinkedIn",url:"https://www.linkedin.com/company/rxdb",icon:"[in]"},{text:"Chat",keyword:"@discord",url:"https://rxdb.info/chat",icon:"\ud83d\udcac"},{text:"Star",keyword:"@github",url:"https://rxdb.info/code",icon:"\ud83d\udc19\ud83d\udcbb"},{text:"Subscribe",keyword:"@newsletter",url:"https://rxdb.info/newsletter",icon:"\ud83d\udcf0"}];function t(e,t){e.parentNode.insertBefore(t,e.nextSibling)}const n="rxdb-call-to-action-button";function r(){console.log("set call to action button");const r=Date.now()%e.length,a=e[r],o=document.querySelector(".call-to-action");o&&o.parentNode.removeChild(o);const i=document.querySelector(".navbar__items");if(!i)return;const l=document.createElement("div");l.classList.add("call-to-action");const s=document.createElement("a");s.classList.add("hover-shadow-top"),s.id=n,s.innerHTML=a.text+' '+a.keyword+''+a.icon+"",s.href=a.url,s.target="_blank",l.append(s),t(i,l)}r()}())})),(0,f.jsx)(f.Fragment,{children:t})}var h=n(5742),g=n(2263),b=n(4996),y=n(6668),v=n(1944),w=n(4711),x=n(9727),k=n(3320),S=n(8780),E=n(197);function _(){const{i18n:{currentLocale:e,defaultLocale:t,localeConfigs:n}}=(0,g.Z)(),r=(0,w.l)(),a=n[e].htmlLang,o=e=>e.replace("-","_");return(0,f.jsxs)(h.Z,{children:[Object.entries(n).map((e=>{let[t,{htmlLang:n}]=e;return(0,f.jsx)("link",{rel:"alternate",href:r.createUrl({locale:t,fullyQualified:!0}),hrefLang:n},t)})),(0,f.jsx)("link",{rel:"alternate",href:r.createUrl({locale:t,fullyQualified:!0}),hrefLang:"x-default"}),(0,f.jsx)("meta",{property:"og:locale",content:o(a)}),Object.values(n).filter((e=>a!==e.htmlLang)).map((e=>(0,f.jsx)("meta",{property:"og:locale:alternate",content:o(e.htmlLang)},`meta-og-${e.htmlLang}`)))]})}function C(e){let{permalink:t}=e;const{siteConfig:{url:n}}=(0,g.Z)(),r=function(){const{siteConfig:{url:e,baseUrl:t,trailingSlash:n}}=(0,g.Z)(),{pathname:r}=(0,u.TH)();return e+(0,S.applyTrailingSlash)((0,b.Z)(r),{trailingSlash:n,baseUrl:t})}(),a=t?`${n}${t}`:r;return(0,f.jsxs)(h.Z,{children:[(0,f.jsx)("meta",{property:"og:url",content:a}),(0,f.jsx)("link",{rel:"canonical",href:a})]})}function T(){const{i18n:{currentLocale:e}}=(0,g.Z)(),{metadata:t,image:n}=(0,y.L)();return(0,f.jsxs)(f.Fragment,{children:[(0,f.jsxs)(h.Z,{children:[(0,f.jsx)("meta",{name:"twitter:card",content:"summary_large_image"}),(0,f.jsx)("body",{className:x.h})]}),n&&(0,f.jsx)(v.d,{image:n}),(0,f.jsx)(C,{}),(0,f.jsx)(_,{}),(0,f.jsx)(E.Z,{tag:k.HX,locale:e}),(0,f.jsx)(h.Z,{children:t.map(((e,t)=>(0,f.jsx)("meta",{...e},t)))})]})}const j=new Map;function N(e){if(j.has(e.pathname))return{...e,pathname:j.get(e.pathname)};if((0,d.f)(c.Z,e.pathname).some((e=>{let{route:t}=e;return!0===t.exact})))return j.set(e.pathname,e.pathname),e;const t=e.pathname.trim().replace(/(?:\/index)?\.html$/,"")||"/";return j.set(e.pathname,t),{...e,pathname:t}}var R=n(8934),A=n(8940),L=n(469);function P(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r{const r=t.default?.[e]??t[e];return r?.(...n)}));return()=>a.forEach((e=>e?.()))}const O=function(e){let{children:t,location:n,previousLocation:r}=e;return(0,L.Z)((()=>{r!==n&&(!function(e){let{location:t,previousLocation:n}=e;if(!n)return;const r=t.pathname===n.pathname,a=t.hash===n.hash,o=t.search===n.search;if(r&&a&&!o)return;const{hash:i}=t;if(i){const e=decodeURIComponent(i.substring(1)),t=document.getElementById(e);t?.scrollIntoView()}else window.scrollTo(0,0)}({location:n,previousLocation:r}),P("onRouteDidUpdate",{previousLocation:r,location:n}))}),[r,n]),t};function I(e){const t=Array.from(new Set([e,decodeURI(e)])).map((e=>(0,d.f)(c.Z,e))).flat();return Promise.all(t.map((e=>e.route.component.preload?.())))}class D extends r.Component{previousLocation;routeUpdateCleanupCb;constructor(e){super(e),this.previousLocation=null,this.routeUpdateCleanupCb=l.Z.canUseDOM?P("onRouteUpdate",{previousLocation:null,location:this.props.location}):()=>{},this.state={nextRouteHasLoaded:!0}}shouldComponentUpdate(e,t){if(e.location===this.props.location)return t.nextRouteHasLoaded;const n=e.location;return this.previousLocation=this.props.location,this.setState({nextRouteHasLoaded:!1}),this.routeUpdateCleanupCb=P("onRouteUpdate",{previousLocation:this.previousLocation,location:n}),I(n.pathname).then((()=>{this.routeUpdateCleanupCb(),this.setState({nextRouteHasLoaded:!0})})).catch((e=>{console.warn(e),window.location.reload()})),!1}render(){const{children:e,location:t}=this.props;return(0,f.jsx)(O,{previousLocation:this.previousLocation,location:t,children:(0,f.jsx)(u.AW,{location:t,render:()=>e})})}}const M=D,F="__docusaurus-base-url-issue-banner-container",z="__docusaurus-base-url-issue-banner",B="__docusaurus-base-url-issue-banner-suggestion-container";function $(e){return`\ndocument.addEventListener('DOMContentLoaded', function maybeInsertBanner() {\n var shouldInsert = typeof window['docusaurus'] === 'undefined';\n shouldInsert && insertBanner();\n});\n\nfunction insertBanner() {\n var bannerContainer = document.createElement('div');\n bannerContainer.id = '${F}';\n var bannerHtml = ${JSON.stringify(function(e){return`\n
\n

Your Docusaurus site did not load properly.

\n

A very common reason is a wrong site baseUrl configuration.

\n

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

\n

We suggest trying baseUrl =

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