diff --git a/CHANGELOG.md b/CHANGELOG.md index 966ad4958e8..4b69b216916 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ -### 16.0.0-beta.1 (25 November 2024) +### 16.0.0-beta.2 (25 November 2024) 🚀 **RxDB v16 is released** diff --git a/dist/cjs/plugin-helpers.js b/dist/cjs/plugin-helpers.js index a021c9dcad8..c94af0d6b6e 100644 --- a/dist/cjs/plugin-helpers.js +++ b/dist/cjs/plugin-helpers.js @@ -72,7 +72,8 @@ validatorKey) { isError: true, documentId, writeRow: row, - validationErrors + validationErrors, + schema: instance.schema }); } else { continueWrites.push(row); diff --git a/dist/cjs/plugin-helpers.js.map b/dist/cjs/plugin-helpers.js.map index d97d1760a29..4dae831ba1c 100644 --- a/dist/cjs/plugin-helpers.js.map +++ b/dist/cjs/plugin-helpers.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin-helpers.js","names":["_operators","require","_rxSchemaHelper","_index","_rxjs","VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","VALIDATOR_CACHE","getFromMapOrCreate","initValidator","schema","JSON","stringify","args","Object","assign","storage","name","createStorageInstance","params","instance","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","validatorCached","requestIdleCallbackIfAvailable","oldBulkWrite","bulkWrite","bind","documentWrites","context","errors","continueWrites","forEach","row","documentId","document","validationErrors","length","push","status","isError","writeRow","writePromise","Promise","resolve","error","success","then","writeResult","validationError","wrapRxStorageInstance","originalSchema","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","v","toStorage","docData","fromStorage","errorFromStorage","ret","flatClone","documentInDb","previous","processingChangesCount$","BehaviorSubject","wrappedInstance","databaseName","internals","cleanup","options","close","collectionName","count","remove","originalStorageInstance","useRows","all","map","undefined","promises","err","firstValueFrom","pipe","filter","query","preparedQuery","queryResult","documents","doc","getAttachmentData","attachmentId","digest","data","findDocumentsById","ids","deleted","findResult","getChangedDocumentsSince","limit","checkpoint","result","d","changeStream","tap","next","getValue","mergeMap","eventBulk","useEvents","events","event","documentData","previousDocumentData","ev","operation","isLocal","id"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { filter, mergeMap, tap } from 'rxjs/operators';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper.ts';\nimport { WrappedRxStorageInstance } from './rx-storage-helper.ts';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxValidationError,\n RxStorageWriteErrorConflict,\n MaybePromise\n} from './types/index.d.ts';\nimport {\n flatClone,\n getFromMapOrCreate,\n requestIdleCallbackIfAvailable\n} from './plugins/utils/index.ts';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\n/**\n * Returns the validation errors.\n * If document is fully valid, returns an empty array.\n */\ntype ValidatorFunction = (docData: RxDocumentData) => RxValidationError[];\n\n/**\n * cache the validators by the schema string\n * so we can reuse them when multiple collections have the same schema\n *\n * Notice: to make it easier and not dependent on a hash function,\n * we use the plain json string.\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n const VALIDATOR_CACHE = getFromMapOrCreate(\n VALIDATOR_CACHE_BY_VALIDATOR_KEY,\n validatorKey,\n () => new Map()\n );\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n return getFromMapOrCreate(\n VALIDATOR_CACHE,\n JSON.stringify(schema),\n () => getValidator(schema)\n );\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n name: 'validate-' + validatorKey + '-' + args.storage.name,\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n const errors: RxStorageWriteError[] = [];\n const continueWrites: typeof documentWrites = [];\n documentWrites.forEach(row => {\n const documentId: string = row.document[primaryPath] as any;\n const validationErrors = validatorCached(row.document);\n if (validationErrors.length > 0) {\n errors.push({\n status: 422,\n isError: true,\n documentId,\n writeRow: row,\n validationErrors\n });\n } else {\n continueWrites.push(row);\n }\n });\n const writePromise: Promise> = continueWrites.length > 0 ?\n oldBulkWrite(continueWrites, context) :\n Promise.resolve({ error: [], success: [] });\n return writePromise.then(writeResult => {\n errors.forEach(validationError => {\n writeResult.error.push(validationError);\n });\n return writeResult;\n });\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n originalSchema: RxJsonSchema>,\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => MaybePromise>,\n modifyFromStorage: (docData: RxDocumentData) => MaybePromise>,\n modifyAttachmentFromStorage: (attachmentData: string) => MaybePromise = (v) => v\n): WrappedRxStorageInstance {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if ((ret as RxStorageWriteErrorConflict).documentInDb) {\n (ret as RxStorageWriteErrorConflict).documentInDb = await fromStorage((ret as RxStorageWriteErrorConflict).documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n\n const processingChangesCount$ = new BehaviorSubject(0);\n\n const wrappedInstance: WrappedRxStorageInstance = {\n databaseName: instance.databaseName,\n internals: instance.internals,\n cleanup: instance.cleanup.bind(instance),\n options: instance.options,\n close: instance.close.bind(instance),\n schema: originalSchema,\n collectionName: instance.collectionName,\n count: instance.count.bind(instance),\n remove: instance.remove.bind(instance),\n originalStorageInstance: instance,\n bulkWrite: async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await instance.bulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n error: []\n };\n const promises: Promise[] = [];\n writeResult.error.forEach(error => {\n promises.push(\n errorFromStorage(error).then(err => ret.error.push(err))\n );\n });\n await Promise.all(promises);\n\n /**\n * By definition, all change events must be emitted\n * BEFORE the write call resolves.\n * To ensure that even when the modifiers are async,\n * we wait here until the processing queue is empty.\n */\n await firstValueFrom(\n processingChangesCount$.pipe(\n filter(v => v === 0)\n )\n );\n return ret;\n },\n query: (preparedQuery) => {\n return instance.query(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n },\n getAttachmentData: async (\n documentId: string,\n attachmentId: string,\n digest: string\n ) => {\n let data = await instance.getAttachmentData(documentId, attachmentId, digest);\n data = await modifyAttachmentFromStorage(data);\n return data;\n },\n findDocumentsById: (ids, deleted) => {\n return instance.findDocumentsById(ids, deleted)\n .then(async (findResult) => {\n const ret: RxDocumentData[] = [];\n await Promise.all(\n findResult\n .map(async (doc) => {\n ret.push(await fromStorage(doc));\n })\n );\n return ret;\n });\n },\n getChangedDocumentsSince: !instance.getChangedDocumentsSince ? undefined : (limit, checkpoint) => {\n return ((instance as any).getChangedDocumentsSince)(limit, checkpoint)\n .then(async (result: any) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map((d: any) => fromStorage(d))\n )\n };\n });\n },\n changeStream: () => {\n return instance.changeStream().pipe(\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() + 1)),\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n documentId: event.documentId,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n }),\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() - 1))\n );\n },\n };\n\n return wrappedInstance;\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AACA,IAAAC,eAAA,GAAAD,OAAA;AAmBA,IAAAE,MAAA,GAAAF,OAAA;AAKA,IAAAG,KAAA,GAAAH,OAAA;AASA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMI,gCAA6E,GA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C;QACD,IAAMtD,GAAoE,GAAG;UACzEyD,EAAE,EAAET,SAAS,CAACS,EAAE;UAChBP,MAAM,EAAED,SAAS;UACjBT,UAAU,EAAEQ,SAAS,CAACR,UAAU;UAChCvE,OAAO,EAAE+E,SAAS,CAAC/E;QACvB,CAAC;QACD,OAAO+B,GAAG;MACd,CAAC,CAAC,EACF,IAAA4C,cAAG,EAAC,MAAMxC,uBAAuB,CAACyC,IAAI,CAACzC,uBAAuB,CAAC0C,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAClF,CAAC;IACL;EACJ,CAAC;EAED,OAAOxC,eAAe;AAC1B","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"plugin-helpers.js","names":["_operators","require","_rxSchemaHelper","_index","_rxjs","VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","VALIDATOR_CACHE","getFromMapOrCreate","initValidator","schema","JSON","stringify","args","Object","assign","storage","name","createStorageInstance","params","instance","primaryPath","getPrimaryFieldOfPrimaryKey","primaryKey","validatorCached","requestIdleCallbackIfAvailable","oldBulkWrite","bulkWrite","bind","documentWrites","context","errors","continueWrites","forEach","row","documentId","document","validationErrors","length","push","status","isError","writeRow","writePromise","Promise","resolve","error","success","then","writeResult","validationError","wrapRxStorageInstance","originalSchema","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","v","toStorage","docData","fromStorage","errorFromStorage","ret","flatClone","documentInDb","previous","processingChangesCount$","BehaviorSubject","wrappedInstance","databaseName","internals","cleanup","options","close","collectionName","count","remove","originalStorageInstance","useRows","all","map","undefined","promises","err","firstValueFrom","pipe","filter","query","preparedQuery","queryResult","documents","doc","getAttachmentData","attachmentId","digest","data","findDocumentsById","ids","deleted","findResult","getChangedDocumentsSince","limit","checkpoint","result","d","changeStream","tap","next","getValue","mergeMap","eventBulk","useEvents","events","event","documentData","previousDocumentData","ev","operation","isLocal","id"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { filter, mergeMap, tap } from 'rxjs/operators';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper.ts';\nimport { WrappedRxStorageInstance } from './rx-storage-helper.ts';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxValidationError,\n RxStorageWriteErrorConflict,\n MaybePromise\n} from './types/index.d.ts';\nimport {\n flatClone,\n getFromMapOrCreate,\n requestIdleCallbackIfAvailable\n} from './plugins/utils/index.ts';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\n/**\n * Returns the validation errors.\n * If document is fully valid, returns an empty array.\n */\ntype ValidatorFunction = (docData: RxDocumentData) => RxValidationError[];\n\n/**\n * cache the validators by the schema string\n * so we can reuse them when multiple collections have the same schema\n *\n * Notice: to make it easier and not dependent on a hash function,\n * we use the plain json string.\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n const VALIDATOR_CACHE = getFromMapOrCreate(\n VALIDATOR_CACHE_BY_VALIDATOR_KEY,\n validatorKey,\n () => new Map()\n );\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n return getFromMapOrCreate(\n VALIDATOR_CACHE,\n JSON.stringify(schema),\n () => getValidator(schema)\n );\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n name: 'validate-' + validatorKey + '-' + args.storage.name,\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n const errors: RxStorageWriteError[] = [];\n const continueWrites: typeof documentWrites = [];\n documentWrites.forEach(row => {\n const documentId: string = row.document[primaryPath] as any;\n const validationErrors = validatorCached(row.document);\n if (validationErrors.length > 0) {\n errors.push({\n status: 422,\n isError: true,\n documentId,\n writeRow: row,\n validationErrors,\n schema: instance.schema\n });\n } else {\n continueWrites.push(row);\n }\n });\n const writePromise: Promise> = continueWrites.length > 0 ?\n oldBulkWrite(continueWrites, context) :\n Promise.resolve({ error: [], success: [] });\n return writePromise.then(writeResult => {\n errors.forEach(validationError => {\n writeResult.error.push(validationError);\n });\n return writeResult;\n });\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n originalSchema: RxJsonSchema>,\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => MaybePromise>,\n modifyFromStorage: (docData: RxDocumentData) => MaybePromise>,\n modifyAttachmentFromStorage: (attachmentData: string) => MaybePromise = (v) => v\n): WrappedRxStorageInstance {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if ((ret as RxStorageWriteErrorConflict).documentInDb) {\n (ret as RxStorageWriteErrorConflict).documentInDb = await fromStorage((ret as RxStorageWriteErrorConflict).documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n\n const processingChangesCount$ = new BehaviorSubject(0);\n\n const wrappedInstance: WrappedRxStorageInstance = {\n databaseName: instance.databaseName,\n internals: instance.internals,\n cleanup: instance.cleanup.bind(instance),\n options: instance.options,\n close: instance.close.bind(instance),\n schema: originalSchema,\n collectionName: instance.collectionName,\n count: instance.count.bind(instance),\n remove: instance.remove.bind(instance),\n originalStorageInstance: instance,\n bulkWrite: async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await instance.bulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n error: []\n };\n const promises: Promise[] = [];\n writeResult.error.forEach(error => {\n promises.push(\n errorFromStorage(error).then(err => ret.error.push(err))\n );\n });\n await Promise.all(promises);\n\n /**\n * By definition, all change events must be emitted\n * BEFORE the write call resolves.\n * To ensure that even when the modifiers are async,\n * we wait here until the processing queue is empty.\n */\n await firstValueFrom(\n processingChangesCount$.pipe(\n filter(v => v === 0)\n )\n );\n return ret;\n },\n query: (preparedQuery) => {\n return instance.query(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n },\n getAttachmentData: async (\n documentId: string,\n attachmentId: string,\n digest: string\n ) => {\n let data = await instance.getAttachmentData(documentId, attachmentId, digest);\n data = await modifyAttachmentFromStorage(data);\n return data;\n },\n findDocumentsById: (ids, deleted) => {\n return instance.findDocumentsById(ids, deleted)\n .then(async (findResult) => {\n const ret: RxDocumentData[] = [];\n await Promise.all(\n findResult\n .map(async (doc) => {\n ret.push(await fromStorage(doc));\n })\n );\n return ret;\n });\n },\n getChangedDocumentsSince: !instance.getChangedDocumentsSince ? undefined : (limit, checkpoint) => {\n return ((instance as any).getChangedDocumentsSince)(limit, checkpoint)\n .then(async (result: any) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map((d: any) => fromStorage(d))\n )\n };\n });\n },\n changeStream: () => {\n return instance.changeStream().pipe(\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() + 1)),\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n documentId: event.documentId,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n }),\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() - 1))\n );\n },\n };\n\n return wrappedInstance;\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AACA,IAAAC,eAAA,GAAAD,OAAA;AAmBA,IAAAE,MAAA,GAAAF,OAAA;AAKA,IAAAG,KAAA,GAAAH,OAAA;AASA;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMI,gCAA6E,GAAG,IAAIC,GAAG,CAAC,CAAC;;AAE/F;AACA;AACA;AACA;AACO,SAASC,6BAA6BA;AACzC;AACJ;AACA;AACA;AACIC,YAA8D;AAC9D;AACJ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P,MAAM,EAAED,SAAS;UACjBT,UAAU,EAAEQ,SAAS,CAACR,UAAU;UAChCvE,OAAO,EAAE+E,SAAS,CAAC/E;QACvB,CAAC;QACD,OAAO+B,GAAG;MACd,CAAC,CAAC,EACF,IAAA4C,cAAG,EAAC,MAAMxC,uBAAuB,CAACyC,IAAI,CAACzC,uBAAuB,CAAC0C,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAClF,CAAC;IACL;EACJ,CAAC;EAED,OAAOxC,eAAe;AAC1B","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/pipeline/rx-pipeline.js b/dist/cjs/plugins/pipeline/rx-pipeline.js index 7bd20f7602e..71b91b76ddd 100644 --- a/dist/cjs/plugins/pipeline/rx-pipeline.js +++ b/dist/cjs/plugins/pipeline/rx-pipeline.js @@ -14,6 +14,12 @@ var _docCache = require("../../doc-cache.js"); var _rxDatabaseInternalStore = require("../../rx-database-internal-store.js"); var _flaggedFunctions = require("./flagged-functions.js"); var RxPipeline = exports.RxPipeline = /*#__PURE__*/function () { + /** + * The handler of the pipeline must never throw. + * If it did anyway, the pipeline will be stuck and always + * throw the previous error on all operations. + */ + function RxPipeline(identifier, source, destination, handler, batchSize = 100) { this.processQueue = _index.PROMISE_RESOLVE_VOID; this.subs = []; @@ -68,49 +74,64 @@ var RxPipeline = exports.RxPipeline = /*#__PURE__*/function () { this.toRun = this.toRun - 1; var done = false; var _loop = async function () { - var checkpointDoc = await getCheckpointDoc(_this2); - var checkpoint = checkpointDoc ? checkpointDoc.data.checkpoint : undefined; - var docsSinceResult = await (0, _rxStorageHelper.getChangedDocumentsSince)(_this2.source.storageInstance, _this2.batchSize, checkpoint); - var lastTime = checkpointDoc ? checkpointDoc.data.lastDocTime : 0; - if (docsSinceResult.documents.length > 0) { - var rxDocuments = (0, _docCache.mapDocumentsDataToCacheDocs)(_this2.source._docCache, docsSinceResult.documents); - var _this = _this2; + var checkpointDoc = await getCheckpointDoc(_this2); + var checkpoint = checkpointDoc ? checkpointDoc.data.checkpoint : undefined; + var docsSinceResult = await (0, _rxStorageHelper.getChangedDocumentsSince)(_this2.source.storageInstance, _this2.batchSize, checkpoint); + var lastTime = checkpointDoc ? checkpointDoc.data.lastDocTime : 0; + if (docsSinceResult.documents.length > 0) { + var rxDocuments = (0, _docCache.mapDocumentsDataToCacheDocs)(_this2.source._docCache, docsSinceResult.documents); + var _this = _this2; - // const o: any = {}; - // eval(` - // async function ${this.secretFunctionName}(docs){ const x = await _this.handler(docs); return x; } - // o.${this.secretFunctionName} = ${this.secretFunctionName}; - // `); - // await o[this.secretFunctionName](rxDocuments); + // const o: any = {}; + // eval(` + // async function ${this.secretFunctionName}(docs){ const x = await _this.handler(docs); return x; } + // o.${this.secretFunctionName} = ${this.secretFunctionName}; + // `); + // await o[this.secretFunctionName](rxDocuments); - var fnKey = (0, _flaggedFunctions.blockFlaggedFunctionKey)(); - _this2.secretFunctionName = fnKey; - try { - await _flaggedFunctions.FLAGGED_FUNCTIONS[fnKey](() => _this.handler(rxDocuments)); - } finally { - (0, _flaggedFunctions.releaseFlaggedFunctionKey)(fnKey); + var fnKey = (0, _flaggedFunctions.blockFlaggedFunctionKey)(); + _this2.secretFunctionName = fnKey; + try { + await _flaggedFunctions.FLAGGED_FUNCTIONS[fnKey](() => _this.handler(rxDocuments)); + } catch (err) { + _this2.error = err; + } finally { + (0, _flaggedFunctions.releaseFlaggedFunctionKey)(fnKey); + } + if (_this2.error) { + return { + v: void 0 + }; + } + lastTime = (0, _index.ensureNotFalsy)((0, _index.lastOfArray)(docsSinceResult.documents))._meta.lwt; } - lastTime = (0, _index.ensureNotFalsy)((0, _index.lastOfArray)(docsSinceResult.documents))._meta.lwt; - } - if (!_this2.destination.closed) { - await setCheckpointDoc(_this2, { - checkpoint: docsSinceResult.checkpoint, - lastDocTime: lastTime - }, checkpointDoc); - } - if (docsSinceResult.documents.length < _this2.batchSize) { - done = true; - } - }; - while (!done && !this.stopped && !this.destination.closed && !this.source.closed) { - await _loop(); + if (!_this2.destination.closed) { + await setCheckpointDoc(_this2, { + checkpoint: docsSinceResult.checkpoint, + lastDocTime: lastTime + }, checkpointDoc); + } + if (docsSinceResult.documents.length < _this2.batchSize) { + done = true; + } + }, + _ret; + while (!done && !this.stopped && !this.destination.closed && !this.source.closed && !this.error) { + _ret = await _loop(); + if (_ret) return _ret.v; } }); }; _proto.awaitIdle = async function awaitIdle() { + if (this.error) { + throw this.error; + } var done = false; while (!done) { await this.processQueue; + if (this.error) { + throw this.error; + } if (this.lastProcessedDocTime.getValue() >= this.lastSourceDocTime.getValue()) { done = true; } else { @@ -119,6 +140,7 @@ var RxPipeline = exports.RxPipeline = /*#__PURE__*/function () { } }; _proto.close = async function close() { + await this.processQueue; this.stopped = true; this.destination.awaitBeforeReads.delete(this.waitBeforeWriteFn); this.subs.forEach(s => s.unsubscribe()); diff --git a/dist/cjs/plugins/pipeline/rx-pipeline.js.map b/dist/cjs/plugins/pipeline/rx-pipeline.js.map index dc57789f1b5..7fcd93e451f 100644 --- a/dist/cjs/plugins/pipeline/rx-pipeline.js.map +++ b/dist/cjs/plugins/pipeline/rx-pipeline.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-pipeline.js","names":["_rxjs","require","_index","_rxStorageHelper","_docCache","_rxDatabaseInternalStore","_flaggedFunctions","RxPipeline","exports","identifier","source","destination","handler","batchSize","processQueue","PROMISE_RESOLVE_VOID","subs","stopped","toRun","lastSourceDocTime","BehaviorSubject","lastProcessedDocTime","somethingChanged","Subject","secretFunctionName","randomToken","waitBeforeWriteFn","stack","Error","includes","awaitIdle","checkpointId","onClose","push","close","awaitBeforeReads","add","eventBulks$","subscribe","bulk","next","events","documentData","_meta","lwt","database","internalStore","changeStream","eventBulk","index","length","event","context","INTERNAL_CONTEXT_PIPELINE_CHECKPOINT","key","data","lastDocTime","_proto","prototype","trigger","_this2","then","done","_loop","checkpointDoc","getCheckpointDoc","checkpoint","undefined","docsSinceResult","getChangedDocumentsSince","storageInstance","lastTime","documents","rxDocuments","mapDocumentsDataToCacheDocs","_this","fnKey","blockFlaggedFunctionKey","FLAGGED_FUNCTIONS","releaseFlaggedFunctionKey","ensureNotFalsy","lastOfArray","closed","setCheckpointDoc","getValue","firstValueFrom","delete","forEach","s","unsubscribe","remove","insternalStore","newDoc","clone","_deleted","writeResult","bulkWrite","previous","document","error","pipeline","getPrimaryKeyOfInternalDocument","results","findDocumentsById","result","newCheckpoint","_attachments","now","_rev","createRevision","token","id","addPipeline","options","waitForLeadership","startPromise","pipe","filter","isLocal"],"sources":["../../../../src/plugins/pipeline/rx-pipeline.ts"],"sourcesContent":["import {\n BehaviorSubject,\n Subject,\n Subscription,\n filter,\n firstValueFrom,\n race\n} from 'rxjs';\nimport type {\n InternalStoreDocType,\n RxCollection,\n RxDocument,\n RxDocumentData\n} from '../../types';\nimport type {\n CheckpointDocData,\n RxPipelineHandler,\n RxPipelineOptions\n} from './types';\nimport {\n PROMISE_RESOLVE_VOID,\n clone,\n createRevision,\n ensureNotFalsy,\n lastOfArray,\n nameFunction,\n now,\n promiseWait,\n randomToken\n} from '../utils/index.ts';\nimport { getChangedDocumentsSince } from '../../rx-storage-helper.ts';\nimport { mapDocumentsDataToCacheDocs } from '../../doc-cache.ts';\nimport { INTERNAL_CONTEXT_PIPELINE_CHECKPOINT, getPrimaryKeyOfInternalDocument } from '../../rx-database-internal-store.ts';\nimport { FLAGGED_FUNCTIONS, blockFlaggedFunctionKey, releaseFlaggedFunctionKey } from './flagged-functions.ts';\n\nexport class RxPipeline {\n processQueue = PROMISE_RESOLVE_VOID;\n subs: Subscription[] = [];\n stopped: boolean = false;\n\n toRun = 1;\n checkpointId: string;\n\n lastSourceDocTime = new BehaviorSubject(-1);\n lastProcessedDocTime = new BehaviorSubject(0);\n somethingChanged = new Subject();\n\n\n secretFunctionName = 'tx_fn_' + randomToken(10)\n\n waitBeforeWriteFn = async () => {\n const stack = new Error().stack;\n if (stack && (\n stack.includes(this.secretFunctionName)\n )) {\n } else {\n await this.awaitIdle();\n }\n }\n\n constructor(\n public readonly identifier: string,\n public readonly source: RxCollection,\n public readonly destination: RxCollection,\n public readonly handler: RxPipelineHandler,\n public readonly batchSize = 100\n ) {\n this.checkpointId = 'rx-pipeline-' + identifier;\n this.source.onClose.push(() => this.close());\n this.destination.awaitBeforeReads.add(this.waitBeforeWriteFn);\n this.subs.push(\n this.source.eventBulks$.subscribe((bulk) => {\n this.lastSourceDocTime.next(bulk.events[0].documentData._meta.lwt);\n this.somethingChanged.next({});\n })\n );\n this.subs.push(\n this.destination.database.internalStore\n .changeStream()\n .subscribe(eventBulk => {\n const events = eventBulk.events;\n for (let index = 0; index < events.length; index++) {\n const event = events[index];\n if (\n event.documentData.context === INTERNAL_CONTEXT_PIPELINE_CHECKPOINT &&\n event.documentData.key === this.checkpointId\n ) {\n this.lastProcessedDocTime.next(event.documentData.data.lastDocTime);\n this.somethingChanged.next({});\n }\n }\n })\n );\n }\n\n trigger() {\n /**\n * Do not stack up too many\n * so that fast writes to the source collection\n * do not block anything too long.\n */\n if (this.toRun > 2) {\n return;\n }\n this.toRun = this.toRun + 1;\n\n this.processQueue = this.processQueue.then(async () => {\n this.toRun = this.toRun - 1;\n\n let done = false;\n while (\n !done &&\n !this.stopped &&\n !this.destination.closed &&\n !this.source.closed\n ) {\n const checkpointDoc = await getCheckpointDoc(this);\n const checkpoint = checkpointDoc ? checkpointDoc.data.checkpoint : undefined;\n const docsSinceResult = await getChangedDocumentsSince(\n this.source.storageInstance,\n this.batchSize,\n checkpoint\n );\n\n let lastTime = checkpointDoc ? checkpointDoc.data.lastDocTime : 0;\n if (docsSinceResult.documents.length > 0) {\n const rxDocuments = mapDocumentsDataToCacheDocs(this.source._docCache, docsSinceResult.documents);\n const _this = this;\n\n\n\n // const o: any = {};\n // eval(`\n // async function ${this.secretFunctionName}(docs){ const x = await _this.handler(docs); return x; }\n // o.${this.secretFunctionName} = ${this.secretFunctionName};\n // `);\n // await o[this.secretFunctionName](rxDocuments);\n\n const fnKey = blockFlaggedFunctionKey();\n this.secretFunctionName = fnKey;\n try {\n await FLAGGED_FUNCTIONS[fnKey](() => _this.handler(rxDocuments));\n } finally {\n releaseFlaggedFunctionKey(fnKey);\n }\n\n lastTime = ensureNotFalsy(lastOfArray(docsSinceResult.documents))._meta.lwt;\n }\n if (!this.destination.closed) {\n await setCheckpointDoc(this, { checkpoint: docsSinceResult.checkpoint, lastDocTime: lastTime }, checkpointDoc);\n }\n if (docsSinceResult.documents.length < this.batchSize) {\n done = true;\n }\n }\n });\n }\n\n async awaitIdle() {\n let done = false;\n while (!done) {\n await this.processQueue;\n if (this.lastProcessedDocTime.getValue() >= this.lastSourceDocTime.getValue()) {\n done = true;\n } else {\n await firstValueFrom(this.somethingChanged);\n }\n }\n }\n\n async close() {\n this.stopped = true;\n this.destination.awaitBeforeReads.delete(this.waitBeforeWriteFn);\n this.subs.forEach(s => s.unsubscribe());\n await this.processQueue;\n }\n\n /**\n * Remove the pipeline and all metadata which it has stored\n */\n async remove() {\n const insternalStore = this.destination.database.internalStore;\n const checkpointDoc = await getCheckpointDoc(this);\n if (checkpointDoc) {\n const newDoc: RxDocumentData = clone(checkpointDoc);\n newDoc._deleted = true;\n const writeResult = await insternalStore.bulkWrite([{\n previous: checkpointDoc,\n document: newDoc,\n }], 'rx-pipeline');\n if (writeResult.error.length > 0) {\n throw writeResult.error;\n }\n }\n return this.close();\n }\n}\n\n\nexport async function getCheckpointDoc(\n pipeline: RxPipeline\n): Promise> | undefined> {\n const insternalStore = pipeline.destination.database.internalStore;\n const checkpointId = getPrimaryKeyOfInternalDocument(\n pipeline.checkpointId,\n INTERNAL_CONTEXT_PIPELINE_CHECKPOINT\n );\n const results = await insternalStore.findDocumentsById([checkpointId], false);\n const result: RxDocumentData = results[0];\n if (result) {\n return result;\n } else {\n return undefined;\n }\n}\n\nexport async function setCheckpointDoc(\n pipeline: RxPipeline,\n newCheckpoint: CheckpointDocData,\n previous?: RxDocumentData\n): Promise {\n const insternalStore = pipeline.destination.database.internalStore;\n const newDoc: RxDocumentData> = {\n _attachments: {},\n _deleted: false,\n _meta: {\n lwt: now()\n },\n _rev: createRevision(pipeline.destination.database.token, previous),\n context: INTERNAL_CONTEXT_PIPELINE_CHECKPOINT,\n data: newCheckpoint,\n id: getPrimaryKeyOfInternalDocument(\n pipeline.checkpointId,\n INTERNAL_CONTEXT_PIPELINE_CHECKPOINT\n ),\n key: pipeline.checkpointId\n };\n\n const writeResult = await insternalStore.bulkWrite([{\n previous,\n document: newDoc,\n }], 'rx-pipeline');\n if (writeResult.error.length > 0) {\n throw writeResult.error;\n }\n}\n\n\nexport async function addPipeline(\n this: RxCollection,\n options: RxPipelineOptions\n): Promise> {\n const pipeline = new RxPipeline(\n options.identifier,\n this,\n options.destination,\n options.handler,\n options.batchSize\n );\n const waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const startPromise = waitForLeadership ? this.database.waitForLeadership() : PROMISE_RESOLVE_VOID;\n startPromise.then(() => {\n pipeline.trigger();\n pipeline.subs.push(\n this.eventBulks$.pipe(\n filter(bulk => {\n if (pipeline.stopped) {\n return false;\n }\n return !bulk.isLocal;\n })\n ).subscribe(() => pipeline.trigger())\n );\n });\n\n return pipeline;\n}\n"],"mappings":";;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAmBA,IAAAC,MAAA,GAAAD,OAAA;AAWA,IAAAE,gBAAA,GAAAF,OAAA;AACA,IAAAG,SAAA,GAAAH,OAAA;AACA,IAAAI,wBAAA,GAAAJ,OAAA;AACA,IAAAK,iBAAA,GAAAL,OAAA;AAA+G,IAElGM,UAAU,GAAAC,OAAA,CAAAD,UAAA;EAyBnB,SAAAA,WACoBE,UAAkB,EAClBC,MAA+B,EAC/BC,WAA8B,EAC9BC,OAAqC,EACrCC,SAAS,GAAG,GAAG,EACjC;IAAA,KA9BFC,YAAY,GAAGC,2BAAoB;IAAA,KACnCC,IAAI,GAAmB,EAAE;IAAA,KACzBC,OAAO,GAAY,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,CACL,CAAC,CAAChF,SAAS,CAAC,MAAM8D,QAAQ,CAACzC,OAAO,CAAC,CAAC,CACxC,CAAC;EACL,CAAC,CAAC;EAEF,OAAOyC,QAAQ;AACnB","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-pipeline.js","names":["_rxjs","require","_index","_rxStorageHelper","_docCache","_rxDatabaseInternalStore","_flaggedFunctions","RxPipeline","exports","identifier","source","destination","handler","batchSize","processQueue","PROMISE_RESOLVE_VOID","subs","stopped","toRun","lastSourceDocTime","BehaviorSubject","lastProcessedDocTime","somethingChanged","Subject","secretFunctionName","randomToken","waitBeforeWriteFn","stack","Error","includes","awaitIdle","checkpointId","onClose","push","close","awaitBeforeReads","add","eventBulks$","subscribe","bulk","next","events","documentData","_meta","lwt","database","internalStore","changeStream","eventBulk","index","length","event","context","INTERNAL_CONTEXT_PIPELINE_CHECKPOINT","key","data","lastDocTime","_proto","prototype","trigger","_this2","then","done","_loop","checkpointDoc","getCheckpointDoc","checkpoint","undefined","docsSinceResult","getChangedDocumentsSince","storageInstance","lastTime","documents","rxDocuments","mapDocumentsDataToCacheDocs","_this","fnKey","blockFlaggedFunctionKey","FLAGGED_FUNCTIONS","err","error","releaseFlaggedFunctionKey","v","ensureNotFalsy","lastOfArray","closed","setCheckpointDoc","_ret","getValue","firstValueFrom","delete","forEach","s","unsubscribe","remove","insternalStore","newDoc","clone","_deleted","writeResult","bulkWrite","previous","document","pipeline","getPrimaryKeyOfInternalDocument","results","findDocumentsById","result","newCheckpoint","_attachments","now","_rev","createRevision","token","id","addPipeline","options","waitForLeadership","startPromise","pipe","filter","isLocal"],"sources":["../../../../src/plugins/pipeline/rx-pipeline.ts"],"sourcesContent":["import {\n BehaviorSubject,\n Subject,\n Subscription,\n filter,\n firstValueFrom,\n race\n} from 'rxjs';\nimport type {\n InternalStoreDocType,\n RxCollection,\n RxDocument,\n RxDocumentData\n} from '../../types';\nimport type {\n CheckpointDocData,\n RxPipelineHandler,\n RxPipelineOptions\n} from './types';\nimport {\n PROMISE_RESOLVE_VOID,\n clone,\n createRevision,\n ensureNotFalsy,\n lastOfArray,\n nameFunction,\n now,\n promiseWait,\n randomToken\n} from '../utils/index.ts';\nimport { getChangedDocumentsSince } from '../../rx-storage-helper.ts';\nimport { mapDocumentsDataToCacheDocs } from '../../doc-cache.ts';\nimport { INTERNAL_CONTEXT_PIPELINE_CHECKPOINT, getPrimaryKeyOfInternalDocument } from '../../rx-database-internal-store.ts';\nimport { FLAGGED_FUNCTIONS, blockFlaggedFunctionKey, releaseFlaggedFunctionKey } from './flagged-functions.ts';\n\nexport class RxPipeline {\n processQueue = PROMISE_RESOLVE_VOID;\n subs: Subscription[] = [];\n stopped: boolean = false;\n\n toRun = 1;\n checkpointId: string;\n\n lastSourceDocTime = new BehaviorSubject(-1);\n lastProcessedDocTime = new BehaviorSubject(0);\n somethingChanged = new Subject();\n\n\n secretFunctionName = 'tx_fn_' + randomToken(10)\n\n waitBeforeWriteFn = async () => {\n const stack = new Error().stack;\n if (stack && (\n stack.includes(this.secretFunctionName)\n )) {\n } else {\n await this.awaitIdle();\n }\n }\n\n /**\n * The handler of the pipeline must never throw.\n * If it did anyway, the pipeline will be stuck and always\n * throw the previous error on all operations.\n */\n error: any;\n\n constructor(\n public readonly identifier: string,\n public readonly source: RxCollection,\n public readonly destination: RxCollection,\n public readonly handler: RxPipelineHandler,\n public readonly batchSize = 100\n ) {\n this.checkpointId = 'rx-pipeline-' + identifier;\n this.source.onClose.push(() => this.close());\n this.destination.awaitBeforeReads.add(this.waitBeforeWriteFn);\n this.subs.push(\n this.source.eventBulks$.subscribe((bulk) => {\n this.lastSourceDocTime.next(bulk.events[0].documentData._meta.lwt);\n this.somethingChanged.next({});\n })\n );\n this.subs.push(\n this.destination.database.internalStore\n .changeStream()\n .subscribe(eventBulk => {\n const events = eventBulk.events;\n for (let index = 0; index < events.length; index++) {\n const event = events[index];\n if (\n event.documentData.context === INTERNAL_CONTEXT_PIPELINE_CHECKPOINT &&\n event.documentData.key === this.checkpointId\n ) {\n this.lastProcessedDocTime.next(event.documentData.data.lastDocTime);\n this.somethingChanged.next({});\n }\n }\n })\n );\n }\n\n trigger() {\n /**\n * Do not stack up too many\n * so that fast writes to the source collection\n * do not block anything too long.\n */\n if (this.toRun > 2) {\n return;\n }\n this.toRun = this.toRun + 1;\n\n this.processQueue = this.processQueue.then(async () => {\n this.toRun = this.toRun - 1;\n\n let done = false;\n while (\n !done &&\n !this.stopped &&\n !this.destination.closed &&\n !this.source.closed &&\n !this.error\n ) {\n const checkpointDoc = await getCheckpointDoc(this);\n const checkpoint = checkpointDoc ? checkpointDoc.data.checkpoint : undefined;\n const docsSinceResult = await getChangedDocumentsSince(\n this.source.storageInstance,\n this.batchSize,\n checkpoint\n );\n\n let lastTime = checkpointDoc ? checkpointDoc.data.lastDocTime : 0;\n if (docsSinceResult.documents.length > 0) {\n const rxDocuments = mapDocumentsDataToCacheDocs(this.source._docCache, docsSinceResult.documents);\n const _this = this;\n\n\n\n // const o: any = {};\n // eval(`\n // async function ${this.secretFunctionName}(docs){ const x = await _this.handler(docs); return x; }\n // o.${this.secretFunctionName} = ${this.secretFunctionName};\n // `);\n // await o[this.secretFunctionName](rxDocuments);\n\n const fnKey = blockFlaggedFunctionKey();\n this.secretFunctionName = fnKey;\n try {\n await FLAGGED_FUNCTIONS[fnKey](() => _this.handler(rxDocuments));\n } catch (err: any) {\n this.error = err;\n } finally {\n releaseFlaggedFunctionKey(fnKey);\n }\n\n if (this.error) {\n return;\n }\n\n lastTime = ensureNotFalsy(lastOfArray(docsSinceResult.documents))._meta.lwt;\n }\n if (!this.destination.closed) {\n await setCheckpointDoc(this, { checkpoint: docsSinceResult.checkpoint, lastDocTime: lastTime }, checkpointDoc);\n }\n if (docsSinceResult.documents.length < this.batchSize) {\n done = true;\n }\n }\n });\n }\n\n async awaitIdle() {\n if (this.error) {\n throw this.error;\n }\n let done = false;\n while (!done) {\n await this.processQueue;\n if (this.error) {\n throw this.error;\n }\n if (this.lastProcessedDocTime.getValue() >= this.lastSourceDocTime.getValue()) {\n done = true;\n } else {\n await firstValueFrom(this.somethingChanged);\n }\n }\n }\n\n async close() {\n await this.processQueue;\n this.stopped = true;\n this.destination.awaitBeforeReads.delete(this.waitBeforeWriteFn);\n this.subs.forEach(s => s.unsubscribe());\n await this.processQueue;\n }\n\n /**\n * Remove the pipeline and all metadata which it has stored\n */\n async remove() {\n const insternalStore = this.destination.database.internalStore;\n const checkpointDoc = await getCheckpointDoc(this);\n if (checkpointDoc) {\n const newDoc: RxDocumentData = clone(checkpointDoc);\n newDoc._deleted = true;\n const writeResult = await insternalStore.bulkWrite([{\n previous: checkpointDoc,\n document: newDoc,\n }], 'rx-pipeline');\n if (writeResult.error.length > 0) {\n throw writeResult.error;\n }\n }\n return this.close();\n }\n}\n\n\nexport async function getCheckpointDoc(\n pipeline: RxPipeline\n): Promise> | undefined> {\n const insternalStore = pipeline.destination.database.internalStore;\n const checkpointId = getPrimaryKeyOfInternalDocument(\n pipeline.checkpointId,\n INTERNAL_CONTEXT_PIPELINE_CHECKPOINT\n );\n const results = await insternalStore.findDocumentsById([checkpointId], false);\n const result: RxDocumentData = results[0];\n if (result) {\n return result;\n } else {\n return undefined;\n }\n}\n\nexport async function setCheckpointDoc(\n pipeline: RxPipeline,\n newCheckpoint: CheckpointDocData,\n previous?: RxDocumentData\n): Promise {\n const insternalStore = pipeline.destination.database.internalStore;\n const newDoc: RxDocumentData> = {\n _attachments: {},\n _deleted: false,\n _meta: {\n lwt: now()\n },\n _rev: createRevision(pipeline.destination.database.token, previous),\n context: INTERNAL_CONTEXT_PIPELINE_CHECKPOINT,\n data: newCheckpoint,\n id: getPrimaryKeyOfInternalDocument(\n pipeline.checkpointId,\n INTERNAL_CONTEXT_PIPELINE_CHECKPOINT\n ),\n key: pipeline.checkpointId\n };\n\n const writeResult = await insternalStore.bulkWrite([{\n previous,\n document: newDoc,\n }], 'rx-pipeline');\n if (writeResult.error.length > 0) {\n throw writeResult.error;\n }\n}\n\n\nexport async function addPipeline(\n this: RxCollection,\n options: RxPipelineOptions\n): Promise> {\n const pipeline = new RxPipeline(\n options.identifier,\n this,\n options.destination,\n options.handler,\n options.batchSize\n );\n const waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const startPromise = waitForLeadership ? this.database.waitForLeadership() : PROMISE_RESOLVE_VOID;\n startPromise.then(() => {\n pipeline.trigger();\n pipeline.subs.push(\n this.eventBulks$.pipe(\n filter(bulk => {\n if (pipeline.stopped) {\n return false;\n }\n return !bulk.isLocal;\n })\n ).subscribe(() => pipeline.trigger())\n );\n });\n\n return pipeline;\n}\n"],"mappings":";;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAmBA,IAAAC,MAAA,GAAAD,OAAA;AAWA,IAAAE,gBAAA,GAAAF,OAAA;AACA,IAAAG,SAAA,GAAAH,OAAA;AACA,IAAAI,wBAAA,GAAAJ,OAAA;AACA,IAAAK,iBAAA,GAAAL,OAAA;AAA+G,IAElGM,UAAU,GAAAC,OAAA,CAAAD,UAAA;EAyBnB;AACJ;AACA;AACA;AACA;;EAGI,SAAAA,WACoBE,UAAkB,EAClBC,MAA+B,EAC/BC,WAA8B,EAC9BC,OAAqC,EACrCC,SAAS,GAAG,GAAG,EACjC;IAAA,KArCFC,YAAY,GAAGC,2BAAoB;IAAA,KACnCC,IAAI,GAAmB,EAAE;IAAA,KACzBC,OAAO,GAAY,KAAK;IAAA,KAExBC,KAAK,GAAG,CAAC;IAAA,KAGTC,iBAAiB,GAAG,IAAIC,qBAAe,CAAC,CAAC,CAAC,CAAC;IAAA,KAC3CC,oBAAoB,GAAG,IAAID,qBAAe,CAAC,CAAC,CAAC;IAAA,KAC7CE,gBAAgB,GAAG,IAAIC,aAAO,CAAC,CAAC;IAAA,KAGhCC,kBAAkB,GAAG,QAAQ,GAAG,IAAAC,kBAAW,EAAC,EAAE,CAAC;IAAA,KAE/CC,iBAAiB,GAAG,YAAY;MAC5B,IAAM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X,IAAIgE,QAAQ,CAACtF,OAAO,EAAE;QAClB,OAAO,KAAK;MAChB;MACA,OAAO,CAACsB,IAAI,CAACkF,OAAO;IACxB,CAAC,CACL,CAAC,CAACnF,SAAS,CAAC,MAAMiE,QAAQ,CAAC5C,OAAO,CAAC,CAAC,CACxC,CAAC;EACL,CAAC,CAAC;EAEF,OAAO4C,QAAQ;AACnB","ignoreList":[]} \ 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 38b6e6030b7..67c26829054 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 = '16.0.0-beta.1'; +var RXDB_VERSION = exports.RXDB_VERSION = '16.0.0-beta.2'; //# 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 4fea49a7ef4..37334bf1209 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 = '16.0.0-beta.1';\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACO,IAAMA,YAAY,GAAAC,OAAA,CAAAD,YAAA,GAAG,eAAe","ignoreList":[]} \ 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 = '16.0.0-beta.2';\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACO,IAAMA,YAAY,GAAAC,OAAA,CAAAD,YAAA,GAAG,eAAe","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/rx-collection.js.map b/dist/cjs/rx-collection.js.map index 5162633be96..3202b4ae515 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","_incrementalWrite","_rxDocument","_overwritable","_defaultConflictHandler","_rxChangeEvent","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","awaitBeforeReads","_incrementalUpsertQueues","Map","synced","hooks","_subs","createQueryCache","$","checkpoint$","eventBulks$","onClose","closed","onRemove","_applyHookFunctions","asRxCollection","pipe","filter","changeEventBulk","collectionName","_proto","prototype","prepare","getWrappedStorageInstance","jsonSchema","IncrementalWriteQueue","primaryPath","newData","oldData","beforeDocumentUpdateWrite","result","_runHooks","mergeMap","rxChangeEventBulkToRxChangeEvents","map","checkpoint","createChangeEventBuffer","documentConstructor","DocumentCache","bulk","isLocal","events","docData","getRxDocumentConstructor","createNewRxDocument","listenToRemoveSub","internalStore","changeStream","key","version","found","find","event","documentData","context","operation","subscribe","close","Promise","all","fn","push","databaseStorageToken","storageToken","subDocs","eventBulk","id","internal","databaseToken","token","$emit","PROMISE_RESOLVE_VOID","cleanup","_minimumDeletedTime","ensureRxCollectionIsNotClosed","pluginMissing","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","throwIfIsStorageWriteError","insertResult","ensureNotFalsy","success","docsData","length","ids","insertRows","hasHooks","useDocData","fillObjectDataBeforeInsert","then","add","document","Array","index","size","newRxError","collection","args","documents","results","bulkWrite","rxDocuments","ret","getWrittenDocumentsFromBulkWriteResponse","mapDocumentsDataToCacheDocs","docsMap","forEach","row","doc","set","get","primary","bulkRemove","idsOrDocs","rxDocumentMap","findByIds","exec","d","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","flatClone","_deleted","previous","deletedRxDocuments","successIds","getCachedRxDocument","bulkUpsert","insertData","useJsonByDocId","useJson","slice","err","status","documentId","writeData","getFromMapOrThrow","docDataInDb","documentInDb","getCachedRxDocuments","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","queryObj","runPluginHooks","op","_getDefaultQuery","query","createRxQuery","findOne","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addPipeline","_options","addHook","when","fun","parallel","newRxTypeError","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","promiseSeries","_runHooksSync","promiseWait","time","res","timeout","setTimeout","delete","PROMISE_RESOLVE_FALSE","clearTimeout","requestIdlePromise","sub","unsubscribe","collections","runAsyncPluginHooks","remove","removeCollectionStorages","storage","password","hashFunction","_createClass2","default","cE","colProto","Object","getPrototypeOf","fnName","ucfirst","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","overwritable","isDevMode","createRxCollectionStorageInstance","entries","funName","defineProperty","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 ensureRxCollectionIsNotClosed\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,\n 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 getRxDocumentConstructor\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n getWrittenDocumentsFromBulkWriteResponse,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxPipeline, RxPipelineOptions } from './plugins/pipeline/index.ts';\nimport { defaultConflictHandler } from './replication-protocol/default-conflict-handler.ts';\nimport { rxChangeEventBulkToRxChangeEvents } from './rx-change-event.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; },\n Reactivity = any\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n\n /**\n * Before reads, all these methods are awaited. Used to \"block\" reads\n * depending on other processes, like when the RxPipeline is running.\n */\n public readonly awaitBeforeReads = new Set<() => MaybePromise>();\n\n constructor(\n public readonly 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 if (database) { // might be falsy on pseudoInstance\n this.eventBulks$ = database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name)\n );\n } else { }\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 * Internally only use eventBulks$\n * Do not use .$ or .observable$ because that has to transform\n * the events which decreases performance.\n */\n public readonly eventBulks$: Observable> = {} as any;\n\n\n /**\n * When the collection is closed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onClose: (() => MaybePromise)[] = [];\n public closed = false;\n\n public onRemove: (() => MaybePromise)[] = [];\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 this.$ = this.eventBulks$.pipe(\n mergeMap(changeEventBulk => rxChangeEventBulkToRxChangeEvents(changeEventBulk)),\n );\n this.checkpoint$ = this.eventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n let documentConstructor: any;\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.eventBulks$.pipe(\n filter(bulk => !bulk.isLocal),\n map(bulk => bulk.events)\n ),\n docData => {\n if (!documentConstructor) {\n documentConstructor = getRxDocumentConstructor(this.asRxCollection);\n }\n return createNewRxDocument(this.asRxCollection, documentConstructor, docData);\n }\n );\n\n\n const listenToRemoveSub = this.database.internalStore.changeStream().pipe(\n filter(bulk => {\n const key = this.name + '-' + this.schema.version;\n const found = bulk.events.find(event => {\n return (\n event.documentData.context === 'collection' &&\n event.documentData.key === key &&\n event.operation === 'DELETE'\n );\n });\n return !!found;\n })\n ).subscribe(async () => {\n await this.close();\n await Promise.all(this.onRemove.map(fn => fn()));\n });\n this._subs.push(listenToRemoveSub);\n\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 isLocal: false,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events,\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n 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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\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\n const ids = new Set();\n\n /**\n * This code is a bit redundant for better performance.\n * Instead of iterating multiple times,\n * we directly transform the input to a write-row array.\n */\n let insertRows: BulkWriteRow[];\n if (this.hasHooks('pre', 'insert')) {\n insertRows = await Promise.all(\n docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return this._runHooks('pre', 'insert', useDocData)\n .then(() => {\n ids.add((useDocData as any)[primaryPath]);\n return { document: useDocData };\n });\n })\n );\n } else {\n insertRows = new Array(docsData.length);\n const schema = this.schema;\n for (let index = 0; index < docsData.length; index++) {\n const docData = docsData[index];\n const useDocData = fillObjectDataBeforeInsert(schema, docData);\n ids.add((useDocData as any)[primaryPath]);\n insertRows[index] = { document: useDocData };\n }\n }\n\n\n if (ids.size !== docsData.length) {\n throw newRxError('COL22', {\n collection: this.name,\n args: {\n documents: docsData\n }\n });\n }\n\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n\n /**\n * Often the user does not need to access the RxDocuments of the bulkInsert() call.\n * So we transform the data to RxDocuments only if needed to use less CPU performance.\n */\n let rxDocuments: RxDocument[];\n const collection = this;\n const ret = {\n get success() {\n if (!rxDocuments) {\n const success = getWrittenDocumentsFromBulkWriteResponse(\n collection.schema.primaryPath,\n insertRows,\n results\n );\n rxDocuments = mapDocumentsDataToCacheDocs(collection._docCache, success);\n }\n return rxDocuments;\n },\n error: results.error\n };\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n insertRows.forEach(row => {\n const doc = row.document;\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n ret.success.map(doc => {\n return this._runHooks(\n 'post',\n 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return ret;\n }\n\n async bulkRemove(\n /**\n * You can either remove the documents by their ids\n * or by directly providing the RxDocument instances\n * if you have them already. This improves performance a bit.\n */\n idsOrDocs: string[] | RxDocument[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n ensureRxCollectionIsNotClosed(this);\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (idsOrDocs.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n let rxDocumentMap: Map>;\n if (typeof idsOrDocs[0] === 'string') {\n rxDocumentMap = await this.findByIds(idsOrDocs as string[]).exec();\n } else {\n rxDocumentMap = new Map();\n (idsOrDocs as RxDocument[]).forEach(d => rxDocumentMap.set(d.primary, d));\n }\n\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\n const success = getWrittenDocumentsFromBulkWriteResponse(\n this.schema.primaryPath,\n removeDocs,\n results\n );\n\n const deletedRxDocuments: RxDocument[] = [];\n const successIds: string[] = success.map(d => {\n const id = d[primaryPath] as string;\n const doc = this._docCache.getCachedRxDocument(d);\n deletedRxDocuments.push(doc);\n return id;\n });\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\n return {\n success: deletedRxDocuments,\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 ensureRxCollectionIsNotClosed(this);\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.getCachedRxDocuments([docDataInDb])[0];\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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[],\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n\n runPluginHooks('prePrepareRxQuery', {\n op: 'find',\n queryObj,\n collection: this\n });\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this as any);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n\n runPluginHooks('prePrepareRxQuery', {\n op: 'findOne',\n queryObj,\n collection: this\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 // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this as any);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n findByIds(\n ids: string[]\n ): RxQuery<\n RxDocumentType,\n Map>,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\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 addPipeline(_options: RxPipelineOptions): Promise> {\n throw pluginMissing('pipeline');\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 /**\n * Performance shortcut\n * so that we not have to build the empty object.\n */\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return false;\n }\n\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 if (!this.hasHooks(when, key)) {\n return;\n }\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 closed\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 async close(): Promise {\n if (this.closed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n\n await Promise.all(this.onClose.map(fn => fn()));\n\n /**\n * Settings closed = 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.closed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.close();\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(() => 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('postCloseRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.close();\n await Promise.all(this.onRemove.map(fn => fn()));\n /**\n * TODO here we should pass the already existing\n * storage instances instead of creating new ones.\n */\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.getCachedRxDocuments([docDataFromCache])[0],\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 as Error));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof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CAACzI,UAAU,EAAEwI,OAAO,EAAE;UACvC1H,GAAG,EAAEA,CAAA,KAAOiE,GAAG,CAASK,IAAI,CAACpF,UAAU;QAC3C,CAAC,CAAC;MACN,CAAC,CAAC;MAEN,IAAIM,GAAG,GAAGxC,2BAAoB;MAC9B,IAAI+J,WAAW,IAAI7H,UAAU,CAACxH,MAAM,CAACgE,OAAO,KAAK,CAAC,EAAE;QAChD8D,GAAG,GAAGN,UAAU,CAACzB,cAAc,CAAC,CAAC;MACrC;MACA,OAAO+B,GAAG;IACd,CAAC,CAAC,CACDb,IAAI,CAAC,MAAM;MACR,IAAAkE,qBAAc,EAAC,oBAAoB,EAAE;QACjC3D,UAAU;QACV0I,OAAO,EAAE;UACLnQ,IAAI;UACJC,MAAM;UACNY,eAAe;UACfV,uBAAuB;UACvBC,mBAAmB;UACnBC,OAAO;UACPC,WAAW;UACXC,OAAO;UACPC,sBAAsB;UACtB+O,cAAc;UACd7O;QACJ;MACJ,CAAC,CAAC;MACF,OAAO+G,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAIC2I,KAAK,CAACnG,GAAG,IAAI;MACV,OAAOpJ,eAAe,CAAC4D,KAAK,CAAC,CAAC,CACzByC,IAAI,CAAC,MAAMxC,OAAO,CAAC2L,MAAM,CAACpG,GAAY,CAAC,CAAC;IACjD,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEO,SAASqG,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAY1Q,gBAAgB;AAC1C","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-collection.js","names":["_rxjs","require","_index","_rxCollectionHelper","_rxQuery","_rxError","_docCache","_queryCache","_changeEventBuffer","_hooks","_rxDocumentPrototypeMerge","_rxStorageHelper","_incrementalWrite","_rxDocument","_overwritable","_defaultConflictHandler","_rxChangeEvent","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","awaitBeforeReads","_incrementalUpsertQueues","Map","synced","hooks","_subs","createQueryCache","$","checkpoint$","eventBulks$","onClose","closed","onRemove","_applyHookFunctions","asRxCollection","pipe","filter","changeEventBulk","collectionName","_proto","prototype","prepare","getWrappedStorageInstance","jsonSchema","IncrementalWriteQueue","primaryPath","newData","oldData","beforeDocumentUpdateWrite","result","_runHooks","mergeMap","rxChangeEventBulkToRxChangeEvents","map","checkpoint","createChangeEventBuffer","documentConstructor","DocumentCache","bulk","isLocal","events","docData","getRxDocumentConstructor","createNewRxDocument","listenToRemoveSub","internalStore","changeStream","key","version","found","find","event","documentData","context","operation","subscribe","close","Promise","all","fn","push","databaseStorageToken","storageToken","subDocs","eventBulk","id","internal","databaseToken","token","$emit","PROMISE_RESOLVE_VOID","cleanup","_minimumDeletedTime","ensureRxCollectionIsNotClosed","pluginMissing","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","throwIfIsStorageWriteError","insertResult","ensureNotFalsy","success","docsData","length","ids","insertRows","hasHooks","useDocData","fillObjectDataBeforeInsert","then","add","document","Array","index","size","newRxError","collection","args","documents","results","bulkWrite","rxDocuments","ret","getWrittenDocumentsFromBulkWriteResponse","mapDocumentsDataToCacheDocs","docsMap","forEach","row","doc","set","get","primary","bulkRemove","idsOrDocs","rxDocumentMap","findByIds","exec","d","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","flatClone","_deleted","previous","deletedRxDocuments","successIds","getCachedRxDocument","bulkUpsert","insertData","useJsonByDocId","useJson","slice","err","status","documentId","writeData","getFromMapOrThrow","docDataInDb","documentInDb","getCachedRxDocuments","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","queryObj","runPluginHooks","op","_getDefaultQuery","query","createRxQuery","findOne","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addPipeline","_options","addHook","when","fun","parallel","newRxTypeError","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","promiseSeries","_runHooksSync","promiseWait","time","res","timeout","setTimeout","delete","PROMISE_RESOLVE_FALSE","clearTimeout","requestIdlePromise","sub","unsubscribe","collections","runAsyncPluginHooks","remove","removeCollectionStorages","storage","password","hashFunction","_createClass2","default","cE","colProto","Object","getPrototypeOf","fnName","ucfirst","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","overwritable","isDevMode","createRxCollectionStorageInstance","entries","funName","defineProperty","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 ensureRxCollectionIsNotClosed\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,\n 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 getRxDocumentConstructor\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n getWrittenDocumentsFromBulkWriteResponse,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxPipeline, RxPipelineOptions } from './plugins/pipeline/index.ts';\nimport { defaultConflictHandler } from './replication-protocol/default-conflict-handler.ts';\nimport { rxChangeEventBulkToRxChangeEvents } from './rx-change-event.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; },\n Reactivity = any\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n\n /**\n * Before reads, all these methods are awaited. Used to \"block\" reads\n * depending on other processes, like when the RxPipeline is running.\n */\n public readonly awaitBeforeReads = new Set<() => MaybePromise>();\n\n constructor(\n public readonly 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 if (database) { // might be falsy on pseudoInstance\n this.eventBulks$ = database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name)\n );\n } else { }\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 * Internally only use eventBulks$\n * Do not use .$ or .observable$ because that has to transform\n * the events which decreases performance.\n */\n public readonly eventBulks$: Observable> = {} as any;\n\n\n /**\n * When the collection is closed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onClose: (() => MaybePromise)[] = [];\n public closed = false;\n\n public onRemove: (() => MaybePromise)[] = [];\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 this.$ = this.eventBulks$.pipe(\n mergeMap(changeEventBulk => rxChangeEventBulkToRxChangeEvents(changeEventBulk)),\n );\n this.checkpoint$ = this.eventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n let documentConstructor: any;\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.eventBulks$.pipe(\n filter(bulk => !bulk.isLocal),\n map(bulk => bulk.events)\n ),\n docData => {\n if (!documentConstructor) {\n documentConstructor = getRxDocumentConstructor(this.asRxCollection);\n }\n return createNewRxDocument(this.asRxCollection, documentConstructor, docData);\n }\n );\n\n\n const listenToRemoveSub = this.database.internalStore.changeStream().pipe(\n filter(bulk => {\n const key = this.name + '-' + this.schema.version;\n const found = bulk.events.find(event => {\n return (\n event.documentData.context === 'collection' &&\n event.documentData.key === key &&\n event.operation === 'DELETE'\n );\n });\n return !!found;\n })\n ).subscribe(async () => {\n await this.close();\n await Promise.all(this.onRemove.map(fn => fn()));\n });\n this._subs.push(listenToRemoveSub);\n\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 isLocal: false,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events,\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n 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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\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 as any);\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 ensureRxCollectionIsNotClosed(this);\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\n const ids = new Set();\n\n /**\n * This code is a bit redundant for better performance.\n * Instead of iterating multiple times,\n * we directly transform the input to a write-row array.\n */\n let insertRows: BulkWriteRow[];\n if (this.hasHooks('pre', 'insert')) {\n insertRows = await Promise.all(\n docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return this._runHooks('pre', 'insert', useDocData)\n .then(() => {\n ids.add((useDocData as any)[primaryPath]);\n return { document: useDocData };\n });\n })\n );\n } else {\n insertRows = new Array(docsData.length);\n const schema = this.schema;\n for (let index = 0; index < docsData.length; index++) {\n const docData = docsData[index];\n const useDocData = fillObjectDataBeforeInsert(schema, docData);\n ids.add((useDocData as any)[primaryPath]);\n insertRows[index] = { document: useDocData };\n }\n }\n\n\n if (ids.size !== docsData.length) {\n throw newRxError('COL22', {\n collection: this.name,\n args: {\n documents: docsData\n }\n });\n }\n\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n\n /**\n * Often the user does not need to access the RxDocuments of the bulkInsert() call.\n * So we transform the data to RxDocuments only if needed to use less CPU performance.\n */\n let rxDocuments: RxDocument[];\n const collection = this;\n const ret = {\n get success() {\n if (!rxDocuments) {\n const success = getWrittenDocumentsFromBulkWriteResponse(\n collection.schema.primaryPath,\n insertRows,\n results\n );\n rxDocuments = mapDocumentsDataToCacheDocs(collection._docCache, success);\n }\n return rxDocuments;\n },\n error: results.error\n };\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n insertRows.forEach(row => {\n const doc = row.document;\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n ret.success.map(doc => {\n return this._runHooks(\n 'post',\n 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return ret;\n }\n\n async bulkRemove(\n /**\n * You can either remove the documents by their ids\n * or by directly providing the RxDocument instances\n * if you have them already. This improves performance a bit.\n */\n idsOrDocs: string[] | RxDocument[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n ensureRxCollectionIsNotClosed(this);\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (idsOrDocs.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n let rxDocumentMap: Map>;\n if (typeof idsOrDocs[0] === 'string') {\n rxDocumentMap = await this.findByIds(idsOrDocs as string[]).exec();\n } else {\n rxDocumentMap = new Map();\n (idsOrDocs as RxDocument[]).forEach(d => rxDocumentMap.set(d.primary, d));\n }\n\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\n const success = getWrittenDocumentsFromBulkWriteResponse(\n this.schema.primaryPath,\n removeDocs,\n results\n );\n\n const deletedRxDocuments: RxDocument[] = [];\n const successIds: string[] = success.map(d => {\n const id = d[primaryPath] as string;\n const doc = this._docCache.getCachedRxDocument(d);\n deletedRxDocuments.push(doc);\n return id;\n });\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\n return {\n success: deletedRxDocuments,\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 ensureRxCollectionIsNotClosed(this);\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.getCachedRxDocuments([docDataInDb])[0];\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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[],\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n\n runPluginHooks('prePrepareRxQuery', {\n op: 'find',\n queryObj,\n collection: this\n });\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this as any);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n\n runPluginHooks('prePrepareRxQuery', {\n op: 'findOne',\n queryObj,\n collection: this\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 // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this as any);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n findByIds(\n ids: string[]\n ): RxQuery<\n RxDocumentType,\n Map>,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\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 addPipeline(_options: RxPipelineOptions): Promise> {\n throw pluginMissing('pipeline');\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 /**\n * Performance shortcut\n * so that we not have to build the empty object.\n */\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return false;\n }\n\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 if (!this.hasHooks(when, key)) {\n return;\n }\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 closed\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 async close(): Promise {\n if (this.closed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n\n await Promise.all(this.onClose.map(fn => fn()));\n\n /**\n * Settings closed = 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.closed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.close();\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(() => 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('postCloseRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.close();\n await Promise.all(this.onRemove.map(fn => fn()));\n /**\n * TODO here we should pass the already existing\n * storage instances instead of creating new ones.\n */\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.getCachedRxDocuments([docDataFromCache])[0],\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 as Error));\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;AAMA,IAAAG,QAAA,GAAAH,OAAA;AAIA,IAAAI,QAAA,GAAAJ,OAAA;AAOA,IAAAK,SAAA,GAAAL,OAAA;AAIA,IAAAM,WAAA,GAAAN,OAAA;AAKA,IAAAO,kBAAA,GAAAP,OAAA;AAIA,IAAAQ,MAAA,GAAAR,OAAA;AA6CA,IAAAS,yBAAA,GAAAT,OAAA;AAIA,IAAAU,gBAAA,GAAAV,OAAA;AAMA,IAAAW,iBAAA,GAAAX,OAAA;AACA,IAAAY,WAAA,GAAAZ,OAAA;AACA,IAAAa,aAAA,GAAAb,OAAA;AAEA,IAAAc,uBAAA,GAAA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AAO;UACPC,WAAW;UACXC,OAAO;UACPC,sBAAsB;UACtB+O,cAAc;UACd7O;QACJ;MACJ,CAAC,CAAC;MACF,OAAO+G,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAIC2I,KAAK,CAACnG,GAAG,IAAI;MACV,OAAOpJ,eAAe,CAAC4D,KAAK,CAAC,CAAC,CACzByC,IAAI,CAAC,MAAMxC,OAAO,CAAC2L,MAAM,CAACpG,GAAY,CAAC,CAAC;IACjD,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEO,SAASqG,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAY1Q,gBAAgB;AAC1C","ignoreList":[]} \ 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 e3af896cace..cecd57b142f 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 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 storage?: string;\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 url?: string;\n extensions?: Record;\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":"","ignoreList":[]} \ 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 storage?: string;\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 url?: string;\n extensions?: Record;\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 * For easier debugging,\n * we directly put the schema into the error.\n */\n schema: RxJsonSchema>;\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":"","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugin-helpers.js b/dist/esm/plugin-helpers.js index e8c7306197a..e84a8c76af4 100644 --- a/dist/esm/plugin-helpers.js +++ b/dist/esm/plugin-helpers.js @@ -66,7 +66,8 @@ validatorKey) { isError: true, documentId, writeRow: row, - validationErrors + validationErrors, + schema: instance.schema }); } else { continueWrites.push(row); diff --git a/dist/esm/plugin-helpers.js.map b/dist/esm/plugin-helpers.js.map index e599aedb2c5..8ee9f8dd1ff 100644 --- a/dist/esm/plugin-helpers.js.map +++ b/dist/esm/plugin-helpers.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin-helpers.js","names":["filter","mergeMap","tap","getPrimaryFieldOfPrimaryKey","flatClone","getFromMapOrCreate","requestIdleCallbackIfAvailable","BehaviorSubject","firstValueFrom","VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","VALIDATOR_CACHE","initValidator","schema","JSON","stringify","args","Object","assign","storage","name","createStorageInstance","params","instance","primaryPath","primaryKey","validatorCached","oldBulkWrite","bulkWrite","bind","documentWrites","context","errors","continueWrites","forEach","row","documentId","document","validationErrors","length","push","status","isError","writeRow","writePromise","Promise","resolve","error","success","then","writeResult","validationError","wrapRxStorageInstance","originalSchema","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","v","toStorage","docData","fromStorage","errorFromStorage","ret","documentInDb","previous","processingChangesCount$","wrappedInstance","databaseName","internals","cleanup","options","close","collectionName","count","remove","originalStorageInstance","useRows","all","map","undefined","promises","err","pipe","query","preparedQuery","queryResult","documents","doc","getAttachmentData","attachmentId","digest","data","findDocumentsById","ids","deleted","findResult","getChangedDocumentsSince","limit","checkpoint","result","d","changeStream","next","getValue","eventBulk","useEvents","events","event","documentData","previousDocumentData","ev","operation","isLocal","id"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { filter, mergeMap, tap } from 'rxjs/operators';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper.ts';\nimport { WrappedRxStorageInstance } from './rx-storage-helper.ts';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxValidationError,\n RxStorageWriteErrorConflict,\n MaybePromise\n} from './types/index.d.ts';\nimport {\n flatClone,\n getFromMapOrCreate,\n requestIdleCallbackIfAvailable\n} from './plugins/utils/index.ts';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\n/**\n * Returns the validation errors.\n * If document is fully valid, returns an empty array.\n */\ntype ValidatorFunction = (docData: RxDocumentData) => RxValidationError[];\n\n/**\n * cache the validators by the schema string\n * so we can reuse them when multiple collections have the same schema\n *\n * Notice: to make it easier and not dependent on a hash function,\n * we use the plain json string.\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n const VALIDATOR_CACHE = getFromMapOrCreate(\n VALIDATOR_CACHE_BY_VALIDATOR_KEY,\n validatorKey,\n () => new Map()\n );\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n return getFromMapOrCreate(\n VALIDATOR_CACHE,\n JSON.stringify(schema),\n () => getValidator(schema)\n );\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n name: 'validate-' + validatorKey + '-' + args.storage.name,\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n const errors: RxStorageWriteError[] = [];\n const continueWrites: typeof documentWrites = [];\n documentWrites.forEach(row => {\n const documentId: string = row.document[primaryPath] as any;\n const validationErrors = validatorCached(row.document);\n if (validationErrors.length > 0) {\n errors.push({\n status: 422,\n isError: true,\n documentId,\n writeRow: row,\n validationErrors\n });\n } else {\n continueWrites.push(row);\n }\n });\n const writePromise: Promise> = continueWrites.length > 0 ?\n oldBulkWrite(continueWrites, context) :\n Promise.resolve({ error: [], success: [] });\n return writePromise.then(writeResult => {\n errors.forEach(validationError => {\n writeResult.error.push(validationError);\n });\n return writeResult;\n });\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n originalSchema: RxJsonSchema>,\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => MaybePromise>,\n modifyFromStorage: (docData: RxDocumentData) => MaybePromise>,\n modifyAttachmentFromStorage: (attachmentData: string) => MaybePromise = (v) => v\n): WrappedRxStorageInstance {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if ((ret as RxStorageWriteErrorConflict).documentInDb) {\n (ret as RxStorageWriteErrorConflict).documentInDb = await fromStorage((ret as RxStorageWriteErrorConflict).documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n\n const processingChangesCount$ = new BehaviorSubject(0);\n\n const wrappedInstance: WrappedRxStorageInstance = {\n databaseName: instance.databaseName,\n internals: instance.internals,\n cleanup: instance.cleanup.bind(instance),\n options: instance.options,\n close: instance.close.bind(instance),\n schema: originalSchema,\n collectionName: instance.collectionName,\n count: instance.count.bind(instance),\n remove: instance.remove.bind(instance),\n originalStorageInstance: instance,\n bulkWrite: async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await instance.bulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n error: []\n };\n const promises: Promise[] = [];\n writeResult.error.forEach(error => {\n promises.push(\n errorFromStorage(error).then(err => ret.error.push(err))\n );\n });\n await Promise.all(promises);\n\n /**\n * By definition, all change events must be emitted\n * BEFORE the write call resolves.\n * To ensure that even when the modifiers are async,\n * we wait here until the processing queue is empty.\n */\n await firstValueFrom(\n processingChangesCount$.pipe(\n filter(v => v === 0)\n )\n );\n return ret;\n },\n query: (preparedQuery) => {\n return instance.query(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n },\n getAttachmentData: async (\n documentId: string,\n attachmentId: string,\n digest: string\n ) => {\n let data = await instance.getAttachmentData(documentId, attachmentId, digest);\n data = await modifyAttachmentFromStorage(data);\n return data;\n },\n findDocumentsById: (ids, deleted) => {\n return instance.findDocumentsById(ids, deleted)\n .then(async (findResult) => {\n const ret: RxDocumentData[] = [];\n await Promise.all(\n findResult\n .map(async (doc) => {\n ret.push(await fromStorage(doc));\n })\n );\n return ret;\n });\n },\n getChangedDocumentsSince: !instance.getChangedDocumentsSince ? undefined : (limit, checkpoint) => {\n return ((instance as any).getChangedDocumentsSince)(limit, checkpoint)\n .then(async (result: any) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map((d: any) => fromStorage(d))\n )\n };\n });\n },\n changeStream: () => {\n return instance.changeStream().pipe(\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() + 1)),\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n documentId: event.documentId,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n }),\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() - 1))\n );\n },\n };\n\n return wrappedInstance;\n}\n"],"mappings":"AAAA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,GAAG,QAAQ,gBAAgB;AACtD,SAASC,2BAA2B,QAAQ,uBAAuB;AAmBnE,SACIC,SAAS,EACTC,kBAAkB,EAClBC,8BAA8B,QAC3B,0BAA0B;AACjC,SAASC,eAAe,EAAEC,cAAc,QAAQ,MAAM;;AAStD;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,gCAA6E,GAAG,IAAIC,GAAG,CAAC,CAAC;;AAE/F;AACA;AACA;AACA;AACA,OAAO,SAASC,6BAA6BA;AACzC;AACJ;AACA;AACA;AACIC,YAA8D;AAC9D;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yE,SAAS,CAACzE;QACvB,CAAC;QACD,OAAO+B,GAAG;MACd,CAAC,CAAC,EACF/D,GAAG,CAAC,MAAMkE,uBAAuB,CAACqC,IAAI,CAACrC,uBAAuB,CAACsC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAClF,CAAC;IACL;EACJ,CAAC;EAED,OAAOrC,eAAe;AAC1B","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"plugin-helpers.js","names":["filter","mergeMap","tap","getPrimaryFieldOfPrimaryKey","flatClone","getFromMapOrCreate","requestIdleCallbackIfAvailable","BehaviorSubject","firstValueFrom","VALIDATOR_CACHE_BY_VALIDATOR_KEY","Map","wrappedValidateStorageFactory","getValidator","validatorKey","VALIDATOR_CACHE","initValidator","schema","JSON","stringify","args","Object","assign","storage","name","createStorageInstance","params","instance","primaryPath","primaryKey","validatorCached","oldBulkWrite","bulkWrite","bind","documentWrites","context","errors","continueWrites","forEach","row","documentId","document","validationErrors","length","push","status","isError","writeRow","writePromise","Promise","resolve","error","success","then","writeResult","validationError","wrapRxStorageInstance","originalSchema","modifyToStorage","modifyFromStorage","modifyAttachmentFromStorage","v","toStorage","docData","fromStorage","errorFromStorage","ret","documentInDb","previous","processingChangesCount$","wrappedInstance","databaseName","internals","cleanup","options","close","collectionName","count","remove","originalStorageInstance","useRows","all","map","undefined","promises","err","pipe","query","preparedQuery","queryResult","documents","doc","getAttachmentData","attachmentId","digest","data","findDocumentsById","ids","deleted","findResult","getChangedDocumentsSince","limit","checkpoint","result","d","changeStream","next","getValue","eventBulk","useEvents","events","event","documentData","previousDocumentData","ev","operation","isLocal","id"],"sources":["../../src/plugin-helpers.ts"],"sourcesContent":["import { filter, mergeMap, tap } from 'rxjs/operators';\nimport { getPrimaryFieldOfPrimaryKey } from './rx-schema-helper.ts';\nimport { WrappedRxStorageInstance } from './rx-storage-helper.ts';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxChangeEvent,\n RxDocumentData,\n RxDocumentWriteData,\n RxJsonSchema,\n RxStorage,\n RxStorageWriteError,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxValidationError,\n RxStorageWriteErrorConflict,\n MaybePromise\n} from './types/index.d.ts';\nimport {\n flatClone,\n getFromMapOrCreate,\n requestIdleCallbackIfAvailable\n} from './plugins/utils/index.ts';\nimport { BehaviorSubject, firstValueFrom } from 'rxjs';\n\n\ntype WrappedStorageFunction = (\n args: {\n storage: RxStorage;\n }\n) => RxStorage;\n\n/**\n * Returns the validation errors.\n * If document is fully valid, returns an empty array.\n */\ntype ValidatorFunction = (docData: RxDocumentData) => RxValidationError[];\n\n/**\n * cache the validators by the schema string\n * so we can reuse them when multiple collections have the same schema\n *\n * Notice: to make it easier and not dependent on a hash function,\n * we use the plain json string.\n */\nconst VALIDATOR_CACHE_BY_VALIDATOR_KEY: Map> = new Map();\n\n/**\n * This factory is used in the validation plugins\n * so that we can reuse the basic storage wrapping code.\n */\nexport function wrappedValidateStorageFactory(\n /**\n * Returns a method that can be used to validate\n * documents and throws when the document is not valid.\n */\n getValidator: (schema: RxJsonSchema) => ValidatorFunction,\n /**\n * A string to identify the validation library.\n */\n validatorKey: string\n): WrappedStorageFunction {\n const VALIDATOR_CACHE = getFromMapOrCreate(\n VALIDATOR_CACHE_BY_VALIDATOR_KEY,\n validatorKey,\n () => new Map()\n );\n\n function initValidator(\n schema: RxJsonSchema\n ): ValidatorFunction {\n return getFromMapOrCreate(\n VALIDATOR_CACHE,\n JSON.stringify(schema),\n () => getValidator(schema)\n );\n }\n\n return (args) => {\n return Object.assign(\n {},\n args.storage,\n {\n name: 'validate-' + validatorKey + '-' + args.storage.name,\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ) {\n const instance = await args.storage.createStorageInstance(params);\n const primaryPath = getPrimaryFieldOfPrimaryKey(params.schema.primaryKey);\n\n /**\n * Lazy initialize the validator\n * to save initial page load performance.\n * Some libraries take really long to initialize the validator\n * from the schema.\n */\n let validatorCached: ValidatorFunction;\n requestIdleCallbackIfAvailable(() => validatorCached = initValidator(params.schema));\n\n const oldBulkWrite = instance.bulkWrite.bind(instance);\n instance.bulkWrite = (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n if (!validatorCached) {\n validatorCached = initValidator(params.schema);\n }\n const errors: RxStorageWriteError[] = [];\n const continueWrites: typeof documentWrites = [];\n documentWrites.forEach(row => {\n const documentId: string = row.document[primaryPath] as any;\n const validationErrors = validatorCached(row.document);\n if (validationErrors.length > 0) {\n errors.push({\n status: 422,\n isError: true,\n documentId,\n writeRow: row,\n validationErrors,\n schema: instance.schema\n });\n } else {\n continueWrites.push(row);\n }\n });\n const writePromise: Promise> = continueWrites.length > 0 ?\n oldBulkWrite(continueWrites, context) :\n Promise.resolve({ error: [], success: [] });\n return writePromise.then(writeResult => {\n errors.forEach(validationError => {\n writeResult.error.push(validationError);\n });\n return writeResult;\n });\n };\n\n return instance;\n }\n }\n );\n };\n\n}\n\n\n\n/**\n * Used in plugins to easily modify all in- and outgoing\n * data of that storage instance.\n */\nexport function wrapRxStorageInstance(\n originalSchema: RxJsonSchema>,\n instance: RxStorageInstance,\n modifyToStorage: (docData: RxDocumentWriteData) => MaybePromise>,\n modifyFromStorage: (docData: RxDocumentData) => MaybePromise>,\n modifyAttachmentFromStorage: (attachmentData: string) => MaybePromise = (v) => v\n): WrappedRxStorageInstance {\n async function toStorage(docData: RxDocumentWriteData): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyToStorage(docData);\n }\n async function fromStorage(docData: RxDocumentData | null): Promise> {\n if (!docData) {\n return docData;\n }\n return await modifyFromStorage(docData);\n }\n async function errorFromStorage(\n error: RxStorageWriteError\n ): Promise> {\n const ret = flatClone(error);\n ret.writeRow = flatClone(ret.writeRow);\n if ((ret as RxStorageWriteErrorConflict).documentInDb) {\n (ret as RxStorageWriteErrorConflict).documentInDb = await fromStorage((ret as RxStorageWriteErrorConflict).documentInDb);\n }\n if (ret.writeRow.previous) {\n ret.writeRow.previous = await fromStorage(ret.writeRow.previous);\n }\n ret.writeRow.document = await fromStorage(ret.writeRow.document);\n return ret;\n }\n\n\n const processingChangesCount$ = new BehaviorSubject(0);\n\n const wrappedInstance: WrappedRxStorageInstance = {\n databaseName: instance.databaseName,\n internals: instance.internals,\n cleanup: instance.cleanup.bind(instance),\n options: instance.options,\n close: instance.close.bind(instance),\n schema: originalSchema,\n collectionName: instance.collectionName,\n count: instance.count.bind(instance),\n remove: instance.remove.bind(instance),\n originalStorageInstance: instance,\n bulkWrite: async (\n documentWrites: BulkWriteRow[],\n context: string\n ) => {\n const useRows: BulkWriteRow[] = [];\n await Promise.all(\n documentWrites.map(async (row) => {\n const [previous, document] = await Promise.all([\n row.previous ? toStorage(row.previous) : undefined,\n toStorage(row.document)\n ]);\n useRows.push({ previous, document });\n })\n );\n\n const writeResult = await instance.bulkWrite(useRows, context);\n const ret: RxStorageBulkWriteResponse = {\n error: []\n };\n const promises: Promise[] = [];\n writeResult.error.forEach(error => {\n promises.push(\n errorFromStorage(error).then(err => ret.error.push(err))\n );\n });\n await Promise.all(promises);\n\n /**\n * By definition, all change events must be emitted\n * BEFORE the write call resolves.\n * To ensure that even when the modifiers are async,\n * we wait here until the processing queue is empty.\n */\n await firstValueFrom(\n processingChangesCount$.pipe(\n filter(v => v === 0)\n )\n );\n return ret;\n },\n query: (preparedQuery) => {\n return instance.query(preparedQuery)\n .then(queryResult => {\n return Promise.all(queryResult.documents.map(doc => fromStorage(doc)));\n })\n .then(documents => ({ documents: documents as any }));\n },\n getAttachmentData: async (\n documentId: string,\n attachmentId: string,\n digest: string\n ) => {\n let data = await instance.getAttachmentData(documentId, attachmentId, digest);\n data = await modifyAttachmentFromStorage(data);\n return data;\n },\n findDocumentsById: (ids, deleted) => {\n return instance.findDocumentsById(ids, deleted)\n .then(async (findResult) => {\n const ret: RxDocumentData[] = [];\n await Promise.all(\n findResult\n .map(async (doc) => {\n ret.push(await fromStorage(doc));\n })\n );\n return ret;\n });\n },\n getChangedDocumentsSince: !instance.getChangedDocumentsSince ? undefined : (limit, checkpoint) => {\n return ((instance as any).getChangedDocumentsSince)(limit, checkpoint)\n .then(async (result: any) => {\n return {\n checkpoint: result.checkpoint,\n documents: await Promise.all(\n result.documents.map((d: any) => fromStorage(d))\n )\n };\n });\n },\n changeStream: () => {\n return instance.changeStream().pipe(\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() + 1)),\n mergeMap(async (eventBulk) => {\n const useEvents = await Promise.all(\n eventBulk.events.map(async (event) => {\n const [\n documentData,\n previousDocumentData\n ] = await Promise.all([\n fromStorage(event.documentData),\n fromStorage(event.previousDocumentData)\n ]);\n const ev: RxChangeEvent = {\n operation: event.operation,\n documentId: event.documentId,\n documentData: documentData as any,\n previousDocumentData: previousDocumentData as any,\n isLocal: false\n };\n return ev;\n })\n );\n const ret: EventBulk>, any> = {\n id: eventBulk.id,\n events: useEvents,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n return ret;\n }),\n tap(() => processingChangesCount$.next(processingChangesCount$.getValue() - 1))\n );\n },\n };\n\n return wrappedInstance;\n}\n"],"mappings":"AAAA,SAASA,MAAM,EAAEC,QAAQ,EAAEC,GAAG,QAAQ,gBAAgB;AACtD,SAASC,2BAA2B,QAAQ,uBAAuB;AAmBnE,SACIC,SAAS,EACTC,kBAAkB,EAClBC,8BAA8B,QAC3B,0BAA0B;AACjC,SAASC,eAAe,EAAEC,cAAc,QAAQ,MAAM;;AAStD;AACA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,gCAA6E,GAAG,IAAIC,GAAG,CAAC,CAAC;;AAE/F;AACA;AACA;AACA;AACA,OAAO,SAASC,6BAA6BA;AACzC;AACJ;AACA;AACA;AACIC,YAA8D;AAC9D;AACJ;AACA;AACIC,YAAoB,EACE;EACtB,IAAMC,eAAe,GAAGT,kBAAkB,CACtCI,gCAAgC,EAChCI,YAAY,EACZ,MAAM,IAAIH,GAA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D,GAAG,CAAC,MAAMkE,uBAAuB,CAACqC,IAAI,CAACrC,uBAAuB,CAACsC,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAClF,CAAC;IACL;EACJ,CAAC;EAED,OAAOrC,eAAe;AAC1B","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/pipeline/rx-pipeline.js b/dist/esm/plugins/pipeline/rx-pipeline.js index 1bbc37a5313..a431b4b505d 100644 --- a/dist/esm/plugins/pipeline/rx-pipeline.js +++ b/dist/esm/plugins/pipeline/rx-pipeline.js @@ -5,6 +5,12 @@ import { mapDocumentsDataToCacheDocs } from "../../doc-cache.js"; import { INTERNAL_CONTEXT_PIPELINE_CHECKPOINT, getPrimaryKeyOfInternalDocument } from "../../rx-database-internal-store.js"; import { FLAGGED_FUNCTIONS, blockFlaggedFunctionKey, releaseFlaggedFunctionKey } from "./flagged-functions.js"; export var RxPipeline = /*#__PURE__*/function () { + /** + * The handler of the pipeline must never throw. + * If it did anyway, the pipeline will be stuck and always + * throw the previous error on all operations. + */ + function RxPipeline(identifier, source, destination, handler, batchSize = 100) { this.processQueue = PROMISE_RESOLVE_VOID; this.subs = []; @@ -59,49 +65,64 @@ export var RxPipeline = /*#__PURE__*/function () { this.toRun = this.toRun - 1; var done = false; var _loop = async function () { - var checkpointDoc = await getCheckpointDoc(_this2); - var checkpoint = checkpointDoc ? checkpointDoc.data.checkpoint : undefined; - var docsSinceResult = await getChangedDocumentsSince(_this2.source.storageInstance, _this2.batchSize, checkpoint); - var lastTime = checkpointDoc ? checkpointDoc.data.lastDocTime : 0; - if (docsSinceResult.documents.length > 0) { - var rxDocuments = mapDocumentsDataToCacheDocs(_this2.source._docCache, docsSinceResult.documents); - var _this = _this2; + var checkpointDoc = await getCheckpointDoc(_this2); + var checkpoint = checkpointDoc ? checkpointDoc.data.checkpoint : undefined; + var docsSinceResult = await getChangedDocumentsSince(_this2.source.storageInstance, _this2.batchSize, checkpoint); + var lastTime = checkpointDoc ? checkpointDoc.data.lastDocTime : 0; + if (docsSinceResult.documents.length > 0) { + var rxDocuments = mapDocumentsDataToCacheDocs(_this2.source._docCache, docsSinceResult.documents); + var _this = _this2; - // const o: any = {}; - // eval(` - // async function ${this.secretFunctionName}(docs){ const x = await _this.handler(docs); return x; } - // o.${this.secretFunctionName} = ${this.secretFunctionName}; - // `); - // await o[this.secretFunctionName](rxDocuments); + // const o: any = {}; + // eval(` + // async function ${this.secretFunctionName}(docs){ const x = await _this.handler(docs); return x; } + // o.${this.secretFunctionName} = ${this.secretFunctionName}; + // `); + // await o[this.secretFunctionName](rxDocuments); - var fnKey = blockFlaggedFunctionKey(); - _this2.secretFunctionName = fnKey; - try { - await FLAGGED_FUNCTIONS[fnKey](() => _this.handler(rxDocuments)); - } finally { - releaseFlaggedFunctionKey(fnKey); + var fnKey = blockFlaggedFunctionKey(); + _this2.secretFunctionName = fnKey; + try { + await FLAGGED_FUNCTIONS[fnKey](() => _this.handler(rxDocuments)); + } catch (err) { + _this2.error = err; + } finally { + releaseFlaggedFunctionKey(fnKey); + } + if (_this2.error) { + return { + v: void 0 + }; + } + lastTime = ensureNotFalsy(lastOfArray(docsSinceResult.documents))._meta.lwt; } - lastTime = ensureNotFalsy(lastOfArray(docsSinceResult.documents))._meta.lwt; - } - if (!_this2.destination.closed) { - await setCheckpointDoc(_this2, { - checkpoint: docsSinceResult.checkpoint, - lastDocTime: lastTime - }, checkpointDoc); - } - if (docsSinceResult.documents.length < _this2.batchSize) { - done = true; - } - }; - while (!done && !this.stopped && !this.destination.closed && !this.source.closed) { - await _loop(); + if (!_this2.destination.closed) { + await setCheckpointDoc(_this2, { + checkpoint: docsSinceResult.checkpoint, + lastDocTime: lastTime + }, checkpointDoc); + } + if (docsSinceResult.documents.length < _this2.batchSize) { + done = true; + } + }, + _ret; + while (!done && !this.stopped && !this.destination.closed && !this.source.closed && !this.error) { + _ret = await _loop(); + if (_ret) return _ret.v; } }); }; _proto.awaitIdle = async function awaitIdle() { + if (this.error) { + throw this.error; + } var done = false; while (!done) { await this.processQueue; + if (this.error) { + throw this.error; + } if (this.lastProcessedDocTime.getValue() >= this.lastSourceDocTime.getValue()) { done = true; } else { @@ -110,6 +131,7 @@ export var RxPipeline = /*#__PURE__*/function () { } }; _proto.close = async function close() { + await this.processQueue; this.stopped = true; this.destination.awaitBeforeReads.delete(this.waitBeforeWriteFn); this.subs.forEach(s => s.unsubscribe()); diff --git a/dist/esm/plugins/pipeline/rx-pipeline.js.map b/dist/esm/plugins/pipeline/rx-pipeline.js.map index b07552d3936..1cd5936e924 100644 --- a/dist/esm/plugins/pipeline/rx-pipeline.js.map +++ b/dist/esm/plugins/pipeline/rx-pipeline.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-pipeline.js","names":["BehaviorSubject","Subject","filter","firstValueFrom","PROMISE_RESOLVE_VOID","clone","createRevision","ensureNotFalsy","lastOfArray","now","randomToken","getChangedDocumentsSince","mapDocumentsDataToCacheDocs","INTERNAL_CONTEXT_PIPELINE_CHECKPOINT","getPrimaryKeyOfInternalDocument","FLAGGED_FUNCTIONS","blockFlaggedFunctionKey","releaseFlaggedFunctionKey","RxPipeline","identifier","source","destination","handler","batchSize","processQueue","subs","stopped","toRun","lastSourceDocTime","lastProcessedDocTime","somethingChanged","secretFunctionName","waitBeforeWriteFn","stack","Error","includes","awaitIdle","checkpointId","onClose","push","close","awaitBeforeReads","add","eventBulks$","subscribe","bulk","next","events","documentData","_meta","lwt","database","internalStore","changeStream","eventBulk","index","length","event","context","key","data","lastDocTime","_proto","prototype","trigger","_this2","then","done","_loop","checkpointDoc","getCheckpointDoc","checkpoint","undefined","docsSinceResult","storageInstance","lastTime","documents","rxDocuments","_docCache","_this","fnKey","closed","setCheckpointDoc","getValue","delete","forEach","s","unsubscribe","remove","insternalStore","newDoc","_deleted","writeResult","bulkWrite","previous","document","error","pipeline","results","findDocumentsById","result","newCheckpoint","_attachments","_rev","token","id","addPipeline","options","waitForLeadership","startPromise","pipe","isLocal"],"sources":["../../../../src/plugins/pipeline/rx-pipeline.ts"],"sourcesContent":["import {\n BehaviorSubject,\n Subject,\n Subscription,\n filter,\n firstValueFrom,\n race\n} from 'rxjs';\nimport type {\n InternalStoreDocType,\n RxCollection,\n RxDocument,\n RxDocumentData\n} from '../../types';\nimport type {\n CheckpointDocData,\n RxPipelineHandler,\n RxPipelineOptions\n} from './types';\nimport {\n PROMISE_RESOLVE_VOID,\n clone,\n createRevision,\n ensureNotFalsy,\n lastOfArray,\n nameFunction,\n now,\n promiseWait,\n randomToken\n} from '../utils/index.ts';\nimport { getChangedDocumentsSince } from '../../rx-storage-helper.ts';\nimport { mapDocumentsDataToCacheDocs } from '../../doc-cache.ts';\nimport { INTERNAL_CONTEXT_PIPELINE_CHECKPOINT, getPrimaryKeyOfInternalDocument } from '../../rx-database-internal-store.ts';\nimport { FLAGGED_FUNCTIONS, blockFlaggedFunctionKey, releaseFlaggedFunctionKey } from './flagged-functions.ts';\n\nexport class RxPipeline {\n processQueue = PROMISE_RESOLVE_VOID;\n subs: Subscription[] = [];\n stopped: boolean = false;\n\n toRun = 1;\n checkpointId: string;\n\n lastSourceDocTime = new BehaviorSubject(-1);\n lastProcessedDocTime = new BehaviorSubject(0);\n somethingChanged = new Subject();\n\n\n secretFunctionName = 'tx_fn_' + randomToken(10)\n\n waitBeforeWriteFn = async () => {\n const stack = new Error().stack;\n if (stack && (\n stack.includes(this.secretFunctionName)\n )) {\n } else {\n await this.awaitIdle();\n }\n }\n\n constructor(\n public readonly identifier: string,\n public readonly source: RxCollection,\n public readonly destination: RxCollection,\n public readonly handler: RxPipelineHandler,\n public readonly batchSize = 100\n ) {\n this.checkpointId = 'rx-pipeline-' + identifier;\n this.source.onClose.push(() => this.close());\n this.destination.awaitBeforeReads.add(this.waitBeforeWriteFn);\n this.subs.push(\n this.source.eventBulks$.subscribe((bulk) => {\n this.lastSourceDocTime.next(bulk.events[0].documentData._meta.lwt);\n this.somethingChanged.next({});\n })\n );\n this.subs.push(\n this.destination.database.internalStore\n .changeStream()\n .subscribe(eventBulk => {\n const events = eventBulk.events;\n for (let index = 0; index < events.length; index++) {\n const event = events[index];\n if (\n event.documentData.context === INTERNAL_CONTEXT_PIPELINE_CHECKPOINT &&\n event.documentData.key === this.checkpointId\n ) {\n this.lastProcessedDocTime.next(event.documentData.data.lastDocTime);\n this.somethingChanged.next({});\n }\n }\n })\n );\n }\n\n trigger() {\n /**\n * Do not stack up too many\n * so that fast writes to the source collection\n * do not block anything too long.\n */\n if (this.toRun > 2) {\n return;\n }\n this.toRun = this.toRun + 1;\n\n this.processQueue = this.processQueue.then(async () => {\n this.toRun = this.toRun - 1;\n\n let done = false;\n while (\n !done &&\n !this.stopped &&\n !this.destination.closed &&\n !this.source.closed\n ) {\n const checkpointDoc = await getCheckpointDoc(this);\n const checkpoint = checkpointDoc ? checkpointDoc.data.checkpoint : undefined;\n const docsSinceResult = await getChangedDocumentsSince(\n this.source.storageInstance,\n this.batchSize,\n checkpoint\n );\n\n let lastTime = checkpointDoc ? checkpointDoc.data.lastDocTime : 0;\n if (docsSinceResult.documents.length > 0) {\n const rxDocuments = mapDocumentsDataToCacheDocs(this.source._docCache, docsSinceResult.documents);\n const _this = this;\n\n\n\n // const o: any = {};\n // eval(`\n // async function ${this.secretFunctionName}(docs){ const x = await _this.handler(docs); return x; }\n // o.${this.secretFunctionName} = ${this.secretFunctionName};\n // `);\n // await o[this.secretFunctionName](rxDocuments);\n\n const fnKey = blockFlaggedFunctionKey();\n this.secretFunctionName = fnKey;\n try {\n await FLAGGED_FUNCTIONS[fnKey](() => _this.handler(rxDocuments));\n } finally {\n releaseFlaggedFunctionKey(fnKey);\n }\n\n lastTime = ensureNotFalsy(lastOfArray(docsSinceResult.documents))._meta.lwt;\n }\n if (!this.destination.closed) {\n await setCheckpointDoc(this, { checkpoint: docsSinceResult.checkpoint, lastDocTime: lastTime }, checkpointDoc);\n }\n if (docsSinceResult.documents.length < this.batchSize) {\n done = true;\n }\n }\n });\n }\n\n async awaitIdle() {\n let done = false;\n while (!done) {\n await this.processQueue;\n if (this.lastProcessedDocTime.getValue() >= this.lastSourceDocTime.getValue()) {\n done = true;\n } else {\n await firstValueFrom(this.somethingChanged);\n }\n }\n }\n\n async close() {\n this.stopped = true;\n this.destination.awaitBeforeReads.delete(this.waitBeforeWriteFn);\n this.subs.forEach(s => s.unsubscribe());\n await this.processQueue;\n }\n\n /**\n * Remove the pipeline and all metadata which it has stored\n */\n async remove() {\n const insternalStore = this.destination.database.internalStore;\n const checkpointDoc = await getCheckpointDoc(this);\n if (checkpointDoc) {\n const newDoc: RxDocumentData = clone(checkpointDoc);\n newDoc._deleted = true;\n const writeResult = await insternalStore.bulkWrite([{\n previous: checkpointDoc,\n document: newDoc,\n }], 'rx-pipeline');\n if (writeResult.error.length > 0) {\n throw writeResult.error;\n }\n }\n return this.close();\n }\n}\n\n\nexport async function getCheckpointDoc(\n pipeline: RxPipeline\n): Promise> | undefined> {\n const insternalStore = pipeline.destination.database.internalStore;\n const checkpointId = getPrimaryKeyOfInternalDocument(\n pipeline.checkpointId,\n INTERNAL_CONTEXT_PIPELINE_CHECKPOINT\n );\n const results = await insternalStore.findDocumentsById([checkpointId], false);\n const result: RxDocumentData = results[0];\n if (result) {\n return result;\n } else {\n return undefined;\n }\n}\n\nexport async function setCheckpointDoc(\n pipeline: RxPipeline,\n newCheckpoint: CheckpointDocData,\n previous?: RxDocumentData\n): Promise {\n const insternalStore = pipeline.destination.database.internalStore;\n const newDoc: RxDocumentData> = {\n _attachments: {},\n _deleted: false,\n _meta: {\n lwt: now()\n },\n _rev: createRevision(pipeline.destination.database.token, previous),\n context: INTERNAL_CONTEXT_PIPELINE_CHECKPOINT,\n data: newCheckpoint,\n id: getPrimaryKeyOfInternalDocument(\n pipeline.checkpointId,\n INTERNAL_CONTEXT_PIPELINE_CHECKPOINT\n ),\n key: pipeline.checkpointId\n };\n\n const writeResult = await insternalStore.bulkWrite([{\n previous,\n document: newDoc,\n }], 'rx-pipeline');\n if (writeResult.error.length > 0) {\n throw writeResult.error;\n }\n}\n\n\nexport async function addPipeline(\n this: RxCollection,\n options: RxPipelineOptions\n): Promise> {\n const pipeline = new RxPipeline(\n options.identifier,\n this,\n options.destination,\n options.handler,\n options.batchSize\n );\n const waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const startPromise = waitForLeadership ? this.database.waitForLeadership() : PROMISE_RESOLVE_VOID;\n startPromise.then(() => {\n pipeline.trigger();\n pipeline.subs.push(\n this.eventBulks$.pipe(\n filter(bulk => {\n if (pipeline.stopped) {\n return false;\n }\n return !bulk.isLocal;\n })\n ).subscribe(() => pipeline.trigger())\n );\n });\n\n return pipeline;\n}\n"],"mappings":"AAAA,SACIA,eAAe,EACfC,OAAO,EAEPC,MAAM,EACNC,cAAc,QAEX,MAAM;AAYb,SACIC,oBAAoB,EACpBC,KAAK,EACLC,cAAc,EACdC,cAAc,EACdC,WAAW,EAEXC,GAAG,EAEHC,WAAW,QACR,mBAAmB;AAC1B,SAASC,wBAAwB,QAAQ,4BAA4B;AACrE,SAASC,2BAA2B,QAAQ,oBAAoB;AAChE,SAASC,oCAAoC,EAAEC,+BAA+B,QAAQ,qCAAqC;AAC3H,SAASC,iBAAiB,EAAEC,uBAAuB,EAAEC,yBAAyB,QAAQ,wBAAwB;AAE9G,WAAaC,UAAU;EAyBnB,SAAAA,WACoBC,UAAkB,EAClBC,MAA+B,EAC/BC,WAA8B,EAC9BC,OAAqC,EACrCC,SAAS,GAAG,GAAG,EACjC;IAAA,KA9BFC,YAAY,GAAGpB,oBAAoB;IAAA,KACnCqB,IAAI,GAAmB,EAAE;IAAA,KACzBC,OAAO,GAAY,KAAK;IAAA,KAExBC,KAAK,GAAG,CAAC;IAAA,KAGTC,iBAAiB,GAAG,IAAI5B,eAAe,CAAC,CAAC,CAAC,CAAC;IAAA,KAC3C6B,oBAAoB,GAAG,IAAI7B,eAAe,CAAC,CAAC,CAAC;IAAA,KAC7C8B,gBAAgB,GAAG,IAAI7B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,CAAC5D;EAClB,CAAC;EAED,IAAMuD,WAAW,GAAG,MAAMH,cAAc,CAACI,SAAS,CAAC,CAAC;IAChDC,QAAQ;IACRC,QAAQ,EAAEL;EACd,CAAC,CAAC,EAAE,aAAa,CAAC;EAClB,IAAIE,WAAW,CAACI,KAAK,CAACxC,MAAM,GAAG,CAAC,EAAE;IAC9B,MAAMoC,WAAW,CAACI,KAAK;EAC3B;AACJ;AAGA,OAAO,eAAeU,WAAWA,CAE7BC,OAAqC,EACP;EAC9B,IAAMV,QAAQ,GAAG,IAAI/E,UAAU,CAC3ByF,OAAO,CAACxF,UAAU,EAClB,IAAI,EACJwF,OAAO,CAACtF,WAAW,EACnBsF,OAAO,CAACrF,OAAO,EACfqF,OAAO,CAACpF,SACZ,CAAC;EACD,IAAMqF,iBAAiB,GAAG,OAAOD,OAAO,CAACC,iBAAiB,KAAK,WAAW,GAAG,IAAI,GAAGD,OAAO,CAACC,iBAAiB;EAC7G,IAAMC,YAAY,GAAGD,iBAAiB,GAAG,IAAI,CAACzD,QAAQ,CAACyD,iBAAiB,CAAC,CAAC,GAAGxG,oBAAoB;EACjGyG,YAAY,CAAC3C,IAAI,CAAC,MAAM;IACpB+B,QAAQ,CAACjC,OAAO,CAAC,CAAC;IAClBiC,QAAQ,CAACxE,IAAI,CAACc,IAAI,CACd,IAAI,CAACI,WAAW,CAACmE,IAAI,CACjB5G,MAAM,CAAC2C,IAAI,IAAI;MACX,IAAIoD,QAAQ,CAACvE,OAAO,EAAE;QAClB,OAAO,KAAK;MAChB;MACA,OAAO,CAACmB,IAAI,CAACkE,OAAO;IACxB,CAAC,CACL,CAAC,CAACnE,SAAS,CAAC,MAAMqD,QAAQ,CAACjC,OAAO,CAAC,CAAC,CACxC,CAAC;EACL,CAAC,CAAC;EAEF,OAAOiC,QAAQ;AACnB","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-pipeline.js","names":["BehaviorSubject","Subject","filter","firstValueFrom","PROMISE_RESOLVE_VOID","clone","createRevision","ensureNotFalsy","lastOfArray","now","randomToken","getChangedDocumentsSince","mapDocumentsDataToCacheDocs","INTERNAL_CONTEXT_PIPELINE_CHECKPOINT","getPrimaryKeyOfInternalDocument","FLAGGED_FUNCTIONS","blockFlaggedFunctionKey","releaseFlaggedFunctionKey","RxPipeline","identifier","source","destination","handler","batchSize","processQueue","subs","stopped","toRun","lastSourceDocTime","lastProcessedDocTime","somethingChanged","secretFunctionName","waitBeforeWriteFn","stack","Error","includes","awaitIdle","checkpointId","onClose","push","close","awaitBeforeReads","add","eventBulks$","subscribe","bulk","next","events","documentData","_meta","lwt","database","internalStore","changeStream","eventBulk","index","length","event","context","key","data","lastDocTime","_proto","prototype","trigger","_this2","then","done","_loop","checkpointDoc","getCheckpointDoc","checkpoint","undefined","docsSinceResult","storageInstance","lastTime","documents","rxDocuments","_docCache","_this","fnKey","err","error","v","closed","setCheckpointDoc","_ret","getValue","delete","forEach","s","unsubscribe","remove","insternalStore","newDoc","_deleted","writeResult","bulkWrite","previous","document","pipeline","results","findDocumentsById","result","newCheckpoint","_attachments","_rev","token","id","addPipeline","options","waitForLeadership","startPromise","pipe","isLocal"],"sources":["../../../../src/plugins/pipeline/rx-pipeline.ts"],"sourcesContent":["import {\n BehaviorSubject,\n Subject,\n Subscription,\n filter,\n firstValueFrom,\n race\n} from 'rxjs';\nimport type {\n InternalStoreDocType,\n RxCollection,\n RxDocument,\n RxDocumentData\n} from '../../types';\nimport type {\n CheckpointDocData,\n RxPipelineHandler,\n RxPipelineOptions\n} from './types';\nimport {\n PROMISE_RESOLVE_VOID,\n clone,\n createRevision,\n ensureNotFalsy,\n lastOfArray,\n nameFunction,\n now,\n promiseWait,\n randomToken\n} from '../utils/index.ts';\nimport { getChangedDocumentsSince } from '../../rx-storage-helper.ts';\nimport { mapDocumentsDataToCacheDocs } from '../../doc-cache.ts';\nimport { INTERNAL_CONTEXT_PIPELINE_CHECKPOINT, getPrimaryKeyOfInternalDocument } from '../../rx-database-internal-store.ts';\nimport { FLAGGED_FUNCTIONS, blockFlaggedFunctionKey, releaseFlaggedFunctionKey } from './flagged-functions.ts';\n\nexport class RxPipeline {\n processQueue = PROMISE_RESOLVE_VOID;\n subs: Subscription[] = [];\n stopped: boolean = false;\n\n toRun = 1;\n checkpointId: string;\n\n lastSourceDocTime = new BehaviorSubject(-1);\n lastProcessedDocTime = new BehaviorSubject(0);\n somethingChanged = new Subject();\n\n\n secretFunctionName = 'tx_fn_' + randomToken(10)\n\n waitBeforeWriteFn = async () => {\n const stack = new Error().stack;\n if (stack && (\n stack.includes(this.secretFunctionName)\n )) {\n } else {\n await this.awaitIdle();\n }\n }\n\n /**\n * The handler of the pipeline must never throw.\n * If it did anyway, the pipeline will be stuck and always\n * throw the previous error on all operations.\n */\n error: any;\n\n constructor(\n public readonly identifier: string,\n public readonly source: RxCollection,\n public readonly destination: RxCollection,\n public readonly handler: RxPipelineHandler,\n public readonly batchSize = 100\n ) {\n this.checkpointId = 'rx-pipeline-' + identifier;\n this.source.onClose.push(() => this.close());\n this.destination.awaitBeforeReads.add(this.waitBeforeWriteFn);\n this.subs.push(\n this.source.eventBulks$.subscribe((bulk) => {\n this.lastSourceDocTime.next(bulk.events[0].documentData._meta.lwt);\n this.somethingChanged.next({});\n })\n );\n this.subs.push(\n this.destination.database.internalStore\n .changeStream()\n .subscribe(eventBulk => {\n const events = eventBulk.events;\n for (let index = 0; index < events.length; index++) {\n const event = events[index];\n if (\n event.documentData.context === INTERNAL_CONTEXT_PIPELINE_CHECKPOINT &&\n event.documentData.key === this.checkpointId\n ) {\n this.lastProcessedDocTime.next(event.documentData.data.lastDocTime);\n this.somethingChanged.next({});\n }\n }\n })\n );\n }\n\n trigger() {\n /**\n * Do not stack up too many\n * so that fast writes to the source collection\n * do not block anything too long.\n */\n if (this.toRun > 2) {\n return;\n }\n this.toRun = this.toRun + 1;\n\n this.processQueue = this.processQueue.then(async () => {\n this.toRun = this.toRun - 1;\n\n let done = false;\n while (\n !done &&\n !this.stopped &&\n !this.destination.closed &&\n !this.source.closed &&\n !this.error\n ) {\n const checkpointDoc = await getCheckpointDoc(this);\n const checkpoint = checkpointDoc ? checkpointDoc.data.checkpoint : undefined;\n const docsSinceResult = await getChangedDocumentsSince(\n this.source.storageInstance,\n this.batchSize,\n checkpoint\n );\n\n let lastTime = checkpointDoc ? checkpointDoc.data.lastDocTime : 0;\n if (docsSinceResult.documents.length > 0) {\n const rxDocuments = mapDocumentsDataToCacheDocs(this.source._docCache, docsSinceResult.documents);\n const _this = this;\n\n\n\n // const o: any = {};\n // eval(`\n // async function ${this.secretFunctionName}(docs){ const x = await _this.handler(docs); return x; }\n // o.${this.secretFunctionName} = ${this.secretFunctionName};\n // `);\n // await o[this.secretFunctionName](rxDocuments);\n\n const fnKey = blockFlaggedFunctionKey();\n this.secretFunctionName = fnKey;\n try {\n await FLAGGED_FUNCTIONS[fnKey](() => _this.handler(rxDocuments));\n } catch (err: any) {\n this.error = err;\n } finally {\n releaseFlaggedFunctionKey(fnKey);\n }\n\n if (this.error) {\n return;\n }\n\n lastTime = ensureNotFalsy(lastOfArray(docsSinceResult.documents))._meta.lwt;\n }\n if (!this.destination.closed) {\n await setCheckpointDoc(this, { checkpoint: docsSinceResult.checkpoint, lastDocTime: lastTime }, checkpointDoc);\n }\n if (docsSinceResult.documents.length < this.batchSize) {\n done = true;\n }\n }\n });\n }\n\n async awaitIdle() {\n if (this.error) {\n throw this.error;\n }\n let done = false;\n while (!done) {\n await this.processQueue;\n if (this.error) {\n throw this.error;\n }\n if (this.lastProcessedDocTime.getValue() >= this.lastSourceDocTime.getValue()) {\n done = true;\n } else {\n await firstValueFrom(this.somethingChanged);\n }\n }\n }\n\n async close() {\n await this.processQueue;\n this.stopped = true;\n this.destination.awaitBeforeReads.delete(this.waitBeforeWriteFn);\n this.subs.forEach(s => s.unsubscribe());\n await this.processQueue;\n }\n\n /**\n * Remove the pipeline and all metadata which it has stored\n */\n async remove() {\n const insternalStore = this.destination.database.internalStore;\n const checkpointDoc = await getCheckpointDoc(this);\n if (checkpointDoc) {\n const newDoc: RxDocumentData = clone(checkpointDoc);\n newDoc._deleted = true;\n const writeResult = await insternalStore.bulkWrite([{\n previous: checkpointDoc,\n document: newDoc,\n }], 'rx-pipeline');\n if (writeResult.error.length > 0) {\n throw writeResult.error;\n }\n }\n return this.close();\n }\n}\n\n\nexport async function getCheckpointDoc(\n pipeline: RxPipeline\n): Promise> | undefined> {\n const insternalStore = pipeline.destination.database.internalStore;\n const checkpointId = getPrimaryKeyOfInternalDocument(\n pipeline.checkpointId,\n INTERNAL_CONTEXT_PIPELINE_CHECKPOINT\n );\n const results = await insternalStore.findDocumentsById([checkpointId], false);\n const result: RxDocumentData = results[0];\n if (result) {\n return result;\n } else {\n return undefined;\n }\n}\n\nexport async function setCheckpointDoc(\n pipeline: RxPipeline,\n newCheckpoint: CheckpointDocData,\n previous?: RxDocumentData\n): Promise {\n const insternalStore = pipeline.destination.database.internalStore;\n const newDoc: RxDocumentData> = {\n _attachments: {},\n _deleted: false,\n _meta: {\n lwt: now()\n },\n _rev: createRevision(pipeline.destination.database.token, previous),\n context: INTERNAL_CONTEXT_PIPELINE_CHECKPOINT,\n data: newCheckpoint,\n id: getPrimaryKeyOfInternalDocument(\n pipeline.checkpointId,\n INTERNAL_CONTEXT_PIPELINE_CHECKPOINT\n ),\n key: pipeline.checkpointId\n };\n\n const writeResult = await insternalStore.bulkWrite([{\n previous,\n document: newDoc,\n }], 'rx-pipeline');\n if (writeResult.error.length > 0) {\n throw writeResult.error;\n }\n}\n\n\nexport async function addPipeline(\n this: RxCollection,\n options: RxPipelineOptions\n): Promise> {\n const pipeline = new RxPipeline(\n options.identifier,\n this,\n options.destination,\n options.handler,\n options.batchSize\n );\n const waitForLeadership = typeof options.waitForLeadership === 'undefined' ? true : options.waitForLeadership;\n const startPromise = waitForLeadership ? this.database.waitForLeadership() : PROMISE_RESOLVE_VOID;\n startPromise.then(() => {\n pipeline.trigger();\n pipeline.subs.push(\n this.eventBulks$.pipe(\n filter(bulk => {\n if (pipeline.stopped) {\n return false;\n }\n return !bulk.isLocal;\n })\n ).subscribe(() => pipeline.trigger())\n );\n });\n\n return pipeline;\n}\n"],"mappings":"AAAA,SACIA,eAAe,EACfC,OAAO,EAEPC,MAAM,EACNC,cAAc,QAEX,MAAM;AAYb,SACIC,oBAAoB,EACpBC,KAAK,EACLC,cAAc,EACdC,cAAc,EACdC,WAAW,EAEXC,GAAG,EAEHC,WAAW,QACR,mBAAmB;AAC1B,SAASC,wBAAwB,QAAQ,4BAA4B;AACrE,SAASC,2BAA2B,QAAQ,oBAAoB;AAChE,SAASC,oCAAoC,EAAEC,+BAA+B,QAAQ,qCAAqC;AAC3H,SAASC,iBAAiB,EAAEC,uBAAuB,EAAEC,yBAAyB,QAAQ,wBAAwB;AAE9G,WAAaC,UAAU;EAyBnB;AACJ;AACA;AACA;AACA;;EAGI,SAAAA,WACoBC,UAAkB,EAClBC,MAA+B,EAC/BC,WAA8B,EAC9BC,OAAqC,EACrCC,SAAS,GAAG,GAAG,EACjC;IAAA,KArCFC,YAAY,GAAGpB,oBAAoB;IAAA,KACnCqB,IAAI,GAAmB,EAAE;IAAA,KACzBC,OAAO,GAAY,KAAK;IAAA,KAExBC,KAAK,GAAG,CAAC;IAAA,KAGTC,iBAAiB,GAAG,IAAI5B,eAAe,CAAC,CAAC,CAAC,CAAC;IAAA,KAC3C6B,oBAAoB,GAAG,IAAI7B,eAAe,CAAC,CAAC,CAAC;IAAA,KAC7C8B,gBAAgB,GAAG,IAAI7B,OAAO,CAAC,CAAC;IAAA,KAGhC8B,kBAAkB,GAAG,QAAQ,GAAGrB,WAAW,CAAC,EAAE,CAAC;IAAA,KAE/CsB,iBAAiB,GAAG,YAAY;MAC5B,IAAMC,KAAK,GAAG,IAAIC,KAAK,CAAC,CAAC,CAACD,KAAK;MAC/B,IAAIA,KAAK,IACLA,KAAK,CAACE,QAAQ,CAAC,IAAI,CAACJ,kBAAkB,CACzC,EAAE,CACH,CAAC,M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L,CAAC,CAAC;EAEF,OAAOoC,QAAQ;AACnB","ignoreList":[]} \ 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 cb82dafd91f..967689d595a 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 = '16.0.0-beta.1'; +export var RXDB_VERSION = '16.0.0-beta.2'; //# 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 9c05b46234d..96ba083605e 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 = '16.0.0-beta.1';\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAO,IAAMA,YAAY,GAAG,eAAe","ignoreList":[]} \ 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 = '16.0.0-beta.2';\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAO,IAAMA,YAAY,GAAG,eAAe","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/rx-collection.js.map b/dist/esm/rx-collection.js.map index c4e4ffbc928..31f1ada001d 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","ensureRxCollectionIsNotClosed","createRxQuery","_getDefaultQuery","newRxError","newRxTypeError","DocumentCache","mapDocumentsDataToCacheDocs","createQueryCache","defaultCacheReplacementPolicy","createChangeEventBuffer","runAsyncPluginHooks","runPluginHooks","createNewRxDocument","getRxDocumentConstructor","getWrappedStorageInstance","getWrittenDocumentsFromBulkWriteResponse","throwIfIsStorageWriteError","IncrementalWriteQueue","beforeDocumentUpdateWrite","overwritable","defaultConflictHandler","rxChangeEventBulkToRxChangeEvents","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","statics","conflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","awaitBeforeReads","_incrementalUpsertQueues","Map","synced","hooks","_subs","_docCache","_queryCache","$","checkpoint$","_changeEventBuffer","eventBulks$","onClose","closed","onRemove","_applyHookFunctions","asRxCollection","pipe","changeEventBulk","collectionName","_proto","prototype","prepare","jsonSchema","primaryPath","newData","oldData","result","_runHooks","checkpoint","documentConstructor","bulk","isLocal","events","docData","listenToRemoveSub","internalStore","changeStream","key","version","found","find","event","documentData","context","operation","subscribe","close","Promise","all","fn","push","databaseStorageToken","storageToken","subDocs","eventBulk","id","internal","databaseToken","token","$emit","cleanup","_minimumDeletedTime","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","insertResult","success","docsData","length","ids","insertRows","hasHooks","useDocData","then","add","document","Array","index","size","collection","args","documents","results","bulkWrite","rxDocuments","ret","docsMap","forEach","row","doc","set","get","primary","bulkRemove","idsOrDocs","rxDocumentMap","findByIds","exec","d","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","_deleted","previous","deletedRxDocuments","successIds","getCachedRxDocument","bulkUpsert","insertData","useJsonByDocId","useJson","slice","err","status","documentId","writeData","docDataInDb","documentInDb","getCachedRxDocuments","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","queryObj","op","query","findOne","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addPipeline","_options","addHook","when","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","_runHooksSync","promiseWait","time","res","timeout","setTimeout","delete","clearTimeout","requestIdlePromise","sub","unsubscribe","collections","remove","storage","password","hashFunction","_createClass","cE","colProto","Object","getPrototypeOf","fnName","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","isDevMode","entries","funName","defineProperty","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 ensureRxCollectionIsNotClosed\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,\n 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 getRxDocumentConstructor\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n getWrittenDocumentsFromBulkWriteResponse,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxPipeline, RxPipelineOptions } from './plugins/pipeline/index.ts';\nimport { defaultConflictHandler } from './replication-protocol/default-conflict-handler.ts';\nimport { rxChangeEventBulkToRxChangeEvents } from './rx-change-event.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; },\n Reactivity = any\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n\n /**\n * Before reads, all these methods are awaited. Used to \"block\" reads\n * depending on other processes, like when the RxPipeline is running.\n */\n public readonly awaitBeforeReads = new Set<() => MaybePromise>();\n\n constructor(\n public readonly 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 if (database) { // might be falsy on pseudoInstance\n this.eventBulks$ = database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name)\n );\n } else { }\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 * Internally only use eventBulks$\n * Do not use .$ or .observable$ because that has to transform\n * the events which decreases performance.\n */\n public readonly eventBulks$: Observable> = {} as any;\n\n\n /**\n * When the collection is closed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onClose: (() => MaybePromise)[] = [];\n public closed = false;\n\n public onRemove: (() => MaybePromise)[] = [];\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 this.$ = this.eventBulks$.pipe(\n mergeMap(changeEventBulk => rxChangeEventBulkToRxChangeEvents(changeEventBulk)),\n );\n this.checkpoint$ = this.eventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n let documentConstructor: any;\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.eventBulks$.pipe(\n filter(bulk => !bulk.isLocal),\n map(bulk => bulk.events)\n ),\n docData => {\n if (!documentConstructor) {\n documentConstructor = getRxDocumentConstructor(this.asRxCollection);\n }\n return createNewRxDocument(this.asRxCollection, documentConstructor, docData);\n }\n );\n\n\n const listenToRemoveSub = this.database.internalStore.changeStream().pipe(\n filter(bulk => {\n const key = this.name + '-' + this.schema.version;\n const found = bulk.events.find(event => {\n return (\n event.documentData.context === 'collection' &&\n event.documentData.key === key &&\n event.operation === 'DELETE'\n );\n });\n return !!found;\n })\n ).subscribe(async () => {\n await this.close();\n await Promise.all(this.onRemove.map(fn => fn()));\n });\n this._subs.push(listenToRemoveSub);\n\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 isLocal: false,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events,\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n 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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\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\n const ids = new Set();\n\n /**\n * This code is a bit redundant for better performance.\n * Instead of iterating multiple times,\n * we directly transform the input to a write-row array.\n */\n let insertRows: BulkWriteRow[];\n if (this.hasHooks('pre', 'insert')) {\n insertRows = await Promise.all(\n docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return this._runHooks('pre', 'insert', useDocData)\n .then(() => {\n ids.add((useDocData as any)[primaryPath]);\n return { document: useDocData };\n });\n })\n );\n } else {\n insertRows = new Array(docsData.length);\n const schema = this.schema;\n for (let index = 0; index < docsData.length; index++) {\n const docData = docsData[index];\n const useDocData = fillObjectDataBeforeInsert(schema, docData);\n ids.add((useDocData as any)[primaryPath]);\n insertRows[index] = { document: useDocData };\n }\n }\n\n\n if (ids.size !== docsData.length) {\n throw newRxError('COL22', {\n collection: this.name,\n args: {\n documents: docsData\n }\n });\n }\n\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n\n /**\n * Often the user does not need to access the RxDocuments of the bulkInsert() call.\n * So we transform the data to RxDocuments only if needed to use less CPU performance.\n */\n let rxDocuments: RxDocument[];\n const collection = this;\n const ret = {\n get success() {\n if (!rxDocuments) {\n const success = getWrittenDocumentsFromBulkWriteResponse(\n collection.schema.primaryPath,\n insertRows,\n results\n );\n rxDocuments = mapDocumentsDataToCacheDocs(collection._docCache, success);\n }\n return rxDocuments;\n },\n error: results.error\n };\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n insertRows.forEach(row => {\n const doc = row.document;\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n ret.success.map(doc => {\n return this._runHooks(\n 'post',\n 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return ret;\n }\n\n async bulkRemove(\n /**\n * You can either remove the documents by their ids\n * or by directly providing the RxDocument instances\n * if you have them already. This improves performance a bit.\n */\n idsOrDocs: string[] | RxDocument[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n ensureRxCollectionIsNotClosed(this);\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (idsOrDocs.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n let rxDocumentMap: Map>;\n if (typeof idsOrDocs[0] === 'string') {\n rxDocumentMap = await this.findByIds(idsOrDocs as string[]).exec();\n } else {\n rxDocumentMap = new Map();\n (idsOrDocs as RxDocument[]).forEach(d => rxDocumentMap.set(d.primary, d));\n }\n\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\n const success = getWrittenDocumentsFromBulkWriteResponse(\n this.schema.primaryPath,\n removeDocs,\n results\n );\n\n const deletedRxDocuments: RxDocument[] = [];\n const successIds: string[] = success.map(d => {\n const id = d[primaryPath] as string;\n const doc = this._docCache.getCachedRxDocument(d);\n deletedRxDocuments.push(doc);\n return id;\n });\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\n return {\n success: deletedRxDocuments,\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 ensureRxCollectionIsNotClosed(this);\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.getCachedRxDocuments([docDataInDb])[0];\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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[],\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n\n runPluginHooks('prePrepareRxQuery', {\n op: 'find',\n queryObj,\n collection: this\n });\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this as any);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n\n runPluginHooks('prePrepareRxQuery', {\n op: 'findOne',\n queryObj,\n collection: this\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 // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this as any);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n findByIds(\n ids: string[]\n ): RxQuery<\n RxDocumentType,\n Map>,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\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 addPipeline(_options: RxPipelineOptions): Promise> {\n throw pluginMissing('pipeline');\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 /**\n * Performance shortcut\n * so that we not have to build the empty object.\n */\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return false;\n }\n\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 if (!this.hasHooks(when, key)) {\n return;\n }\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 closed\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 async close(): Promise {\n if (this.closed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n\n await Promise.all(this.onClose.map(fn => fn()));\n\n /**\n * Settings closed = 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.closed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.close();\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(() => 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('postCloseRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.close();\n await Promise.all(this.onRemove.map(fn => fn()));\n /**\n * TODO here we should pass the already existing\n * storage instances instead of creating new ones.\n */\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.getCachedRxDocuments([docDataFromCache])[0],\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 as Error));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";AAAA,SACIA,MAAM,EACNC,GAAG,EACHC,QAAQ,QACL,MAAM;AAEb,SACIC,OAAO,EACPC,SAAS,EACTC,aAAa,EACbC,aAAa,EACbC,cAAc,EACdC,iBAAiB,EACjBC,qBAAqB,EACrBC,oBAAoB,QACjB,0BAA0B;AACjC,SACIC,0BAA0B,EAC1BC,iCAAiC,EACjCC,wBAAwB,EACxBC,6BAA6B,QAC1B,2BAA2B;AAClC,SACIC,aAAa,EACbC,gBAAgB,QACb,eAAe;AACtB,SACIC,UAAU,EACVC,cAAc,QACX,eAAe;AAItB,SACIC,aAAa,EACbC,2BAA2B,QACxB,gBAAgB;AACvB,SAEIC,gBAAgB,EAChBC,6BAA6B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ACA;AACA,OAHY,CAIC2H,KAAK,CAACtF,GAAG,IAAI;MACV,OAAOjI,eAAe,CAACmD,KAAK,CAAC,CAAC,CACzBmC,IAAI,CAAC,MAAMlC,OAAO,CAACoK,MAAM,CAACvF,GAAY,CAAC,CAAC;IACjD,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEA,OAAO,SAASwF,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYvO,gBAAgB;AAC1C","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-collection.js","names":["filter","map","mergeMap","ucfirst","flatClone","promiseSeries","pluginMissing","ensureNotFalsy","getFromMapOrThrow","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_VOID","fillObjectDataBeforeInsert","createRxCollectionStorageInstance","removeCollectionStorages","ensureRxCollectionIsNotClosed","createRxQuery","_getDefaultQuery","newRxError","newRxTypeError","DocumentCache","mapDocumentsDataToCacheDocs","createQueryCache","defaultCacheReplacementPolicy","createChangeEventBuffer","runAsyncPluginHooks","runPluginHooks","createNewRxDocument","getRxDocumentConstructor","getWrappedStorageInstance","getWrittenDocumentsFromBulkWriteResponse","throwIfIsStorageWriteError","IncrementalWriteQueue","beforeDocumentUpdateWrite","overwritable","defaultConflictHandler","rxChangeEventBulkToRxChangeEvents","HOOKS_WHEN","HOOKS_KEYS","hooksApplied","RxCollectionBase","database","name","schema","internalStorageInstance","instanceCreationOptions","migrationStrategies","methods","attachments","options","cacheReplacementPolicy","statics","conflictHandler","storageInstance","timeouts","Set","incrementalWriteQueue","awaitBeforeReads","_incrementalUpsertQueues","Map","synced","hooks","_subs","_docCache","_queryCache","$","checkpoint$","_changeEventBuffer","eventBulks$","onClose","closed","onRemove","_applyHookFunctions","asRxCollection","pipe","changeEventBulk","collectionName","_proto","prototype","prepare","jsonSchema","primaryPath","newData","oldData","result","_runHooks","checkpoint","documentConstructor","bulk","isLocal","events","docData","listenToRemoveSub","internalStore","changeStream","key","version","found","find","event","documentData","context","operation","subscribe","close","Promise","all","fn","push","databaseStorageToken","storageToken","subDocs","eventBulk","id","internal","databaseToken","token","$emit","cleanup","_minimumDeletedTime","migrationNeeded","getMigrationState","startMigration","batchSize","migratePromise","insert","json","writeResult","bulkInsert","isError","error","insertResult","success","docsData","length","ids","insertRows","hasHooks","useDocData","then","add","document","Array","index","size","collection","args","documents","results","bulkWrite","rxDocuments","ret","docsMap","forEach","row","doc","set","get","primary","bulkRemove","idsOrDocs","rxDocumentMap","findByIds","exec","d","from","values","rxDocument","data","toMutableJSON","removeDocs","writeDoc","_deleted","previous","deletedRxDocuments","successIds","getCachedRxDocument","bulkUpsert","insertData","useJsonByDocId","useJson","slice","err","status","documentId","writeData","docDataInDb","documentInDb","getCachedRxDocuments","newDoc","incrementalModify","upsert","bulkResult","incrementalUpsert","queue","_incrementalUpsertEnsureRxDocumentExists","wasInserted","inserted","_incrementalUpsertUpdate","queryObj","op","query","findOne","selector","limit","count","mangoQuery","$in","exportJSON","importJSON","_exportedJSON","insertCRDT","_updateObj","addPipeline","_options","addHook","when","fun","parallel","includes","boundFun","bind","runName","series","getHooks","instance","tasks","hook","_runHooksSync","promiseWait","time","res","timeout","setTimeout","delete","clearTimeout","requestIdlePromise","sub","unsubscribe","collections","remove","storage","password","hashFunction","_createClass","cE","colProto","Object","getPrototypeOf","fnName","_innerDoc","rxCollection","docDataFromCache","getLatestDocumentDataIfExists","resolve","createRxCollection","autoMigrate","localDocuments","storageInstanceCreationParams","databaseInstanceToken","databaseName","multiInstance","devMode","isDevMode","entries","funName","defineProperty","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 ensureRxCollectionIsNotClosed\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,\n 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 getRxDocumentConstructor\n} from './rx-document-prototype-merge.ts';\nimport {\n getWrappedStorageInstance,\n getWrittenDocumentsFromBulkWriteResponse,\n throwIfIsStorageWriteError,\n WrappedRxStorageInstance\n} from './rx-storage-helper.ts';\nimport { IncrementalWriteQueue } from './incremental-write.ts';\nimport { beforeDocumentUpdateWrite } from './rx-document.ts';\nimport { overwritable } from './overwritable.ts';\nimport type { RxPipeline, RxPipelineOptions } from './plugins/pipeline/index.ts';\nimport { defaultConflictHandler } from './replication-protocol/default-conflict-handler.ts';\nimport { rxChangeEventBulkToRxChangeEvents } from './rx-change-event.ts';\n\nconst HOOKS_WHEN = ['pre', 'post'] as const;\ntype HookWhenType = typeof HOOKS_WHEN[number];\nconst HOOKS_KEYS = ['insert', 'save', 'remove', 'create'] as const;\ntype HookKeyType = typeof HOOKS_KEYS[number];\nlet hooksApplied = false;\n\nexport class RxCollectionBase<\n InstanceCreationOptions,\n RxDocumentType = { [prop: string]: any; },\n OrmMethods = {},\n StaticMethods = { [key: string]: any; },\n Reactivity = any\n> {\n\n\n /**\n * Stores all 'normal' documents\n */\n public storageInstance: WrappedRxStorageInstance = {} as any;\n public readonly timeouts: Set> = new Set();\n public incrementalWriteQueue: IncrementalWriteQueue = {} as any;\n\n\n /**\n * Before reads, all these methods are awaited. Used to \"block\" reads\n * depending on other processes, like when the RxPipeline is running.\n */\n public readonly awaitBeforeReads = new Set<() => MaybePromise>();\n\n constructor(\n public readonly 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 if (database) { // might be falsy on pseudoInstance\n this.eventBulks$ = database.eventBulks$.pipe(\n filter(changeEventBulk => changeEventBulk.collectionName === this.name)\n );\n } else { }\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 * Internally only use eventBulks$\n * Do not use .$ or .observable$ because that has to transform\n * the events which decreases performance.\n */\n public readonly eventBulks$: Observable> = {} as any;\n\n\n /**\n * When the collection is closed,\n * these functions will be called an awaited.\n * Used to automatically clean up stuff that\n * belongs to this collection.\n */\n public onClose: (() => MaybePromise)[] = [];\n public closed = false;\n\n public onRemove: (() => MaybePromise)[] = [];\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 this.$ = this.eventBulks$.pipe(\n mergeMap(changeEventBulk => rxChangeEventBulkToRxChangeEvents(changeEventBulk)),\n );\n this.checkpoint$ = this.eventBulks$.pipe(\n map(changeEventBulk => changeEventBulk.checkpoint),\n );\n\n this._changeEventBuffer = createChangeEventBuffer(this.asRxCollection);\n let documentConstructor: any;\n this._docCache = new DocumentCache(\n this.schema.primaryPath,\n this.eventBulks$.pipe(\n filter(bulk => !bulk.isLocal),\n map(bulk => bulk.events)\n ),\n docData => {\n if (!documentConstructor) {\n documentConstructor = getRxDocumentConstructor(this.asRxCollection);\n }\n return createNewRxDocument(this.asRxCollection, documentConstructor, docData);\n }\n );\n\n\n const listenToRemoveSub = this.database.internalStore.changeStream().pipe(\n filter(bulk => {\n const key = this.name + '-' + this.schema.version;\n const found = bulk.events.find(event => {\n return (\n event.documentData.context === 'collection' &&\n event.documentData.key === key &&\n event.operation === 'DELETE'\n );\n });\n return !!found;\n })\n ).subscribe(async () => {\n await this.close();\n await Promise.all(this.onRemove.map(fn => fn()));\n });\n this._subs.push(listenToRemoveSub);\n\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 isLocal: false,\n internal: false,\n collectionName: this.name,\n storageToken: databaseStorageToken,\n events: eventBulk.events,\n databaseToken: this.database.token,\n checkpoint: eventBulk.checkpoint,\n context: eventBulk.context\n };\n this.database.$emit(changeEventBulk);\n });\n this._subs.push(subDocs);\n\n 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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\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 as any);\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 ensureRxCollectionIsNotClosed(this);\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\n const ids = new Set();\n\n /**\n * This code is a bit redundant for better performance.\n * Instead of iterating multiple times,\n * we directly transform the input to a write-row array.\n */\n let insertRows: BulkWriteRow[];\n if (this.hasHooks('pre', 'insert')) {\n insertRows = await Promise.all(\n docsData.map(docData => {\n const useDocData = fillObjectDataBeforeInsert(this.schema, docData);\n return this._runHooks('pre', 'insert', useDocData)\n .then(() => {\n ids.add((useDocData as any)[primaryPath]);\n return { document: useDocData };\n });\n })\n );\n } else {\n insertRows = new Array(docsData.length);\n const schema = this.schema;\n for (let index = 0; index < docsData.length; index++) {\n const docData = docsData[index];\n const useDocData = fillObjectDataBeforeInsert(schema, docData);\n ids.add((useDocData as any)[primaryPath]);\n insertRows[index] = { document: useDocData };\n }\n }\n\n\n if (ids.size !== docsData.length) {\n throw newRxError('COL22', {\n collection: this.name,\n args: {\n documents: docsData\n }\n });\n }\n\n const results = await this.storageInstance.bulkWrite(\n insertRows,\n 'rx-collection-bulk-insert'\n );\n\n\n /**\n * Often the user does not need to access the RxDocuments of the bulkInsert() call.\n * So we transform the data to RxDocuments only if needed to use less CPU performance.\n */\n let rxDocuments: RxDocument[];\n const collection = this;\n const ret = {\n get success() {\n if (!rxDocuments) {\n const success = getWrittenDocumentsFromBulkWriteResponse(\n collection.schema.primaryPath,\n insertRows,\n results\n );\n rxDocuments = mapDocumentsDataToCacheDocs(collection._docCache, success);\n }\n return rxDocuments;\n },\n error: results.error\n };\n\n if (this.hasHooks('post', 'insert')) {\n const docsMap: Map = new Map();\n insertRows.forEach(row => {\n const doc = row.document;\n docsMap.set((doc as any)[primaryPath] as any, doc);\n });\n await Promise.all(\n ret.success.map(doc => {\n return this._runHooks(\n 'post',\n 'insert',\n docsMap.get(doc.primary),\n doc\n );\n })\n );\n }\n\n return ret;\n }\n\n async bulkRemove(\n /**\n * You can either remove the documents by their ids\n * or by directly providing the RxDocument instances\n * if you have them already. This improves performance a bit.\n */\n idsOrDocs: string[] | RxDocument[]\n ): Promise<{\n success: RxDocument[];\n error: RxStorageWriteError[];\n }> {\n ensureRxCollectionIsNotClosed(this);\n const primaryPath = this.schema.primaryPath;\n /**\n * Optimization shortcut,\n * do nothing when called with an empty array\n */\n if (idsOrDocs.length === 0) {\n return {\n success: [],\n error: []\n };\n }\n\n let rxDocumentMap: Map>;\n if (typeof idsOrDocs[0] === 'string') {\n rxDocumentMap = await this.findByIds(idsOrDocs as string[]).exec();\n } else {\n rxDocumentMap = new Map();\n (idsOrDocs as RxDocument[]).forEach(d => rxDocumentMap.set(d.primary, d));\n }\n\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\n const success = getWrittenDocumentsFromBulkWriteResponse(\n this.schema.primaryPath,\n removeDocs,\n results\n );\n\n const deletedRxDocuments: RxDocument[] = [];\n const successIds: string[] = success.map(d => {\n const id = d[primaryPath] as string;\n const doc = this._docCache.getCachedRxDocument(d);\n deletedRxDocuments.push(doc);\n return id;\n });\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\n return {\n success: deletedRxDocuments,\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 ensureRxCollectionIsNotClosed(this);\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.getCachedRxDocuments([docDataInDb])[0];\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 ensureRxCollectionIsNotClosed(this);\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 ensureRxCollectionIsNotClosed(this);\n const useJson = fillObjectDataBeforeInsert(this.schema, json);\n const primary: string = useJson[this.schema.primaryPath] as any;\n if (!primary) {\n throw newRxError('COL4', {\n data: json\n });\n }\n\n // ensure that it won't try 2 parallel runs\n let queue = this._incrementalUpsertQueues.get(primary);\n if (!queue) {\n queue = PROMISE_RESOLVE_VOID;\n }\n queue = queue\n .then(() => _incrementalUpsertEnsureRxDocumentExists(this as any, primary as any, useJson))\n .then((wasInserted) => {\n if (!wasInserted.inserted) {\n return _incrementalUpsertUpdate(wasInserted.doc, useJson);\n } else {\n return wasInserted.doc;\n }\n });\n this._incrementalUpsertQueues.set(primary, queue);\n return queue;\n }\n\n find(queryObj?: MangoQuery): RxQuery<\n RxDocumentType,\n RxDocument[],\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n\n runPluginHooks('prePrepareRxQuery', {\n op: 'find',\n queryObj,\n collection: this\n });\n\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n\n const query = createRxQuery('find', queryObj, this as any);\n return query as any;\n }\n\n findOne(\n queryObj?: MangoQueryNoLimit | string\n ): RxQuery<\n RxDocumentType,\n RxDocument | null,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n\n runPluginHooks('prePrepareRxQuery', {\n op: 'findOne',\n queryObj,\n collection: this\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 // cannot have limit on findOne queries because it will be overwritten\n if ((queryObj as MangoQuery).limit) {\n throw newRxError('QU6');\n }\n\n queryObj = flatClone(queryObj);\n (queryObj as any).limit = 1;\n query = createRxQuery('findOne', queryObj, this as any);\n }\n\n\n return query as any;\n }\n\n count(queryObj?: MangoQuerySelectorAndIndex): RxQuery<\n RxDocumentType,\n number,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\n if (!queryObj) {\n queryObj = _getDefaultQuery();\n }\n const query = createRxQuery('count', queryObj, this as any);\n return query as any;\n }\n\n /**\n * find a list documents by their primary key\n * has way better performance then running multiple findOne() or a find() with a complex $or-selected\n */\n findByIds(\n ids: string[]\n ): RxQuery<\n RxDocumentType,\n Map>,\n OrmMethods,\n Reactivity\n > {\n ensureRxCollectionIsNotClosed(this);\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 addPipeline(_options: RxPipelineOptions): Promise> {\n throw pluginMissing('pipeline');\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 /**\n * Performance shortcut\n * so that we not have to build the empty object.\n */\n if (\n !this.hooks[key] ||\n !this.hooks[key][when]\n ) {\n return false;\n }\n\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 if (!this.hasHooks(when, key)) {\n return;\n }\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 closed\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 async close(): Promise {\n if (this.closed) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n\n await Promise.all(this.onClose.map(fn => fn()));\n\n /**\n * Settings closed = 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.closed = true;\n\n\n Array.from(this.timeouts).forEach(timeout => clearTimeout(timeout));\n if (this._changeEventBuffer) {\n this._changeEventBuffer.close();\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(() => 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('postCloseRxCollection', this).then(() => true);\n });\n }\n\n /**\n * remove all data of the collection\n */\n async remove(): Promise {\n await this.close();\n await Promise.all(this.onRemove.map(fn => fn()));\n /**\n * TODO here we should pass the already existing\n * storage instances instead of creating new ones.\n */\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.getCachedRxDocuments([docDataFromCache])[0],\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 as Error));\n });\n });\n}\n\nexport function isRxCollection(obj: any): boolean {\n return obj instanceof RxCollectionBase;\n}\n"],"mappings":";AAAA,SACIA,MAAM,EACNC,GAAG,EACHC,QAAQ,QACL,MAAM;AAEb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UAAU,CAACrB,cAAc,CAAC,CAAC;MACrC;MACA,OAAO2B,GAAG;IACd,CAAC,CAAC,CACDZ,IAAI,CAAC,MAAM;MACRjH,cAAc,CAAC,oBAAoB,EAAE;QACjCuH,UAAU;QACV0H,OAAO,EAAE;UACLjO,IAAI;UACJC,MAAM;UACNU,eAAe;UACfR,uBAAuB;UACvBC,mBAAmB;UACnBC,OAAO;UACPC,WAAW;UACXC,OAAO;UACPC,sBAAsB;UACtB+M,cAAc;UACd9M;QACJ;MACJ,CAAC,CAAC;MACF,OAAO8F,UAAU;IACrB,CAAC;IACD;AACZ;AACA;AACA,OAHY,CAIC2H,KAAK,CAACtF,GAAG,IAAI;MACV,OAAOjI,eAAe,CAACmD,KAAK,CAAC,CAAC,CACzBmC,IAAI,CAAC,MAAMlC,OAAO,CAACoK,MAAM,CAACvF,GAAY,CAAC,CAAC;IACjD,CAAC,CAAC;EACV,CAAC,CAAC;AACN;AAEA,OAAO,SAASwF,cAAcA,CAACC,GAAQ,EAAW;EAC9C,OAAOA,GAAG,YAAYvO,gBAAgB;AAC1C","ignoreList":[]} \ 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 e3af896cace..cecd57b142f 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 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 storage?: string;\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 url?: string;\n extensions?: Record;\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":"","ignoreList":[]} \ 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 storage?: string;\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 url?: string;\n extensions?: Record;\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 * For easier debugging,\n * we directly put the schema into the error.\n */\n schema: RxJsonSchema>;\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":"","ignoreList":[]} \ No newline at end of file diff --git a/dist/types/plugins/pipeline/rx-pipeline.d.ts b/dist/types/plugins/pipeline/rx-pipeline.d.ts index 8648b502a3d..345b159b641 100644 --- a/dist/types/plugins/pipeline/rx-pipeline.d.ts +++ b/dist/types/plugins/pipeline/rx-pipeline.d.ts @@ -17,6 +17,12 @@ export declare class RxPipeline { somethingChanged: Subject; secretFunctionName: string; waitBeforeWriteFn: () => Promise; + /** + * The handler of the pipeline must never throw. + * If it did anyway, the pipeline will be stuck and always + * throw the previous error on all operations. + */ + error: any; constructor(identifier: string, source: RxCollection, destination: RxCollection, handler: RxPipelineHandler, batchSize?: number); trigger(): void; awaitIdle(): Promise; diff --git a/dist/types/plugins/storage-denokv/index.d.ts b/dist/types/plugins/storage-denokv/index.d.ts index 864896ff0bd..fe76b35b20f 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 = "16.0.0-beta.1"; + readonly rxdbVersion = "16.0.0-beta.2"; 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 40c947a9466..924cbdb0f1b 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 = "16.0.0-beta.1"; + readonly rxdbVersion = "16.0.0-beta.2"; constructor(settings: DexieSettings); createStorageInstance(params: RxStorageInstanceCreationParams): Promise>; } 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 a764f4cc3a1..f22424067ab 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 = "16.0.0-beta.1"; + readonly rxdbVersion = "16.0.0-beta.2"; 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 ed60b961795..2810ad9daef 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 = "16.0.0-beta.1"; + readonly rxdbVersion = "16.0.0-beta.2"; private seed; private lastRequestId; messageChannelIfOneMode?: Promise; diff --git a/dist/types/plugins/utils/utils-rxdb-version.d.ts b/dist/types/plugins/utils/utils-rxdb-version.d.ts index 90e46b5c42d..50ee712d24b 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 = "16.0.0-beta.1"; +export declare const RXDB_VERSION = "16.0.0-beta.2"; diff --git a/dist/types/rx-database.d.ts b/dist/types/rx-database.d.ts index 90120149a2e..efcfb5c996e 100644 --- a/dist/types/rx-database.d.ts +++ b/dist/types/rx-database.d.ts @@ -28,7 +28,7 @@ export declare class RxDatabaseBase | undefined; readonly idleQueue: IdleQueue; - readonly rxdbVersion = "16.0.0-beta.1"; + readonly rxdbVersion = "16.0.0-beta.2"; /** * Contains all known non-closed storage instances * that belong to this database. diff --git a/dist/types/types/rx-error.d.ts b/dist/types/types/rx-error.d.ts index a0e04d80aec..d1e9e98b6cb 100644 --- a/dist/types/types/rx-error.d.ts +++ b/dist/types/types/rx-error.d.ts @@ -182,6 +182,11 @@ export type RxStorageWriteErrorValidation = RxStorageWriteErrorBase>; }; export type RxStorageWriteErrorAttachment = RxStorageWriteErrorBase & { diff --git a/package.json b/package.json index 04743cbdcf4..ffd015ee6d1 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "rxdb", "description": "A local-first realtime NoSQL Database for JavaScript applications - https://rxdb.info/", - "version": "16.0.0-beta.1", + "version": "16.0.0-beta.2", "author": "pubkey", "repository": { "type": "git", diff --git a/src/plugins/utils/utils-rxdb-version.ts b/src/plugins/utils/utils-rxdb-version.ts index d0b847cb180..01112437560 100644 --- a/src/plugins/utils/utils-rxdb-version.ts +++ b/src/plugins/utils/utils-rxdb-version.ts @@ -1,4 +1,4 @@ /** * This file is replaced in the 'npm run build:version' script. */ -export const RXDB_VERSION = '16.0.0-beta.1'; +export const RXDB_VERSION = '16.0.0-beta.2';