diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a91ed219ce..26ff06f0c6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ -### 16.0.0-beta.8 (10 December 2024) +### 16.0.0-beta.9 (10 December 2024) 🚀 **RxDB v16 is released** diff --git a/dist/cjs/plugins/dev-mode/error-messages.js b/dist/cjs/plugins/dev-mode/error-messages.js index 0b1b55a92ac..33aceadfe67 100644 --- a/dist/cjs/plugins/dev-mode/error-messages.js +++ b/dist/cjs/plugins/dev-mode/error-messages.js @@ -234,6 +234,8 @@ var ERROR_MESSAGES = exports.ERROR_MESSAGES = { DXE1: 'non-required index fields are not possible with the dexie.js RxStorage: https://github.com/pubkey/rxdb/pull/6643#issuecomment-2505310082', // removed in 15.0.0, added boolean index support to dexie storage - DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index', + // plugins/storage-remote + RM1: 'Cannot communicate with a remote that was build on a different RxDB version. Did you forget to rebuild your workers when updating RxDB?', /** * Should never be thrown, use this for * null checks etc. so you do not have to increase the diff --git a/dist/cjs/plugins/dev-mode/error-messages.js.map b/dist/cjs/plugins/dev-mode/error-messages.js.map index ab6d97dfe0d..ebb0cbaf2e4 100644 --- a/dist/cjs/plugins/dev-mode/error-messages.js.map +++ b/dist/cjs/plugins/dev-mode/error-messages.js.map @@ -1 +1 @@ -{"version":3,"file":"error-messages.js","names":["_utilsPremium","require","ERROR_MESSAGES","exports","UT1","UT2","UT3","UT4","UT5","UT6","UT7","PL1","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","QU16","QU17","QU18","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB9","DB11","DB12","DB13","DB14","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL20","COL21","CONFLICT","COL22","COL23","NON_PREMIUM_COLLECTION_LIMIT","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DOC20","DOC21","DOC22","DOC23","DOC24","DM1","DM2","DM3","DM4","DM5","AT1","EN1","EN2","EN3","EN4","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC4","RC5","RC6","RC7","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_WEBRTC_PEER","RC_COUCHDB_1","RC_COUCHDB_2","RC_OUTDATED","RC_UNAUTHORIZED","RC_FORBIDDEN","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","SC40","SC41","DVM1","VD1","VD2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","DXE1","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\nimport { NON_PREMIUM_COLLECTION_LIMIT } from '../utils/utils-premium.ts';\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n UT7: 'attachments.compression is enabled but no attachment-compression plugin is used',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin.',\n // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importing a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n QU16: '$regex queries must be defined by a string, not an RegExp instance. ' +\n 'This is because RegExp objects cannot be JSON stringified and also they are mutable which would be dangerous',\n QU17: 'Chained queries cannot be used on findByIds() RxQuery instances',\n QU18: 'Malformated query result data. This likely happens because you create a OPFS-storage RxDatabase inside of a worker but did not set the usesRxDatabaseInWorker setting. https://rxdb.info/rx-storage-opfs.html#setting-usesrxdatabaseinworker-when-a-rxdatabase-is-also-used-inside-of-the-worker ',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://rxdb.info/questions-answers.html?console=qa#cant-change-the-schema ',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'createRxDatabase(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional-\\n' +\n 'This often happens in react projects with hot reload that reloads the code without reloading the process.',\n DB9: 'ignoreDuplicate is only allowed in dev-mode and must never be used in production',\n // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n DB12: 'RxDatabase.addCollections(): could not write to internal store',\n DB13: 'createRxDatabase(): Invalid db-name or collection name, name contains the dollar sign',\n DB14: 'no custom reactivity factory added on database creation',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.incrementalUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string. Notice that in RxDB, primary keys must be strings and cannot be numbers.',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n COL20: 'Storage write error',\n COL21: 'The RxCollection is closed or removed already, either from this JavaScript realm or from another, like a browser tab',\n CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision',\n COL22: '.bulkInsert() and .bulkUpsert() cannot be run with multiple documents that have the same primary key',\n COL23: 'In the open-source version of RxDB, the amount of collections that can exist in parallel is limited to '+NON_PREMIUM_COLLECTION_LIMIT+'. If you already purchased the premium access, you can remove this limit: https://rxdb.info/rx-collection.html#faq',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.close() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n DOC20: 'PrimaryKey missing',\n DOC21: 'PrimaryKey must be equal to PrimaryKey.trim(). It cannot start or end with a whitespace',\n DOC22: 'PrimaryKey must not contain a linebreak',\n DOC23: 'PrimaryKey must not contain a double-quote [\"]',\n DOC24: 'Given document data could not be structured cloned. This happens if you pass non-plain-json data into it, like a Date() object or a Function. ' +\n 'In vue.js this happens if you use ref() on the document data which transforms it into a Proxy object.',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n DM4: 'Migration errored',\n DM5: 'Cannot open database state with newer RxDB version. You have to migrate your database state first. See https://rxdb.info/migration-storage.html?console=storage ',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption-crypto-js.js\n EN1: 'password is not valid',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n EN4: 'Password not valid',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'replicateCouchDB() query must be from the same RxCollection',\n // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC7: 'SimplePeer requires to have process.nextTick() polyfilled, see https://rxdb.info/replication-webrtc.html?console=webrtc ',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_WEBRTC_PEER: 'RxReplication WebRTC Peer has error',\n RC_COUCHDB_1: 'replicateCouchDB() url must end with a slash like \\'https://example.com/mydatabase/\\'',\n RC_COUCHDB_2: 'replicateCouchDB() did not get valid result with rows.',\n RC_OUTDATED: 'Outdated client, update required. Replication was canceled',\n RC_UNAUTHORIZED: 'Unauthorized client, update the replicationState.headers to set correct auth data',\n RC_FORBIDDEN: 'Client behaves wrong so the replication was canceled. Mostly happens if the client tries to write data that it is not allowed to',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n // removed in 16.0.0 - SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n SC40: '$ref fields in the schema are not allowed. RxDB cannot resolve related schemas because it would have a negative performance impact.' +\n 'It would have to run http requests on runtime. $ref fields should be resolved during build time.',\n SC41: 'minimum, maximum and maxLength values for indexes must be real numbers, not Infinity or -Infinity',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 instead - DEV1: 'dev-mode added multiple times',\n DVM1: 'When dev-mode is enabled, your storage must use one of the schema validators at the top level. This is because most problems people have with RxDB is because they store data that is not valid to the schema which causes strange bugs and problems.',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/storage-dexie/\n DXE1: 'non-required index fields are not possible with the dexie.js RxStorage: https://github.com/pubkey/rxdb/pull/6643#issuecomment-2505310082',\n // removed in 15.0.0, added boolean index support to dexie storage - DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":";;;;;;AAMA,IAAAA,aAAA,GAAAC,OAAA;AANA;AACA;AACA;AACA;AACA;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ACAC,IAAI,EAAE,uPAAuP;EAE7P;EACAC,GAAG,EAAE,kEAAkE;EACvEC,GAAG,EAAE,8BAA8B;EAEnC;EACA;EACA;;EAEA;EACAC,EAAE,EAAE,iEAAiE;EAErE;EACAC,IAAI,EAAE,oDAAoD;EAC1D;EACAC,IAAI,EAAE,iEAAiE;EACvE;;EAEA;EACAC,KAAK,EAAE,oFAAoF;EAC3FC,KAAK,EAAE,yEAAyE;EAChFC,KAAK,EAAE,wGAAwG;EAE/G;EACAC,IAAI,EAAE,0IAA0I;EAChJ;;EAEA;AACJ;AACA;AACA;AACA;EACIC,GAAG,EAAE;AACT,CAAC","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"error-messages.js","names":["_utilsPremium","require","ERROR_MESSAGES","exports","UT1","UT2","UT3","UT4","UT5","UT6","UT7","PL1","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","QU16","QU17","QU18","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB9","DB11","DB12","DB13","DB14","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL20","COL21","CONFLICT","COL22","COL23","NON_PREMIUM_COLLECTION_LIMIT","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DOC20","DOC21","DOC22","DOC23","DOC24","DM1","DM2","DM3","DM4","DM5","AT1","EN1","EN2","EN3","EN4","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC4","RC5","RC6","RC7","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_WEBRTC_PEER","RC_COUCHDB_1","RC_COUCHDB_2","RC_OUTDATED","RC_UNAUTHORIZED","RC_FORBIDDEN","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","SC40","SC41","DVM1","VD1","VD2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","DXE1","RM1","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\nimport { NON_PREMIUM_COLLECTION_LIMIT } from '../utils/utils-premium.ts';\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n UT7: 'attachments.compression is enabled but no attachment-compression plugin is used',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin.',\n // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importing a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n QU16: '$regex queries must be defined by a string, not an RegExp instance. ' +\n 'This is because RegExp objects cannot be JSON stringified and also they are mutable which would be dangerous',\n QU17: 'Chained queries cannot be used on findByIds() RxQuery instances',\n QU18: 'Malformated query result data. This likely happens because you create a OPFS-storage RxDatabase inside of a worker but did not set the usesRxDatabaseInWorker setting. https://rxdb.info/rx-storage-opfs.html#setting-usesrxdatabaseinworker-when-a-rxdatabase-is-also-used-inside-of-the-worker ',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://rxdb.info/questions-answers.html?console=qa#cant-change-the-schema ',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'createRxDatabase(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional-\\n' +\n 'This often happens in react projects with hot reload that reloads the code without reloading the process.',\n DB9: 'ignoreDuplicate is only allowed in dev-mode and must never be used in production',\n // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n DB12: 'RxDatabase.addCollections(): could not write to internal store',\n DB13: 'createRxDatabase(): Invalid db-name or collection name, name contains the dollar sign',\n DB14: 'no custom reactivity factory added on database creation',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.incrementalUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string. Notice that in RxDB, primary keys must be strings and cannot be numbers.',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n COL20: 'Storage write error',\n COL21: 'The RxCollection is closed or removed already, either from this JavaScript realm or from another, like a browser tab',\n CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision',\n COL22: '.bulkInsert() and .bulkUpsert() cannot be run with multiple documents that have the same primary key',\n COL23: 'In the open-source version of RxDB, the amount of collections that can exist in parallel is limited to ' + NON_PREMIUM_COLLECTION_LIMIT + '. If you already purchased the premium access, you can remove this limit: https://rxdb.info/rx-collection.html#faq',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.close() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n DOC20: 'PrimaryKey missing',\n DOC21: 'PrimaryKey must be equal to PrimaryKey.trim(). It cannot start or end with a whitespace',\n DOC22: 'PrimaryKey must not contain a linebreak',\n DOC23: 'PrimaryKey must not contain a double-quote [\"]',\n DOC24: 'Given document data could not be structured cloned. This happens if you pass non-plain-json data into it, like a Date() object or a Function. ' +\n 'In vue.js this happens if you use ref() on the document data which transforms it into a Proxy object.',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n DM4: 'Migration errored',\n DM5: 'Cannot open database state with newer RxDB version. You have to migrate your database state first. See https://rxdb.info/migration-storage.html?console=storage ',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption-crypto-js.js\n EN1: 'password is not valid',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n EN4: 'Password not valid',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'replicateCouchDB() query must be from the same RxCollection',\n // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC7: 'SimplePeer requires to have process.nextTick() polyfilled, see https://rxdb.info/replication-webrtc.html?console=webrtc ',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_WEBRTC_PEER: 'RxReplication WebRTC Peer has error',\n RC_COUCHDB_1: 'replicateCouchDB() url must end with a slash like \\'https://example.com/mydatabase/\\'',\n RC_COUCHDB_2: 'replicateCouchDB() did not get valid result with rows.',\n RC_OUTDATED: 'Outdated client, update required. Replication was canceled',\n RC_UNAUTHORIZED: 'Unauthorized client, update the replicationState.headers to set correct auth data',\n RC_FORBIDDEN: 'Client behaves wrong so the replication was canceled. Mostly happens if the client tries to write data that it is not allowed to',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n // removed in 16.0.0 - SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n SC40: '$ref fields in the schema are not allowed. RxDB cannot resolve related schemas because it would have a negative performance impact.' +\n 'It would have to run http requests on runtime. $ref fields should be resolved during build time.',\n SC41: 'minimum, maximum and maxLength values for indexes must be real numbers, not Infinity or -Infinity',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 instead - DEV1: 'dev-mode added multiple times',\n DVM1: 'When dev-mode is enabled, your storage must use one of the schema validators at the top level. This is because most problems people have with RxDB is because they store data that is not valid to the schema which causes strange bugs and problems.',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/storage-dexie/\n DXE1: 'non-required index fields are not possible with the dexie.js RxStorage: https://github.com/pubkey/rxdb/pull/6643#issuecomment-2505310082',\n // removed in 15.0.0, added boolean index support to dexie storage - DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n // plugins/storage-remote\n RM1: 'Cannot communicate with a remote that was build on a different RxDB version. Did you forget to rebuild your workers when updating RxDB?',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":";;;;;;AAMA,IAAAA,aAAA,GAAAC,OAAA;AANA;AACA;AACA;AACA;AACA;;AAKO,IAAMC,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG;EAC1B;EACAE,GAAG,EAAE,kCAAkC;EACvCC,GAAG,kTAE8F;EACjGC,GAAG,EAAE,yEAAyE;EAC9EC,GAAG,EAAE,qCAAqC;EAC1CC,GAAG,EAAE,mGAAmG;EACxGC,GAAG,EAAE,mFAAmF;EACxFC,GAAG,EAAE,iFAAiF;EAEtF;EACAC,GAAG,EAAE,kCAAkC;EACvC;EACAC,GAAG,EAAE,+FAA+F;EAEpG;EACA;EACAC,EAAE,EAAE,kDAAkD;EACtD;;EA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AAE,yIAAyI;EAE9I;AACJ;AACA;AACA;AACA;EACIC,GAAG,EAAE;AACT,CAAC","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/replication/index.js b/dist/cjs/plugins/replication/index.js index 1faaa04f2a2..a7d54830d09 100644 --- a/dist/cjs/plugins/replication/index.js +++ b/dist/cjs/plugins/replication/index.js @@ -92,6 +92,7 @@ var RxReplicationState = exports.RxReplicationState = /*#__PURE__*/function () { if (this.isStopped()) { return; } + (0, _replicationHelper.preventHibernateBrowserTab)(this); // fill in defaults for pull & push var pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : _replicationHelper.DEFAULT_MODIFIER; diff --git a/dist/cjs/plugins/replication/index.js.map b/dist/cjs/plugins/replication/index.js.map index 2aa8f50f129..5916ad19f5c 100644 --- a/dist/cjs/plugins/replication/index.js.map +++ b/dist/cjs/plugins/replication/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_rxjs","require","_index","_index2","_index3","_rxError","_replicationHelper","_rxDatabaseInternalStore","_plugin","_rxStorageHelper","_overwritable","_hooks","REPLICATION_STATE_BY_COLLECTION","exports","WeakMap","RxReplicationState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","Subject","sent","error","canceled","BehaviorSubject","active","received$","asObservable","sent$","error$","canceled$","active$","onCancel","callOnStart","undefined","remoteEvents$","metaInfoPromise","metaInstanceCollectionName","database","hashFunction","name","join","metaInstanceSchema","getRxReplicationMetaInstanceSchema","schema","jsonSchema","hasEncryption","collectionName","replicationStates","getFromMapOrCreate","onClose","cancel","Object","keys","forEach","key","defineProperty","get","startPromise","Promise","res","_proto","prototype","start","isStopped","pullModifier","modifier","DEFAULT_MODIFIER","pushModifier","metaInfo","metaInstance","all","storage","createStorageInstance","databaseName","databaseInstanceToken","token","multiInstance","options","password","devMode","overwritable","isDevMode","addConnectedStorageToCollection","internalReplicationState","replicateRxStorageInstance","pushBatchSize","batchSize","pullBatchSize","initialCheckpoint","upstream","downstream","forkInstance","storageInstance","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","filter","_v","mergeMap","ev","useEv","flatClone","documents","handlePulledDocuments","map","d","masterChangesSince","checkpoint","done","result","handler","err","emitError","newRxError","errors","toArray","er","errorToPlainJson","direction","next","awaitRetry","ensureNotFalsy","useResult","masterWrite","rows","runAsyncPluginHooks","useRowsOrNull","row","newDocumentState","assumedMasterState","swapDefaultDeletedTodeletedField","useRows","arrayFilterNotEmpty","length","Array","isArray","pushRows","args","rxdb","conflicts","events","subscribe","processed","down","document","up","writeToMasterRow","combineLatest","isActive","stream$","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","getValue","awaitInitialReplication","awaitInSync","t","requestIdlePromise","reSync","emitEvent","PROMISE_RESOLVE_FALSE","promises","fn","toPromise","cancelRxStorageReplication","checkpointQueue","then","close","sub","unsubscribe","complete","remove","removeConnectedStorageFromCollection","replicateRxCollection","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun","PROMISE_RESOLVE_TRUE"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxJsonSchema,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport {\n arrayFilterNotEmpty,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n toArray,\n toPromise\n} from '../../plugins/utils/index.ts';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n getRxReplicationMetaInstanceSchema,\n replicateRxStorageInstance\n} from '../../replication-protocol/index.ts';\nimport { newRxError } from '../../rx-error.ts';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n handlePulledDocuments\n} from './replication-helper.ts';\nimport {\n addConnectedStorageToCollection, removeConnectedStorageFromCollection\n} from '../../rx-database-internal-store.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { hasEncryption } from '../../rx-storage-helper.ts';\nimport { overwritable } from '../../overwritable.ts';\nimport {\n runAsyncPluginHooks\n} from '../../hooks.ts';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n sent: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false) // true when something is running, false when not\n };\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly sent$: Observable> = this.subjects.sent.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n readonly metaInfoPromise: Promise<{ collectionName: string, schema: RxJsonSchema>> }>;\n\n public startPromise: Promise;\n\n public onCancel: (() => void)[] = [];\n\n constructor(\n /**\n * The identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n this.metaInfoPromise = (async () => {\n const metaInstanceCollectionName = 'rx-replication-meta-' + await collection.database.hashFunction([\n this.collection.name,\n this.replicationIdentifier\n ].join('-'));\n const metaInstanceSchema = getRxReplicationMetaInstanceSchema(\n this.collection.schema.jsonSchema,\n hasEncryption(this.collection.schema.jsonSchema)\n );\n return {\n collectionName: metaInstanceCollectionName,\n schema: metaInstanceSchema\n };\n })();\n const replicationStates = getFromMapOrCreate(\n REPLICATION_STATE_BY_COLLECTION,\n collection,\n () => []\n );\n replicationStates.push(this);\n\n // stop the replication when the collection gets closed\n this.collection.onClose.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance, any, {}, any>;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n\n const metaInfo = await this.metaInfoPromise;\n\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance>({\n databaseName: database.name,\n collectionName: metaInfo.collectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance,\n options: {},\n schema: metaInfo.schema,\n password: database.password,\n devMode: overwritable.isDevMode()\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInfo.collectionName,\n metaInfo.schema\n )\n ]);\n this.metaInstance = metaInstance;\n\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n initialCheckpoint: {\n upstream: this.push ? this.push.initialCheckpoint : undefined,\n downstream: this.pull ? this.pull.initialCheckpoint : undefined\n },\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rxdbreplication' + this.replicationIdentifier,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n filter(_v => !!this.pull),\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n useEv.documents = handlePulledDocuments(this.collection, this.deletedField, useEv.documents);\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType | undefined,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n useResult.documents = handlePulledDocuments(this.collection, this.deletedField, useResult.documents);\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n\n await runAsyncPluginHooks('preReplicationMasterWrite', {\n rows,\n collection: this.collection\n });\n\n const useRowsOrNull = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.newDocumentState === null) {\n return null;\n }\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n return row;\n })\n );\n const useRows: RxReplicationWriteToMasterRow[] = useRowsOrNull.filter(arrayFilterNotEmpty);\n\n let result: WithDeleted[] = null as any;\n\n // In case all the rows have been filtered and nothing has to be sent\n if (useRows.length === 0) {\n done = true;\n result = [];\n }\n\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n if (this.isStopped()) {\n return [];\n }\n\n await runAsyncPluginHooks('preReplicationMasterWriteDocumentsHandle', {\n result,\n collection: this.collection\n });\n\n const conflicts = handlePulledDocuments(this.collection, this.deletedField, ensureNotFalsy(result));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.sent.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * To reduce the amount of re-renders and make testing\n * and to make the whole behavior more predictable,\n * we await these things multiple times.\n * For example the state might be in sync already and at the\n * exact same time a pull.stream$ event comes in and we want to catch\n * that in the same call to awaitInSync() instead of resolving\n * while actually the state is not in sync.\n */\n let t = 2;\n while (t > 0) {\n t--;\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n }\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n async cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = this.onCancel.map(fn => toPromise(fn()));\n\n if (this.internalReplicationState) {\n await cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.sent.complete();\n\n return Promise.all(promises);\n }\n\n async remove() {\n await ensureNotFalsy(this.metaInstance).remove();\n const metaInfo = await this.metaInfoPromise;\n await this.cancel();\n await removeConnectedStorageFromCollection(\n this.collection,\n metaInfo.collectionName,\n metaInfo.schema\n );\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n /**\n * It is a common error to forget to add these config\n * objects. So we check here because it makes no sense\n * to start a replication with neither push nor pull.\n */\n if (!pull && !push) {\n throw newRxError('UT3', {\n collection: collection.name,\n args: {\n replicationIdentifier\n }\n });\n }\n\n const replicationState = new RxReplicationState(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":";;;;;;;;AAOA,IAAAA,KAAA,GAAAC,OAAA;AA0BA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAWA,IAAAG,OAAA,GAAAH,OAAA;AAOA,IAAAI,QAAA,GAAAJ,OAAA;AACA,IAAAK,kBAAA,GAAAL,OAAA;AAMA,IAAAM,wBAAA,GAAAN,OAAA;AAGA,IAAAO,OAAA,GAAAP,OAAA;AACA,IAAAQ,gBAAA,GAAAR,OAAA;AACA,IAAAS,aAAA,GAAAT,OAAA;AACA,IAAAU,MAAA,GAAAV,OAAA;AAjEA;AACA;AACA;AACA;AACA;AACA;;AAiEO,IAAMW,+BAAsF,GAAAC,OAAA,CAAAD,+BAAA,GAAG,IAAIE,OAAO,CAAC,CAAC;AAAC,IAEvGC,kBAAkB,GAAAF,OAAA,CAAAE,kBAAA;EAsB3B,SAAAA;EACI;AACR;AACA;AACA;EACwBC,qBAA6B,EAC7BC,UAAmC,EACnCC,YAAoB,EACpBC,IAAwD,EACxDC,IAAwC,EACxCC,IAAc,EACvBC,SAAkB,EAClBC,SAAmB,EAC5B;IAAA,KAlCcC,IAAI,GAAmB,EAAE;IAAA,KACzBC,QAAQ,GAAG;MACvBC,QAAQ,EAAE,IAAIC,aAAO,CAA4B,CAAC;MAAE;MACpDC,IAAI,EAAE,IAAID,aAAO,CAAyB,CAAC;MAAE;MAC7CE,KAAK,EAAE,IAAIF,aAAO,CAAwB,CAAC;MAAE;MAC7CG,QAAQ,EAAE,IAAIC,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AAI;EACJC,IAAI;EACJC,IAAI,GAAG,IAAI;EACXC,SAAS,GAAG,IAAI,GAAG,CAAC;EACpBiK,iBAAiB,GAAG,IAAI;EACxBhK,SAAS,GAAG;AAC+B,CAAC,EACH;EAC7C,IAAAiK,mBAAW,EAACC,+BAAwB,CAAC;;EAErC;AACJ;AACA;AACA;AACA;EACI,IAAI,CAACtK,IAAI,IAAI,CAACC,IAAI,EAAE;IAChB,MAAM,IAAAuG,mBAAU,EAAC,KAAK,EAAE;MACpB1G,UAAU,EAAEA,UAAU,CAAC8B,IAAI;MAC3BoG,IAAI,EAAE;QACFnI;MACJ;IACJ,CAAC,CAAC;EACN;EAEA,IAAM0K,gBAAgB,GAAG,IAAI3K,kBAAkB,CAC3CC,qBAAqB,EACrBC,UAAU,EACVC,YAAY,EACZC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SACJ,CAAC;EAGDoK,4BAA4B,CAACJ,iBAAiB,EAAEG,gBAAgB,CAAC;EACjE,OAAOA,gBAAgB;AAC3B;AAGO,SAASC,4BAA4BA,CACxCJ,iBAA0B,EAC1BG,gBAA8C,EAChD;EACE;AACJ;AACA;AACA;EACI,IAAME,qBAAqB,GAAGL,iBAAiB,IAAIG,gBAAgB,CAACzK,UAAU,CAAC4B,QAAQ,CAACuC,aAAa;EACrG,IAAMyG,WAAyB,GAAGD,qBAAqB,GAAGF,gBAAgB,CAACzK,UAAU,CAAC4B,QAAQ,CAAC0I,iBAAiB,CAAC,CAAC,GAAGO,4BAAoB;EACzI,OAAOD,WAAW,CAACd,IAAI,CAAC,MAAM;IAC1B,IAAIW,gBAAgB,CAACnH,SAAS,CAAC,CAAC,EAAE;MAC9B;IACJ;IACA,IAAImH,gBAAgB,CAACnK,SAAS,EAAE;MAC5BmK,gBAAgB,CAACpH,KAAK,CAAC,CAAC;IAC5B;EACJ,CAAC,CAAC;AACN","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["_rxjs","require","_index","_index2","_index3","_rxError","_replicationHelper","_rxDatabaseInternalStore","_plugin","_rxStorageHelper","_overwritable","_hooks","REPLICATION_STATE_BY_COLLECTION","exports","WeakMap","RxReplicationState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","Subject","sent","error","canceled","BehaviorSubject","active","received$","asObservable","sent$","error$","canceled$","active$","onCancel","callOnStart","undefined","remoteEvents$","metaInfoPromise","metaInstanceCollectionName","database","hashFunction","name","join","metaInstanceSchema","getRxReplicationMetaInstanceSchema","schema","jsonSchema","hasEncryption","collectionName","replicationStates","getFromMapOrCreate","onClose","cancel","Object","keys","forEach","key","defineProperty","get","startPromise","Promise","res","_proto","prototype","start","isStopped","preventHibernateBrowserTab","pullModifier","modifier","DEFAULT_MODIFIER","pushModifier","metaInfo","metaInstance","all","storage","createStorageInstance","databaseName","databaseInstanceToken","token","multiInstance","options","password","devMode","overwritable","isDevMode","addConnectedStorageToCollection","internalReplicationState","replicateRxStorageInstance","pushBatchSize","batchSize","pullBatchSize","initialCheckpoint","upstream","downstream","forkInstance","storageInstance","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","filter","_v","mergeMap","ev","useEv","flatClone","documents","handlePulledDocuments","map","d","masterChangesSince","checkpoint","done","result","handler","err","emitError","newRxError","errors","toArray","er","errorToPlainJson","direction","next","awaitRetry","ensureNotFalsy","useResult","masterWrite","rows","runAsyncPluginHooks","useRowsOrNull","row","newDocumentState","assumedMasterState","swapDefaultDeletedTodeletedField","useRows","arrayFilterNotEmpty","length","Array","isArray","pushRows","args","rxdb","conflicts","events","subscribe","processed","down","document","up","writeToMasterRow","combineLatest","isActive","stream$","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","getValue","awaitInitialReplication","awaitInSync","t","requestIdlePromise","reSync","emitEvent","PROMISE_RESOLVE_FALSE","promises","fn","toPromise","cancelRxStorageReplication","checkpointQueue","then","close","sub","unsubscribe","complete","remove","removeConnectedStorageFromCollection","replicateRxCollection","waitForLeadership","addRxPlugin","RxDBLeaderElectionPlugin","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun","PROMISE_RESOLVE_TRUE"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxJsonSchema,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport {\n arrayFilterNotEmpty,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n toArray,\n toPromise\n} from '../../plugins/utils/index.ts';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n getRxReplicationMetaInstanceSchema,\n replicateRxStorageInstance\n} from '../../replication-protocol/index.ts';\nimport { newRxError } from '../../rx-error.ts';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n handlePulledDocuments,\n preventHibernateBrowserTab\n} from './replication-helper.ts';\nimport {\n addConnectedStorageToCollection, removeConnectedStorageFromCollection\n} from '../../rx-database-internal-store.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { hasEncryption } from '../../rx-storage-helper.ts';\nimport { overwritable } from '../../overwritable.ts';\nimport {\n runAsyncPluginHooks\n} from '../../hooks.ts';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n sent: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false) // true when something is running, false when not\n };\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly sent$: Observable> = this.subjects.sent.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n readonly metaInfoPromise: Promise<{ collectionName: string, schema: RxJsonSchema>> }>;\n\n public startPromise: Promise;\n\n public onCancel: (() => void)[] = [];\n\n constructor(\n /**\n * The identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n this.metaInfoPromise = (async () => {\n const metaInstanceCollectionName = 'rx-replication-meta-' + await collection.database.hashFunction([\n this.collection.name,\n this.replicationIdentifier\n ].join('-'));\n const metaInstanceSchema = getRxReplicationMetaInstanceSchema(\n this.collection.schema.jsonSchema,\n hasEncryption(this.collection.schema.jsonSchema)\n );\n return {\n collectionName: metaInstanceCollectionName,\n schema: metaInstanceSchema\n };\n })();\n const replicationStates = getFromMapOrCreate(\n REPLICATION_STATE_BY_COLLECTION,\n collection,\n () => []\n );\n replicationStates.push(this);\n\n // stop the replication when the collection gets closed\n this.collection.onClose.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance, any, {}, any>;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n preventHibernateBrowserTab(this);\n\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n\n const metaInfo = await this.metaInfoPromise;\n\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance>({\n databaseName: database.name,\n collectionName: metaInfo.collectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance,\n options: {},\n schema: metaInfo.schema,\n password: database.password,\n devMode: overwritable.isDevMode()\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInfo.collectionName,\n metaInfo.schema\n )\n ]);\n this.metaInstance = metaInstance;\n\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n initialCheckpoint: {\n upstream: this.push ? this.push.initialCheckpoint : undefined,\n downstream: this.pull ? this.pull.initialCheckpoint : undefined\n },\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rxdbreplication' + this.replicationIdentifier,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n filter(_v => !!this.pull),\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n useEv.documents = handlePulledDocuments(this.collection, this.deletedField, useEv.documents);\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType | undefined,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n useResult.documents = handlePulledDocuments(this.collection, this.deletedField, useResult.documents);\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n\n await runAsyncPluginHooks('preReplicationMasterWrite', {\n rows,\n collection: this.collection\n });\n\n const useRowsOrNull = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.newDocumentState === null) {\n return null;\n }\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n return row;\n })\n );\n const useRows: RxReplicationWriteToMasterRow[] = useRowsOrNull.filter(arrayFilterNotEmpty);\n\n let result: WithDeleted[] = null as any;\n\n // In case all the rows have been filtered and nothing has to be sent\n if (useRows.length === 0) {\n done = true;\n result = [];\n }\n\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n if (this.isStopped()) {\n return [];\n }\n\n await runAsyncPluginHooks('preReplicationMasterWriteDocumentsHandle', {\n result,\n collection: this.collection\n });\n\n const conflicts = handlePulledDocuments(this.collection, this.deletedField, ensureNotFalsy(result));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.sent.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * To reduce the amount of re-renders and make testing\n * and to make the whole behavior more predictable,\n * we await these things multiple times.\n * For example the state might be in sync already and at the\n * exact same time a pull.stream$ event comes in and we want to catch\n * that in the same call to awaitInSync() instead of resolving\n * while actually the state is not in sync.\n */\n let t = 2;\n while (t > 0) {\n t--;\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n }\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n async cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = this.onCancel.map(fn => toPromise(fn()));\n\n if (this.internalReplicationState) {\n await cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.sent.complete();\n\n return Promise.all(promises);\n }\n\n async remove() {\n await ensureNotFalsy(this.metaInstance).remove();\n const metaInfo = await this.metaInfoPromise;\n await this.cancel();\n await removeConnectedStorageFromCollection(\n this.collection,\n metaInfo.collectionName,\n metaInfo.schema\n );\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n /**\n * It is a common error to forget to add these config\n * objects. So we check here because it makes no sense\n * to start a replication with neither push nor pull.\n */\n if (!pull && !push) {\n throw newRxError('UT3', {\n collection: collection.name,\n args: {\n replicationIdentifier\n }\n });\n }\n\n const replicationState = new RxReplicationState(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":";;;;;;;;AAOA,IAAAA,KAAA,GAAAC,OAAA;AA0BA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,OAAA,GAAAF,OAAA;AAWA,IAAAG,OAAA,GAAAH,OAAA;AAOA,IAAAI,QAAA,GAAAJ,OAAA;AACA,IAAAK,kBAAA,GAAAL,OAAA;AAOA,IAAAM,wBAAA,GAAAN,OAAA;AAGA,IAA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Y,EACZC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SACJ,CAAC;EAGDqK,4BAA4B,CAACJ,iBAAiB,EAAEG,gBAAgB,CAAC;EACjE,OAAOA,gBAAgB;AAC3B;AAGO,SAASC,4BAA4BA,CACxCJ,iBAA0B,EAC1BG,gBAA8C,EAChD;EACE;AACJ;AACA;AACA;EACI,IAAME,qBAAqB,GAAGL,iBAAiB,IAAIG,gBAAgB,CAAC1K,UAAU,CAAC4B,QAAQ,CAACwC,aAAa;EACrG,IAAMyG,WAAyB,GAAGD,qBAAqB,GAAGF,gBAAgB,CAAC1K,UAAU,CAAC4B,QAAQ,CAAC2I,iBAAiB,CAAC,CAAC,GAAGO,4BAAoB;EACzI,OAAOD,WAAW,CAACd,IAAI,CAAC,MAAM;IAC1B,IAAIW,gBAAgB,CAACpH,SAAS,CAAC,CAAC,EAAE;MAC9B;IACJ;IACA,IAAIoH,gBAAgB,CAACpK,SAAS,EAAE;MAC5BoK,gBAAgB,CAACrH,KAAK,CAAC,CAAC;IAC5B;EACJ,CAAC,CAAC;AACN","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/replication/replication-helper.js b/dist/cjs/plugins/replication/replication-helper.js index e32d38f9738..17ad2f6171c 100644 --- a/dist/cjs/plugins/replication/replication-helper.js +++ b/dist/cjs/plugins/replication/replication-helper.js @@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { exports.DEFAULT_MODIFIER = void 0; exports.awaitRetry = awaitRetry; exports.handlePulledDocuments = handlePulledDocuments; +exports.preventHibernateBrowserTab = preventHibernateBrowserTab; exports.swapDefaultDeletedTodeletedField = swapDefaultDeletedTodeletedField; var _index = require("../../plugins/utils/index.js"); var _rxSchemaHelper = require("../../rx-schema-helper.js"); @@ -74,4 +75,23 @@ function awaitRetry(collection, retryTime) { window.removeEventListener('online', listener); }); } + +/** + * When a replication is running and the leading tab get hibernated + * by the browser, the replication will be stuck. + * To prevent this, we fire a mouseeven each X seconds while the replication is not canceled. + * + * If you find a better way to prevent hibernation, please make a pull request. + */ +function preventHibernateBrowserTab(replicationState) { + function simulateActivity() { + if (typeof document === 'undefined' || typeof document.dispatchEvent !== 'function') { + return; + } + var event = new Event('mousemove'); + document.dispatchEvent(event); + } + var intervalId = setInterval(simulateActivity, 20 * 1000); // Simulate activity every 20 seconds + replicationState.onCancel.push(() => clearInterval(intervalId)); +} //# sourceMappingURL=replication-helper.js.map \ No newline at end of file diff --git a/dist/cjs/plugins/replication/replication-helper.js.map b/dist/cjs/plugins/replication/replication-helper.js.map index 7dc0df0a0fa..72dc60a0da5 100644 --- a/dist/cjs/plugins/replication/replication-helper.js.map +++ b/dist/cjs/plugins/replication/replication-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"replication-helper.js","names":["_index","require","_rxSchemaHelper","DEFAULT_MODIFIER","d","Promise","resolve","exports","swapDefaultDeletedTodeletedField","deletedField","doc","flatClone","isDeleted","_deleted","handlePulledDocuments","collection","docs","map","useDoc","primaryPath","schema","getComposedPrimaryKeyOfDocumentData","jsonSchema","awaitRetry","retryTime","window","addEventListener","navigator","onLine","promiseWait","listener","onlineAgain","res","removeEventListener","race","then"],"sources":["../../../../src/plugins/replication/replication-helper.ts"],"sourcesContent":["import type {\n RxCollection,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { flatClone } from '../../plugins/utils/index.ts';\nimport { getComposedPrimaryKeyOfDocumentData } from '../../rx-schema-helper.ts';\n\n// does nothing\nexport const DEFAULT_MODIFIER = (d: any) => Promise.resolve(d);\n\n\nexport function swapDefaultDeletedTodeletedField(\n deletedField: string,\n doc: WithDeleted\n): RxDocType {\n if (deletedField === '_deleted') {\n return doc;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!doc._deleted;\n (doc as any)[deletedField] = isDeleted;\n delete (doc as any)._deleted;\n return doc;\n }\n}\n\n/**\n * Must be run over all plain document data\n * that was pulled from the remote.\n * Used to fill up fields or modify the deleted field etc.\n */\nexport function handlePulledDocuments(\n collection: RxCollection,\n deletedField: string,\n docs: RxDocType[]\n): WithDeleted[] {\n return docs.map(doc => {\n const useDoc: WithDeleted = flatClone(doc) as any;\n\n /**\n * Swap out the deleted field\n */\n if (deletedField !== '_deleted') {\n const isDeleted = !!(useDoc as any)[deletedField];\n (useDoc as any)._deleted = isDeleted;\n delete (useDoc as any)[deletedField];\n } else {\n // ensure we have a boolean.\n useDoc._deleted = !!useDoc._deleted;\n }\n\n /**\n * Fill up composed primary\n */\n const primaryPath = collection.schema.primaryPath;\n (useDoc as any)[primaryPath] = getComposedPrimaryKeyOfDocumentData(\n collection.schema.jsonSchema,\n useDoc\n );\n return useDoc as any;\n });\n}\n\n\n/**\n * Like normal promiseWait()\n * but will skip the wait time if the online-state changes.\n */\nexport function awaitRetry(\n collection: RxCollection,\n retryTime: number\n) {\n if (\n typeof window === 'undefined' ||\n typeof window !== 'object' ||\n typeof window.addEventListener === 'undefined' ||\n navigator.onLine\n ) {\n return collection.promiseWait(retryTime);\n }\n\n let listener: any;\n const onlineAgain = new Promise(res => {\n listener = () => {\n window.removeEventListener('online', listener);\n res();\n };\n window.addEventListener('online', listener);\n });\n\n return Promise.race([\n onlineAgain,\n collection.promiseWait(retryTime)\n ]).then(() => {\n window.removeEventListener('online', listener);\n });\n}\n"],"mappings":";;;;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,eAAA,GAAAD,OAAA;AAEA;AACO,IAAME,gBAAgB,GAAIC,CAAM,IAAKC,OAAO,CAACC,OAAO,CAACF,CAAC,CAAC;AAACG,OAAA,CAAAJ,gBAAA,GAAAA,gBAAA;AAGxD,SAASK,gCAAgCA,CAC5CC,YAAoB,EACpBC,GAA2B,EAClB;EACT,IAAID,YAAY,KAAK,UAAU,EAAE;IAC7B,OAAOC,GAAG;EACd,CAAC,MAAM;IACHA,GAAG,GAAG,IAAAC,gBAAS,EAACD,GAAG,CAAC;IACpB,IAAME,SAAS,GAAG,CAAC,CAACF,GAAG,CAACG,Q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,MAAM,CAACQ,mBAAmB,CAAC,QAAQ,EAAEH,QAAQ,CAAC;MAC9CE,GAAG,CAAC,CAAC;IACT,CAAC;IACDP,MAAM,CAACC,gBAAgB,CAAC,QAAQ,EAAEI,QAAQ,CAAC;EAC/C,CAAC,CAAC;EAEF,OAAOzB,OAAO,CAAC6B,IAAI,CAAC,CAChBH,WAAW,EACXhB,UAAU,CAACc,WAAW,CAACL,SAAS,CAAC,CACpC,CAAC,CAACW,IAAI,CAAC,MAAM;IACVV,MAAM,CAACQ,mBAAmB,CAAC,QAAQ,EAAEH,QAAQ,CAAC;EAClD,CAAC,CAAC;AACN","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"replication-helper.js","names":["_index","require","_rxSchemaHelper","DEFAULT_MODIFIER","d","Promise","resolve","exports","swapDefaultDeletedTodeletedField","deletedField","doc","flatClone","isDeleted","_deleted","handlePulledDocuments","collection","docs","map","useDoc","primaryPath","schema","getComposedPrimaryKeyOfDocumentData","jsonSchema","awaitRetry","retryTime","window","addEventListener","navigator","onLine","promiseWait","listener","onlineAgain","res","removeEventListener","race","then","preventHibernateBrowserTab","replicationState","simulateActivity","document","dispatchEvent","event","Event","intervalId","setInterval","onCancel","push","clearInterval"],"sources":["../../../../src/plugins/replication/replication-helper.ts"],"sourcesContent":["import type {\n RxCollection,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { flatClone } from '../../plugins/utils/index.ts';\nimport { getComposedPrimaryKeyOfDocumentData } from '../../rx-schema-helper.ts';\nimport type { RxReplicationState } from './index.ts';\n\n// does nothing\nexport const DEFAULT_MODIFIER = (d: any) => Promise.resolve(d);\n\n\nexport function swapDefaultDeletedTodeletedField(\n deletedField: string,\n doc: WithDeleted\n): RxDocType {\n if (deletedField === '_deleted') {\n return doc;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!doc._deleted;\n (doc as any)[deletedField] = isDeleted;\n delete (doc as any)._deleted;\n return doc;\n }\n}\n\n/**\n * Must be run over all plain document data\n * that was pulled from the remote.\n * Used to fill up fields or modify the deleted field etc.\n */\nexport function handlePulledDocuments(\n collection: RxCollection,\n deletedField: string,\n docs: RxDocType[]\n): WithDeleted[] {\n return docs.map(doc => {\n const useDoc: WithDeleted = flatClone(doc) as any;\n\n /**\n * Swap out the deleted field\n */\n if (deletedField !== '_deleted') {\n const isDeleted = !!(useDoc as any)[deletedField];\n (useDoc as any)._deleted = isDeleted;\n delete (useDoc as any)[deletedField];\n } else {\n // ensure we have a boolean.\n useDoc._deleted = !!useDoc._deleted;\n }\n\n /**\n * Fill up composed primary\n */\n const primaryPath = collection.schema.primaryPath;\n (useDoc as any)[primaryPath] = getComposedPrimaryKeyOfDocumentData(\n collection.schema.jsonSchema,\n useDoc\n );\n return useDoc as any;\n });\n}\n\n\n/**\n * Like normal promiseWait()\n * but will skip the wait time if the online-state changes.\n */\nexport function awaitRetry(\n collection: RxCollection,\n retryTime: number\n) {\n if (\n typeof window === 'undefined' ||\n typeof window !== 'object' ||\n typeof window.addEventListener === 'undefined' ||\n navigator.onLine\n ) {\n return collection.promiseWait(retryTime);\n }\n\n let listener: any;\n const onlineAgain = new Promise(res => {\n listener = () => {\n window.removeEventListener('online', listener);\n res();\n };\n window.addEventListener('online', listener);\n });\n\n return Promise.race([\n onlineAgain,\n collection.promiseWait(retryTime)\n ]).then(() => {\n window.removeEventListener('online', listener);\n });\n}\n\n\n/**\n * When a replication is running and the leading tab get hibernated\n * by the browser, the replication will be stuck.\n * To prevent this, we fire a mouseeven each X seconds while the replication is not canceled.\n * \n * If you find a better way to prevent hibernation, please make a pull request.\n */\nexport function preventHibernateBrowserTab(replicationState: RxReplicationState) {\n function simulateActivity() {\n if (\n typeof document === 'undefined' ||\n typeof document.dispatchEvent !== 'function'\n ) {\n return;\n }\n const event = new Event('mousemove');\n document.dispatchEvent(event);\n }\n\n const intervalId = setInterval(simulateActivity, 20 * 1000); // Simulate activity every 20 seconds\n replicationState.onCancel.push(() => clearInterval(intervalId));\n}\n"],"mappings":";;;;;;;;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B,CAACQ,QAAQ,CAACC,IAAI,CAAC,MAAMC,aAAa,CAACJ,UAAU,CAAC,CAAC;AACnE","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/storage-remote-websocket/index.js b/dist/cjs/plugins/storage-remote-websocket/index.js index 592889b2c44..aed62aca383 100644 --- a/dist/cjs/plugins/storage-remote-websocket/index.js +++ b/dist/cjs/plugins/storage-remote-websocket/index.js @@ -39,7 +39,8 @@ function startRxStorageRemoteWebsocketServer(options) { send(msg) { var ws = (0, _index.getFromMapOrThrow)(websocketByConnectionId, msg.connectionId); ws.send(JSON.stringify(msg)); - } + }, + fakeVersion: options.fakeVersion }; var exposeState = (0, _remote.exposeRxStorageRemote)(exposeSettings); serverState.onConnection$.subscribe(ws => { diff --git a/dist/cjs/plugins/storage-remote-websocket/index.js.map b/dist/cjs/plugins/storage-remote-websocket/index.js.map index 3c9b01ef96c..2cd465024fa 100644 --- a/dist/cjs/plugins/storage-remote-websocket/index.js.map +++ b/dist/cjs/plugins/storage-remote-websocket/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["_rxjs","require","_index","_index2","_remote","_rxStorageRemote","_storageRemoteHelpers","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","startRxStorageRemoteWebsocketServer","options","serverState","startSocketServer","websocketByConnectionId","Map","messages$","Subject","exposeSettings","asObservable","storage","database","customRequestHandler","send","msg","ws","getFromMapOrThrow","connectionId","JSON","stringify","exposeState","exposeRxStorageRemote","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","createErrorAnswer","Error","set","next","getRxStorageRemoteWebsocket","identifier","url","join","getRxStorageRemote","mode","messageChannelCreator","websocketClient","createWebSocketClient","message$","socket","close","PROMISE_RESOLVE_VOID"],"sources":["../../../../src/plugins/storage-remote-websocket/index.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport {\n PROMISE_RESOLVE_VOID,\n getFromMapOrThrow\n} from '../../plugins/utils/index.ts';\nimport {\n createWebSocketClient,\n startSocketServer\n} from '../replication-websocket/index.ts';\nimport { exposeRxStorageRemote } from '../storage-remote/remote.ts';\nimport { getRxStorageRemote } from '../storage-remote/rx-storage-remote.ts';\nimport { createErrorAnswer } from '../storage-remote/storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport type {\n RxStorageRemoteWebsocketClient,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './types.ts';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage as any,\n database: options.database as any,\n customRequestHandler: options.customRequestHandler,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n }\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (\n message.method !== 'create' &&\n message.method !== 'custom'\n ) {\n ws.send(\n JSON.stringify(\n createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))\n )\n );\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\nexport function getRxStorageRemoteWebsocket(\n options: RxStorageRemoteWebsocketClientOptions\n): RxStorageRemoteWebsocketClient {\n const identifier = [\n options.url,\n 'rx-remote-storage-websocket'\n ].join('');\n const storage = getRxStorageRemote({\n identifier,\n mode: options.mode,\n async messageChannelCreator() {\n const messages$ = new Subject();\n const websocketClient = await createWebSocketClient(options as any);\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n return {\n messages$,\n send(msg) {\n return websocketClient.socket.send(JSON.stringify(msg));\n },\n close() {\n websocketClient.socket.close();\n return PROMISE_RESOLVE_VOID;\n }\n };\n\n }\n });\n return storage;\n}\n\n\nexport * from './types.ts';\n\n"],"mappings":";;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAIA,IAAAC,MAAA,GAAAD,OAAA;AAIA,IAAAE,OAAA,GAAAF,OAAA;AAIA,IAAAG,OAAA,GAAAH,OAAA;AACA,IAAAI,gBAAA,GAAAJ,OAAA;AACA,IAAAK,qBAAA,GAAAL,OAAA;AAkGA,IAAAM,MAAA,GAAAN,OAAA;AAAAO,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,MAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,MAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AAtFO,SAASS,mCAAmCA,CAC/CC,OAA8C,EACX;EACnC,IAAMC,WAAW,GAAG,IAAAC,yBAAiB,EAACF,OAAO,CAAC;EAE9C,IAAMG,uBAAuB,GAAG,IAAIC,GAAG,CAAoB,CAAC;EAC5D,IAAMC,SAAS,GAAG,I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UACD;QACJ;QACA1B,uBAAuB,CAACgC,GAAG,CAACnB,YAAY,EAAEF,EAAE,CAAC;MACjD;MACAT,SAAS,CAAC+B,IAAI,CAACP,OAAO,CAAC;IAC3B,CAAC,CAAC;EACN,CAAC,CAAC;EAEF,OAAO;IACH5B,WAAW;IACXkB;EACJ,CAAC;AACL;AAEO,SAASkB,2BAA2BA,CACvCrC,OAA8C,EAChB;EAC9B,IAAMsC,UAAU,GAAG,CACftC,OAAO,CAACuC,GAAG,EACX,6BAA6B,CAChC,CAACC,IAAI,CAAC,EAAE,CAAC;EACV,IAAM/B,OAAO,GAAG,IAAAgC,mCAAkB,EAAC;IAC/BH,UAAU;IACVI,IAAI,EAAE1C,OAAO,CAAC0C,IAAI;IAClB,MAAMC,qBAAqBA,CAAA,EAAG;MAC1B,IAAMtC,SAAS,GAAG,IAAIC,aAAO,CAAoB,CAAC;MAClD,IAAMsC,eAAe,GAAG,MAAM,IAAAC,6BAAqB,EAAC7C,OAAc,CAAC;MACnE4C,eAAe,CAACE,QAAQ,CAACxB,SAAS,CAACT,GAAG,IAAIR,SAAS,CAAC+B,IAAI,CAACvB,GAAG,CAAC,CAAC;MAC9D,OAAO;QACHR,SAAS;QACTO,IAAIA,CAACC,GAAG,EAAE;UACN,OAAO+B,eAAe,CAACG,MAAM,CAACnC,IAAI,CAACK,IAAI,CAACC,SAAS,CAACL,GAAG,CAAC,CAAC;QAC3D,CAAC;QACDmC,KAAKA,CAAA,EAAG;UACJJ,eAAe,CAACG,MAAM,CAACC,KAAK,CAAC,CAAC;UAC9B,OAAOC,2BAAoB;QAC/B;MACJ,CAAC;IAEL;EACJ,CAAC,CAAC;EACF,OAAOxC,OAAO;AAClB","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["_rxjs","require","_index","_index2","_remote","_rxStorageRemote","_storageRemoteHelpers","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","startRxStorageRemoteWebsocketServer","options","serverState","startSocketServer","websocketByConnectionId","Map","messages$","Subject","exposeSettings","asObservable","storage","database","customRequestHandler","send","msg","ws","getFromMapOrThrow","connectionId","JSON","stringify","fakeVersion","exposeState","exposeRxStorageRemote","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","createErrorAnswer","Error","set","next","getRxStorageRemoteWebsocket","identifier","url","join","getRxStorageRemote","mode","messageChannelCreator","websocketClient","createWebSocketClient","message$","socket","close","PROMISE_RESOLVE_VOID"],"sources":["../../../../src/plugins/storage-remote-websocket/index.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport {\n PROMISE_RESOLVE_VOID,\n getFromMapOrThrow\n} from '../../plugins/utils/index.ts';\nimport {\n createWebSocketClient,\n startSocketServer\n} from '../replication-websocket/index.ts';\nimport { exposeRxStorageRemote } from '../storage-remote/remote.ts';\nimport { getRxStorageRemote } from '../storage-remote/rx-storage-remote.ts';\nimport { createErrorAnswer } from '../storage-remote/storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport type {\n RxStorageRemoteWebsocketClient,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './types.ts';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage as any,\n database: options.database as any,\n customRequestHandler: options.customRequestHandler,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n },\n fakeVersion: options.fakeVersion\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (\n message.method !== 'create' &&\n message.method !== 'custom'\n ) {\n ws.send(\n JSON.stringify(\n createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))\n )\n );\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\nexport function getRxStorageRemoteWebsocket(\n options: RxStorageRemoteWebsocketClientOptions\n): RxStorageRemoteWebsocketClient {\n const identifier = [\n options.url,\n 'rx-remote-storage-websocket'\n ].join('');\n const storage = getRxStorageRemote({\n identifier,\n mode: options.mode,\n async messageChannelCreator() {\n const messages$ = new Subject();\n const websocketClient = await createWebSocketClient(options as any);\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n return {\n messages$,\n send(msg) {\n return websocketClient.socket.send(JSON.stringify(msg));\n },\n close() {\n websocketClient.socket.close();\n return PROMISE_RESOLVE_VOID;\n }\n };\n\n }\n });\n return storage;\n}\n\n\nexport * from './types.ts';\n\n"],"mappings":";;;;;;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAIA,IAAAC,MAAA,GAAAD,OAAA;AAIA,IAAAE,OAAA,GAAAF,OAAA;AAIA,IAAAG,OAAA,GAAAH,OAAA;AACA,IAAAI,gBAAA,GAAAJ,OAAA;AACA,IAAAK,qBAAA,GAAAL,OAAA;AAmGA,IAAAM,MAAA,GAAAN,OAAA;AAAAO,MAAA,CAAAC,IAAA,CAAAF,MAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,C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O,IAAIA,CAACC,GAAG,EAAE;UACN,OAAOgC,eAAe,CAACG,MAAM,CAACpC,IAAI,CAACK,IAAI,CAACC,SAAS,CAACL,GAAG,CAAC,CAAC;QAC3D,CAAC;QACDoC,KAAKA,CAAA,EAAG;UACJJ,eAAe,CAACG,MAAM,CAACC,KAAK,CAAC,CAAC;UAC9B,OAAOC,2BAAoB;QAC/B;MACJ,CAAC;IAEL;EACJ,CAAC,CAAC;EACF,OAAOzC,OAAO;AAClB","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/storage-remote-websocket/types.js.map b/dist/cjs/plugins/storage-remote-websocket/types.js.map index dd77baacfbb..37578fa1cc3 100644 --- a/dist/cjs/plugins/storage-remote-websocket/types.js.map +++ b/dist/cjs/plugins/storage-remote-websocket/types.js.map @@ -1 +1 @@ -{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/storage-remote-websocket/types.ts"],"sourcesContent":["import type {\n WebsocketServerState\n} from '../replication-websocket/index.ts';\nimport type { ServerOptions, ClientOptions } from 'ws';\nimport type { RxDatabase, RxStorage } from '../../types/index.d.ts';\nimport type {\n CustomRequestHandler,\n RxStorageRemoteExposeType,\n RxStorageRemoteSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport { RxStorageRemote } from '../storage-remote/index.ts';\n\nexport type RxStorageRemoteWebsocketServerOptions = ServerOptions & {\n storage?: RxStorage;\n database?: RxDatabase;\n customRequestHandler?: CustomRequestHandler;\n};\n\nexport type RxStorageRemoteWebsocketServerState = {\n serverState: WebsocketServerState;\n exposeState: RxStorageRemoteExposeType;\n};\n\nexport type RxStorageRemoteWebsocketClientOptions = ClientOptions & {\n url: string;\n mode: RxStorageRemoteSettings['mode'];\n};\n\nexport type RxStorageRemoteWebsocketClient = RxStorageRemote;\n"],"mappings":"","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/storage-remote-websocket/types.ts"],"sourcesContent":["import type {\n WebsocketServerState\n} from '../replication-websocket/index.ts';\nimport type { ServerOptions, ClientOptions } from 'ws';\nimport type { RxDatabase, RxStorage } from '../../types/index.d.ts';\nimport type {\n CustomRequestHandler,\n RxStorageRemoteExposeType,\n RxStorageRemoteSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport { RxStorageRemote } from '../storage-remote/index.ts';\n\nexport type RxStorageRemoteWebsocketServerOptions = ServerOptions & {\n storage?: RxStorage;\n database?: RxDatabase;\n customRequestHandler?: CustomRequestHandler;\n /**\n * Used in tests to simulate what happens if the remote\n * was build on a different RxDB version.\n */\n fakeVersion?: string;\n};\n\nexport type RxStorageRemoteWebsocketServerState = {\n serverState: WebsocketServerState;\n exposeState: RxStorageRemoteExposeType;\n};\n\nexport type RxStorageRemoteWebsocketClientOptions = ClientOptions & {\n url: string;\n mode: RxStorageRemoteSettings['mode'];\n};\n\nexport type RxStorageRemoteWebsocketClient = RxStorageRemote;\n"],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/storage-remote/remote.js b/dist/cjs/plugins/storage-remote/remote.js index 8f2b0e7f989..8aaaba8a1bd 100644 --- a/dist/cjs/plugins/storage-remote/remote.js +++ b/dist/cjs/plugins/storage-remote/remote.js @@ -8,6 +8,7 @@ var _rxjs = require("rxjs"); var _index = require("../../plugins/utils/index.js"); var _storageRemoteHelpers = require("./storage-remote-helpers.js"); var _rxStorageHelper = require("../../rx-storage-helper.js"); +var _rxError = require("../../rx-error.js"); /** * Run this on the 'remote' part, * so that RxStorageMessageChannel can connect to it. @@ -51,7 +52,17 @@ function exposeRxStorageRemote(settings) { throw new Error('no base given'); } } + var mustBeRxDBVersion = settings.fakeVersion ? settings.fakeVersion : _index.RXDB_VERSION; settings.messages$.pipe((0, _rxjs.filter)(msg => msg.method === 'create')).subscribe(async msg => { + if (msg.version !== mustBeRxDBVersion) { + settings.send((0, _storageRemoteHelpers.createErrorAnswer)(msg, (0, _rxError.newRxError)('RM1', { + args: { + mainVersion: msg.version, + remoteVersion: mustBeRxDBVersion + } + }))); + return; + } var connectionId = msg.connectionId; /** diff --git a/dist/cjs/plugins/storage-remote/remote.js.map b/dist/cjs/plugins/storage-remote/remote.js.map index 54855d3f1a5..a200faa83a7 100644 --- a/dist/cjs/plugins/storage-remote/remote.js.map +++ b/dist/cjs/plugins/storage-remote/remote.js.map @@ -1 +1 @@ -{"version":3,"file":"remote.js","names":["_rxjs","require","_index","_storageRemoteHelpers","_rxStorageHelper","exposeRxStorageRemote","settings","instanceByFullName","Map","messages$","pipe","filter","msg","method","subscribe","customRequestHandler","send","createErrorAnswer","Error","result","params","createAnswer","err","getRxStorageInstance","storage","createStorageInstance","database","storageInstances","Array","from","collectionName","storageInstance","find","instance","console","dir","JSON","stringify","schema","deepEqual","existingSchema","Promise","resolve","connectionId","isArray","fullName","databaseName","version","join","state","get","storageInstancePromise","connectionIds","Set","set","add","subs","push","changeStream","changes","message","answerTo","return","connectionClosed","closeThisConnection","forEach","sub","unsubscribe","ensureNotFalsy","delete","collection","collections","onClose","subMsg","plainMessage","size","getChangedDocumentsSince"],"sources":["../../../../src/plugins/storage-remote/remote.ts"],"sourcesContent":["import { filter, Subscription } from 'rxjs';\nimport type {\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types/index.d.ts';\nimport {\n deepEqual,\n ensureNotFalsy\n} from '../../plugins/utils/index.ts';\nimport { createAnswer, createErrorAnswer } from './storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteExposeSettingsRxDatabase,\n RxStorageRemoteExposeSettingsRxStorage,\n RxStorageRemoteExposeType\n} from './storage-remote-types.ts';\nimport { getChangedDocumentsSince } from '../../rx-storage-helper.ts';\n\n/**\n * Run this on the 'remote' part,\n * so that RxStorageMessageChannel can connect to it.\n */\nexport function exposeRxStorageRemote(settings: RxStorageRemoteExposeSettings): RxStorageRemoteExposeType {\n type InstanceState = {\n storageInstancePromise: Promise>;\n connectionIds: Set;\n params: RxStorageInstanceCreationParams;\n };\n const instanceByFullName: Map = new Map();\n\n\n settings.messages$.pipe(\n filter(msg => msg.method === 'custom')\n ).subscribe(async (msg) => {\n if (!settings.customRequestHandler) {\n settings.send(createErrorAnswer(\n msg,\n new Error('Remote storage: cannot resolve custom request because settings.customRequestHandler is not set')\n ));\n } else {\n try {\n const result = await settings.customRequestHandler(msg.params);\n settings.send(createAnswer(msg, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(\n msg,\n err\n ));\n }\n }\n });\n\n\n function getRxStorageInstance(params: any): Promise> {\n if ((settings as RxStorageRemoteExposeSettingsRxStorage).storage) {\n return (settings as RxStorageRemoteExposeSettingsRxStorage).storage.createStorageInstance(params);\n } else if ((settings as RxStorageRemoteExposeSettingsRxDatabase).database) {\n const storageInstances = Array.from((settings as RxStorageRemoteExposeSettingsRxDatabase).database.storageInstances);\n const collectionName = params.collectionName;\n const storageInstance = storageInstances.find(instance => instance.collectionName === collectionName);\n if (!storageInstance) {\n console.dir(storageInstances);\n throw new Error('storageInstance does not exist ' + JSON.stringify({\n collectionName\n }));\n }\n const schema = params.schema;\n if (!deepEqual(schema, storageInstance.schema)) {\n throw new Error('Wrong schema ' + JSON.stringify({\n schema,\n existingSchema: storageInstance.schema\n }));\n }\n return Promise.resolve(storageInstance);\n } else {\n throw new Error('no base given');\n }\n }\n\n settings.messages$.pipe(\n filter(msg => msg.method === 'create')\n ).subscribe(async (msg) => {\n const connectionId = msg.connectionId;\n\n /**\n * Do an isArray check here\n * for runtime check types to ensure we have\n * instance creation params and not method input params.\n */\n if (Array.isArray(msg.params)) {\n return;\n }\n const params = msg.params;\n const collectionName = params.collectionName;\n\n /**\n * We de-duplicate the storage instances.\n * This makes sense in many environments like\n * electron where on main process contains the storage\n * for multiple renderer processes. Same goes for SharedWorkers etc.\n */\n const fullName = [\n params.databaseName,\n params.collectionName,\n params.schema.version\n ].join('|');\n let state = instanceByFullName.get(fullName);\n if (!state) {\n try {\n state = {\n /**\n * We work with a promise here to ensure\n * that parallel create-calls will still end up\n * with exactly one instance and not more.\n */\n storageInstancePromise: getRxStorageInstance(params),\n connectionIds: new Set(),\n params\n };\n instanceByFullName.set(fullName, state);\n\n /**\n * Must await the creation here\n * so that in case of an error,\n * it knows about the error message and can send\n * that back to the main process. \n */\n await state.storageInstancePromise;\n } catch (err: any) {\n settings.send(createErrorAnswer(msg, err));\n return;\n }\n } else {\n // if instance already existed, ensure that the schema is equal\n if (!deepEqual(params.schema, state.params.schema)) {\n settings.send(createErrorAnswer(msg, new Error('Remote storage: schema not equal to existing storage')));\n return;\n }\n }\n state.connectionIds.add(msg.connectionId);\n const subs: Subscription[] = [];\n\n const storageInstance = await state.storageInstancePromise;\n /**\n * Automatically subscribe to the changeStream()\n * because we always need them.\n */\n subs.push(\n storageInstance.changeStream().subscribe(changes => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'changestream',\n method: 'changeStream',\n return: changes\n };\n settings.send(message);\n })\n );\n\n let connectionClosed = false;\n function closeThisConnection() {\n if (connectionClosed) {\n return;\n }\n connectionClosed = true;\n subs.forEach(sub => sub.unsubscribe());\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n instanceByFullName.delete(fullName);\n /**\n * TODO how to notify the other ports on remove() ?\n */\n }\n\n // also close the connection when the collection gets closed\n if ((settings as RxStorageRemoteExposeSettingsRxDatabase).database) {\n const database = (settings as RxStorageRemoteExposeSettingsRxDatabase).database;\n const collection = database.collections[collectionName];\n if (collection) {\n collection.onClose.push(() => closeThisConnection());\n } else {\n database.onClose.push(() => closeThisConnection());\n }\n }\n\n subs.push(\n settings.messages$.pipe(\n filter(subMsg => (subMsg as MessageToRemote).connectionId === connectionId)\n ).subscribe(async (plainMessage) => {\n const message: MessageToRemote = plainMessage as any;\n if (\n message.method === 'create' ||\n message.method === 'custom'\n ) {\n return;\n }\n if (!Array.isArray(message.params)) {\n return;\n }\n let result;\n try {\n if (\n message.method === 'close' &&\n (settings as RxStorageRemoteExposeSettingsRxDatabase).database\n ) {\n /**\n * Do not close the storageInstance if it was taken from\n * a running RxDatabase.\n * In that case we only close the instance\n * when the RxDatabase gets closed.\n */\n settings.send(createAnswer(message, null));\n return;\n }\n /**\n * On calls to 'close()',\n * we only close the main instance if there are no other\n * ports connected.\n */\n if (\n message.method === 'close' &&\n ensureNotFalsy(state).connectionIds.size > 1\n ) {\n settings.send(createAnswer(message, null));\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n subs.forEach(sub => sub.unsubscribe());\n return;\n }\n\n if (message.method === 'getChangedDocumentsSince' && !storageInstance.getChangedDocumentsSince) {\n result = await getChangedDocumentsSince(\n storageInstance,\n message.params[0],\n message.params[1]\n );\n } else {\n result = await (storageInstance as any)[message.method](\n message.params[0],\n message.params[1],\n message.params[2],\n message.params[3]\n );\n }\n if (\n message.method === 'close' ||\n message.method === 'remove'\n ) {\n closeThisConnection();\n }\n settings.send(createAnswer(message, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(message, err));\n }\n })\n );\n\n settings.send(createAnswer(msg, 'ok'));\n });\n\n return {\n instanceByFullName\n };\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAKA,IAAAC,MAAA,GAAAD,OAAA;AAIA,IAAAE,qBAAA,GAAAF,OAAA;AASA,IAAAG,gBAAA,GAAAH,OAAA;AAEA;AACA;AACA;AACA;AACO,SAASI,qBAAqBA,CAACC,QAAuC,EAA6B;EAMtG,IAAMC,kBAA8C,GAAG,IAAIC,GAAG,CAAC,CAAC;EAGhEF,QAAQ,CAACG,SAAS,CAACC,IAAI,CACnB,IAAAC,YAAM,EAACC,GAAG,IAAIA,GAAG,CAACC,MAAM,KAAK,QAAQ,CACzC,CAAC,CAACC,SAAS,CAAC,MAAOF,GAAG,IAAK;IACvB,IAAI,CAACN,QAAQ,CAACS,oBAAoB,EAAE;MAChCT,QAAQ,CAACU,IAAI,CAAC,IAAAC,uCAAiB,EAC3BL,GAAG,EACH,IAAIM,KAAK,CAAC,gGA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L;EACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"remote.js","names":["_rxjs","require","_index","_storageRemoteHelpers","_rxStorageHelper","_rxError","exposeRxStorageRemote","settings","instanceByFullName","Map","messages$","pipe","filter","msg","method","subscribe","customRequestHandler","send","createErrorAnswer","Error","result","params","createAnswer","err","getRxStorageInstance","storage","createStorageInstance","database","storageInstances","Array","from","collectionName","storageInstance","find","instance","console","dir","JSON","stringify","schema","deepEqual","existingSchema","Promise","resolve","mustBeRxDBVersion","fakeVersion","RXDB_VERSION","version","newRxError","args","mainVersion","remoteVersion","connectionId","isArray","fullName","databaseName","join","state","get","storageInstancePromise","connectionIds","Set","set","add","subs","push","changeStream","changes","message","answerTo","return","connectionClosed","closeThisConnection","forEach","sub","unsubscribe","ensureNotFalsy","delete","collection","collections","onClose","subMsg","plainMessage","size","getChangedDocumentsSince"],"sources":["../../../../src/plugins/storage-remote/remote.ts"],"sourcesContent":["import { filter, Subscription } from 'rxjs';\nimport type {\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types/index.d.ts';\nimport {\n deepEqual,\n ensureNotFalsy,\n RXDB_VERSION\n} from '../../plugins/utils/index.ts';\nimport { createAnswer, createErrorAnswer } from './storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteExposeSettingsRxDatabase,\n RxStorageRemoteExposeSettingsRxStorage,\n RxStorageRemoteExposeType\n} from './storage-remote-types.ts';\nimport { getChangedDocumentsSince } from '../../rx-storage-helper.ts';\nimport { newRxError } from '../../rx-error.ts';\n\n/**\n * Run this on the 'remote' part,\n * so that RxStorageMessageChannel can connect to it.\n */\nexport function exposeRxStorageRemote(settings: RxStorageRemoteExposeSettings): RxStorageRemoteExposeType {\n type InstanceState = {\n storageInstancePromise: Promise>;\n connectionIds: Set;\n params: RxStorageInstanceCreationParams;\n };\n const instanceByFullName: Map = new Map();\n\n\n settings.messages$.pipe(\n filter(msg => msg.method === 'custom')\n ).subscribe(async (msg) => {\n if (!settings.customRequestHandler) {\n settings.send(createErrorAnswer(\n msg,\n new Error('Remote storage: cannot resolve custom request because settings.customRequestHandler is not set')\n ));\n } else {\n try {\n const result = await settings.customRequestHandler(msg.params);\n settings.send(createAnswer(msg, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(\n msg,\n err\n ));\n }\n }\n });\n\n\n function getRxStorageInstance(params: any): Promise> {\n if ((settings as RxStorageRemoteExposeSettingsRxStorage).storage) {\n return (settings as RxStorageRemoteExposeSettingsRxStorage).storage.createStorageInstance(params);\n } else if ((settings as RxStorageRemoteExposeSettingsRxDatabase).database) {\n const storageInstances = Array.from((settings as RxStorageRemoteExposeSettingsRxDatabase).database.storageInstances);\n const collectionName = params.collectionName;\n const storageInstance = storageInstances.find(instance => instance.collectionName === collectionName);\n if (!storageInstance) {\n console.dir(storageInstances);\n throw new Error('storageInstance does not exist ' + JSON.stringify({\n collectionName\n }));\n }\n const schema = params.schema;\n if (!deepEqual(schema, storageInstance.schema)) {\n throw new Error('Wrong schema ' + JSON.stringify({\n schema,\n existingSchema: storageInstance.schema\n }));\n }\n return Promise.resolve(storageInstance);\n } else {\n throw new Error('no base given');\n }\n }\n\n const mustBeRxDBVersion = settings.fakeVersion ? settings.fakeVersion : RXDB_VERSION;\n settings.messages$.pipe(\n filter(msg => msg.method === 'create')\n ).subscribe(async (msg) => {\n if (msg.version !== mustBeRxDBVersion) {\n settings.send(createErrorAnswer(msg, newRxError('RM1', {\n args: {\n mainVersion: msg.version,\n remoteVersion: mustBeRxDBVersion\n }\n })));\n return;\n }\n\n const connectionId = msg.connectionId;\n\n /**\n * Do an isArray check here\n * for runtime check types to ensure we have\n * instance creation params and not method input params.\n */\n if (Array.isArray(msg.params)) {\n return;\n }\n const params = msg.params;\n const collectionName = params.collectionName;\n\n /**\n * We de-duplicate the storage instances.\n * This makes sense in many environments like\n * electron where on main process contains the storage\n * for multiple renderer processes. Same goes for SharedWorkers etc.\n */\n const fullName = [\n params.databaseName,\n params.collectionName,\n params.schema.version\n ].join('|');\n let state = instanceByFullName.get(fullName);\n if (!state) {\n try {\n state = {\n /**\n * We work with a promise here to ensure\n * that parallel create-calls will still end up\n * with exactly one instance and not more.\n */\n storageInstancePromise: getRxStorageInstance(params),\n connectionIds: new Set(),\n params\n };\n instanceByFullName.set(fullName, state);\n\n /**\n * Must await the creation here\n * so that in case of an error,\n * it knows about the error message and can send\n * that back to the main process. \n */\n await state.storageInstancePromise;\n } catch (err: any) {\n settings.send(createErrorAnswer(msg, err));\n return;\n }\n } else {\n // if instance already existed, ensure that the schema is equal\n if (!deepEqual(params.schema, state.params.schema)) {\n settings.send(createErrorAnswer(msg, new Error('Remote storage: schema not equal to existing storage')));\n return;\n }\n }\n state.connectionIds.add(msg.connectionId);\n const subs: Subscription[] = [];\n\n const storageInstance = await state.storageInstancePromise;\n /**\n * Automatically subscribe to the changeStream()\n * because we always need them.\n */\n subs.push(\n storageInstance.changeStream().subscribe(changes => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'changestream',\n method: 'changeStream',\n return: changes\n };\n settings.send(message);\n })\n );\n\n let connectionClosed = false;\n function closeThisConnection() {\n if (connectionClosed) {\n return;\n }\n connectionClosed = true;\n subs.forEach(sub => sub.unsubscribe());\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n instanceByFullName.delete(fullName);\n /**\n * TODO how to notify the other ports on remove() ?\n */\n }\n\n // also close the connection when the collection gets closed\n if ((settings as RxStorageRemoteExposeSettingsRxDatabase).database) {\n const database = (settings as RxStorageRemoteExposeSettingsRxDatabase).database;\n const collection = database.collections[collectionName];\n if (collection) {\n collection.onClose.push(() => closeThisConnection());\n } else {\n database.onClose.push(() => closeThisConnection());\n }\n }\n\n subs.push(\n settings.messages$.pipe(\n filter(subMsg => (subMsg as MessageToRemote).connectionId === connectionId)\n ).subscribe(async (plainMessage) => {\n const message: MessageToRemote = plainMessage as any;\n if (\n message.method === 'create' ||\n message.method === 'custom'\n ) {\n return;\n }\n if (!Array.isArray(message.params)) {\n return;\n }\n let result;\n try {\n if (\n message.method === 'close' &&\n (settings as RxStorageRemoteExposeSettingsRxDatabase).database\n ) {\n /**\n * Do not close the storageInstance if it was taken from\n * a running RxDatabase.\n * In that case we only close the instance\n * when the RxDatabase gets closed.\n */\n settings.send(createAnswer(message, null));\n return;\n }\n /**\n * On calls to 'close()',\n * we only close the main instance if there are no other\n * ports connected.\n */\n if (\n message.method === 'close' &&\n ensureNotFalsy(state).connectionIds.size > 1\n ) {\n settings.send(createAnswer(message, null));\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n subs.forEach(sub => sub.unsubscribe());\n return;\n }\n\n if (message.method === 'getChangedDocumentsSince' && !storageInstance.getChangedDocumentsSince) {\n result = await getChangedDocumentsSince(\n storageInstance,\n message.params[0],\n message.params[1]\n );\n } else {\n result = await (storageInstance as any)[message.method](\n message.params[0],\n message.params[1],\n message.params[2],\n message.params[3]\n );\n }\n if (\n message.method === 'close' ||\n message.method === 'remove'\n ) {\n closeThisConnection();\n }\n settings.send(createAnswer(message, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(message, err));\n }\n })\n );\n\n settings.send(createAnswer(msg, 'ok'));\n });\n\n return {\n instanceByFullName\n };\n}\n"],"mappings":";;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAKA,IAAAC,MAAA,GAAAD,OAAA;AAKA,IAAAE,qBAAA,GAAAF,OAAA;AASA,IAAAG,gBAAA,GAAAH,OAAA;AACA,IAAAI,QAAA,GAAAJ,OAAA;AAEA;AACA;AACA;AACA;AACO,SAASK,qBAAqBA,CAACC,QAAuC,EAA6B;EAMtG,IAAMC,kBAA8C,GAAG,IAAIC,GAAG,CAAC,CAAC;EAGhEF,QAAQ,CAACG,SAAS,CAACC,IAAI,CACnB,IAAAC,YAAM,EAACC,GAAG,IAAIA,GAAG,CAACC,MAAM,KAAK,QAAQ,CACzC,CAAC,CAACC,SAAS,CAAC,MAAOF,GA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CACpB,CAAC;QACL;QACA,IACI+C,OAAO,CAACtD,MAAM,KAAK,OAAO,IAC1BsD,OAAO,CAACtD,MAAM,KAAK,QAAQ,EAC7B;UACE0D,mBAAmB,CAAC,CAAC;QACzB;QACAjE,QAAQ,CAACU,IAAI,CAAC,IAAAK,kCAAY,EAAC8C,OAAO,EAAEhD,MAAM,CAAC,CAAC;MAChD,CAAC,CAAC,OAAOG,GAAQ,EAAE;QACfhB,QAAQ,CAACU,IAAI,CAAC,IAAAC,uCAAiB,EAACkD,OAAO,EAAE7C,GAAG,CAAC,CAAC;MAClD;IACJ,CAAC,CACL,CAAC;IAEDhB,QAAQ,CAACU,IAAI,CAAC,IAAAK,kCAAY,EAACT,GAAG,EAAE,IAAI,CAAC,CAAC;EAC1C,CAAC,CAAC;EAEF,OAAO;IACHL;EACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/storage-remote/rx-storage-remote.js b/dist/cjs/plugins/storage-remote/rx-storage-remote.js index bb2eda51dab..ea1f4612111 100644 --- a/dist/cjs/plugins/storage-remote/rx-storage-remote.js +++ b/dist/cjs/plugins/storage-remote/rx-storage-remote.js @@ -43,6 +43,7 @@ var RxStorageRemote = exports.RxStorageRemote = /*#__PURE__*/function () { messageChannel.send({ connectionId, method: 'create', + version: _index.RXDB_VERSION, requestId, params }); @@ -65,6 +66,7 @@ var RxStorageRemote = exports.RxStorageRemote = /*#__PURE__*/function () { messageChannel.send({ connectionId, method: 'custom', + version: _index.RXDB_VERSION, requestId, params: data }); @@ -124,6 +126,7 @@ var RxStorageInstanceRemote = exports.RxStorageInstanceRemote = /*#__PURE__*/fun var message = { connectionId: this.internals.connectionId, requestId, + version: _index.RXDB_VERSION, method: methodName, params }; diff --git a/dist/cjs/plugins/storage-remote/rx-storage-remote.js.map b/dist/cjs/plugins/storage-remote/rx-storage-remote.js.map index 44c88d7f538..3da6186c981 100644 --- a/dist/cjs/plugins/storage-remote/rx-storage-remote.js.map +++ b/dist/cjs/plugins/storage-remote/rx-storage-remote.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-remote.js","names":["_rxjs","require","_index","_messageChannelCache","RxStorageRemote","exports","settings","name","rxdbVersion","RXDB_VERSION","seed","randomToken","lastRequestId","mode","messageChannelIfOneMode","getMessageChannel","_proto","prototype","getRequestId","newId","createStorageInstance","params","connectionId","cacheKeys","push","collectionName","databaseName","messageChannel","requestId","waitForOkPromise","firstValueFrom","messages$","pipe","filter","msg","answerTo","send","method","waitForOkResult","error","closeMessageChannel","Error","JSON","stringify","RxStorageInstanceRemote","schema","options","customRequest","data","messageChannelCreator","waitForAnswerPromise","response","close","return","getMessageReturn","parse","storage","internals","changes$","Subject","subs","subscribe","next","_proto2","requestRemote","methodName","responsePromise","message","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","digest","getChangedDocumentsSince","limit","checkpoint","changeStream","asObservable","cleanup","minDeletedTime","closed","forEach","sub","unsubscribe","complete","remove","getRxStorageRemote","withDefaults","Object","assign"],"sources":["../../../../src/plugins/storage-remote/rx-storage-remote.ts"],"sourcesContent":["import {\n firstValueFrom,\n filter,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from '../../types/index.d.ts';\nimport {\n RXDB_VERSION,\n randomToken\n} from '../../plugins/utils/index.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RemoteMessageChannel,\n RxStorageRemoteInternals,\n RxStorageRemoteSettings\n} from './storage-remote-types.ts';\nimport { closeMessageChannel, getMessageChannel } from './message-channel-cache.ts';\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper.ts';\n\n\nexport class RxStorageRemote implements RxStorage {\n public readonly name: string = 'remote';\n public readonly rxdbVersion = RXDB_VERSION;\n\n private seed: string = randomToken(10);\n private lastRequestId: number = 0;\n public messageChannelIfOneMode?: Promise;\n constructor(\n public readonly settings: RxStorageRemoteSettings\n ) {\n if (settings.mode === 'one') {\n this.messageChannelIfOneMode = getMessageChannel(\n settings,\n [],\n true\n );\n }\n }\n\n public getRequestId() {\n const newId = this.lastRequestId++;\n return this.seed + '|' + newId;\n }\n\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n const connectionId = 'c|' + this.getRequestId();\n\n const cacheKeys: string[] = [\n 'mode-' + this.settings.mode\n ];\n switch (this.settings.mode) {\n case 'collection':\n cacheKeys.push('collection-' + params.collectionName);\n // eslint-disable-next-line no-fallthrough\n case 'database':\n cacheKeys.push('database-' + params.databaseName);\n // eslint-disable-next-line no-fallthrough\n case 'storage':\n cacheKeys.push('seed-' + this.seed);\n }\n const messageChannel = await (this.messageChannelIfOneMode ?\n this.messageChannelIfOneMode :\n getMessageChannel(\n this.settings,\n cacheKeys\n )\n );\n\n const requestId = this.getRequestId();\n const waitForOkPromise = firstValueFrom(messageChannel.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n messageChannel.send({\n connectionId,\n method: 'create',\n requestId,\n params\n });\n\n const waitForOkResult = await waitForOkPromise;\n if (waitForOkResult.error) {\n await closeMessageChannel(messageChannel);\n throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error));\n }\n\n return new RxStorageInstanceRemote(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n params,\n connectionId,\n messageChannel\n },\n params.options\n );\n }\n\n async customRequest(data: In): Promise {\n const messageChannel = await this.settings.messageChannelCreator();\n const requestId = this.getRequestId();\n const connectionId = 'custom|request|' + requestId;\n const waitForAnswerPromise = firstValueFrom(messageChannel.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n messageChannel.send({\n connectionId,\n method: 'custom',\n requestId,\n params: data\n });\n const response = await waitForAnswerPromise;\n if (response.error) {\n await messageChannel.close();\n throw new Error('could not run customRequest(): ' + JSON.stringify({\n data,\n error: response.error\n }));\n } else {\n await messageChannel.close();\n return response.return;\n }\n\n }\n}\n\n/**\n * Because postMessage() can be very slow on complex objects,\n * and some RxStorage implementations do need a JSON-string internally\n * anyway, it is allowed to transfer a string instead of an object\n * which must then be JSON.parse()-ed before RxDB can use it.\n * @link https://surma.dev/things/is-postmessage-slow/\n */\nfunction getMessageReturn(\n msg: MessageFromRemote\n) {\n if (msg.method === 'getAttachmentData') {\n return msg.return;\n } else {\n if (typeof msg.return === 'string') {\n return JSON.parse(msg.return);\n } else {\n return msg.return;\n }\n }\n}\n\nexport class RxStorageInstanceRemote implements RxStorageInstance {\n private changes$: Subject>, any>> = new Subject();\n private subs: Subscription[] = [];\n\n private closed?: Promise;\n messages$: Observable;\n\n constructor(\n public readonly storage: RxStorageRemote,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: RxStorageRemoteInternals,\n public readonly options: Readonly\n ) {\n this.messages$ = this.internals.messageChannel.messages$.pipe(\n filter(msg => msg.connectionId === this.internals.connectionId)\n );\n this.subs.push(\n this.messages$.subscribe(msg => {\n if (msg.method === 'changeStream') {\n this.changes$.next(getMessageReturn(msg));\n }\n })\n );\n }\n\n private async requestRemote(\n methodName: keyof RxStorageInstance,\n params: any\n ) {\n const requestId = this.storage.getRequestId();\n const responsePromise = firstValueFrom(\n this.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n )\n );\n const message: MessageToRemote = {\n connectionId: this.internals.connectionId,\n requestId,\n method: methodName,\n params\n };\n this.internals.messageChannel.send(message);\n const response = await responsePromise;\n if (response.error) {\n throw new Error('could not requestRemote: ' + JSON.stringify({\n methodName,\n params,\n error: response.error\n }, null, 4));\n } else {\n return getMessageReturn(response);\n }\n }\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.requestRemote('bulkWrite', [documentWrites, context]);\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise[]> {\n return this.requestRemote('findDocumentsById', [ids, deleted]);\n }\n query(preparedQuery: any): Promise> {\n return this.requestRemote('query', [preparedQuery]);\n }\n count(preparedQuery: any): Promise {\n return this.requestRemote('count', [preparedQuery]);\n }\n getAttachmentData(documentId: string, attachmentId: string, digest: string): Promise {\n return this.requestRemote('getAttachmentData', [documentId, attachmentId, digest]);\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ): Promise<\n {\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n return this.requestRemote('getChangedDocumentsSince', [limit, checkpoint]);\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number): Promise {\n return this.requestRemote('cleanup', [minDeletedTime]);\n }\n async close(): Promise {\n if (this.closed) {\n return this.closed;\n }\n this.closed = (async () => {\n this.subs.forEach(sub => sub.unsubscribe());\n this.changes$.complete();\n await this.requestRemote('close', []);\n await closeMessageChannel(this.internals.messageChannel);\n })();\n return this.closed;\n }\n async remove(): Promise {\n if (this.closed) {\n throw new Error('already closed');\n }\n this.closed = (async () => {\n await this.requestRemote('remove', []);\n await closeMessageChannel(this.internals.messageChannel);\n })();\n return this.closed;\n }\n}\n\nexport function getRxStorageRemote(settings: RxStorageRemoteSettings): RxStorageRemote {\n const withDefaults = Object.assign({\n mode: 'storage'\n }, settings);\n return new RxStorageRemote(withDefaults);\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAoBA,IAAAC,MAAA,GAAAD,OAAA;AAWA,IAAAE,oBAAA,GAAAF,OAAA;AAAoF,IAIvEG,eAAe,GAAAC,OAAA,CAAAD,eAAA;EAOxB,SAAAA,gBACoBE,QAAiC,EACnD;IAAA,KARcC,IAAI,GAAW,QAAQ;IAAA,KACvBC,WAAW,GAAGC,mBAAY;IAAA,KAElCC,IAAI,GAAW,IAAAC,kBAAW,EAAC,EAAE,CAAC;IAAA,KAC9BC,a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;AAGE,SAASkD,kBAAkBA,CAACxF,QAAiC,EAAmB;EACnF,IAAMyF,YAAY,GAAGC,MAAM,CAACC,MAAM,CAAC;IAC/BpF,IAAI,EAAE;EACV,CAAC,EAAEP,QAAQ,CAAC;EACZ,OAAO,IAAIF,eAAe,CAAC2F,YAAY,CAAC;AAC5C","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"rx-storage-remote.js","names":["_rxjs","require","_index","_messageChannelCache","RxStorageRemote","exports","settings","name","rxdbVersion","RXDB_VERSION","seed","randomToken","lastRequestId","mode","messageChannelIfOneMode","getMessageChannel","_proto","prototype","getRequestId","newId","createStorageInstance","params","connectionId","cacheKeys","push","collectionName","databaseName","messageChannel","requestId","waitForOkPromise","firstValueFrom","messages$","pipe","filter","msg","answerTo","send","method","version","waitForOkResult","error","closeMessageChannel","Error","JSON","stringify","RxStorageInstanceRemote","schema","options","customRequest","data","messageChannelCreator","waitForAnswerPromise","response","close","return","getMessageReturn","parse","storage","internals","changes$","Subject","subs","subscribe","next","_proto2","requestRemote","methodName","responsePromise","message","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","digest","getChangedDocumentsSince","limit","checkpoint","changeStream","asObservable","cleanup","minDeletedTime","closed","forEach","sub","unsubscribe","complete","remove","getRxStorageRemote","withDefaults","Object","assign"],"sources":["../../../../src/plugins/storage-remote/rx-storage-remote.ts"],"sourcesContent":["import {\n firstValueFrom,\n filter,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from '../../types/index.d.ts';\nimport {\n RXDB_VERSION,\n randomToken\n} from '../../plugins/utils/index.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RemoteMessageChannel,\n RxStorageRemoteInternals,\n RxStorageRemoteSettings\n} from './storage-remote-types.ts';\nimport { closeMessageChannel, getMessageChannel } from './message-channel-cache.ts';\n\n\nexport class RxStorageRemote implements RxStorage {\n public readonly name: string = 'remote';\n public readonly rxdbVersion = RXDB_VERSION;\n\n private seed: string = randomToken(10);\n private lastRequestId: number = 0;\n public messageChannelIfOneMode?: Promise;\n constructor(\n public readonly settings: RxStorageRemoteSettings\n ) {\n if (settings.mode === 'one') {\n this.messageChannelIfOneMode = getMessageChannel(\n settings,\n [],\n true\n );\n }\n }\n\n public getRequestId() {\n const newId = this.lastRequestId++;\n return this.seed + '|' + newId;\n }\n\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n const connectionId = 'c|' + this.getRequestId();\n\n const cacheKeys: string[] = [\n 'mode-' + this.settings.mode\n ];\n switch (this.settings.mode) {\n case 'collection':\n cacheKeys.push('collection-' + params.collectionName);\n // eslint-disable-next-line no-fallthrough\n case 'database':\n cacheKeys.push('database-' + params.databaseName);\n // eslint-disable-next-line no-fallthrough\n case 'storage':\n cacheKeys.push('seed-' + this.seed);\n }\n const messageChannel = await (this.messageChannelIfOneMode ?\n this.messageChannelIfOneMode :\n getMessageChannel(\n this.settings,\n cacheKeys\n )\n );\n\n const requestId = this.getRequestId();\n const waitForOkPromise = firstValueFrom(messageChannel.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n messageChannel.send({\n connectionId,\n method: 'create',\n version: RXDB_VERSION,\n requestId,\n params\n });\n\n const waitForOkResult = await waitForOkPromise;\n if (waitForOkResult.error) {\n await closeMessageChannel(messageChannel);\n throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error));\n }\n\n return new RxStorageInstanceRemote(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n params,\n connectionId,\n messageChannel\n },\n params.options\n );\n }\n\n async customRequest(data: In): Promise {\n const messageChannel = await this.settings.messageChannelCreator();\n const requestId = this.getRequestId();\n const connectionId = 'custom|request|' + requestId;\n const waitForAnswerPromise = firstValueFrom(messageChannel.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n messageChannel.send({\n connectionId,\n method: 'custom',\n version: RXDB_VERSION,\n requestId,\n params: data\n });\n const response = await waitForAnswerPromise;\n if (response.error) {\n await messageChannel.close();\n throw new Error('could not run customRequest(): ' + JSON.stringify({\n data,\n error: response.error\n }));\n } else {\n await messageChannel.close();\n return response.return;\n }\n\n }\n}\n\n/**\n * Because postMessage() can be very slow on complex objects,\n * and some RxStorage implementations do need a JSON-string internally\n * anyway, it is allowed to transfer a string instead of an object\n * which must then be JSON.parse()-ed before RxDB can use it.\n * @link https://surma.dev/things/is-postmessage-slow/\n */\nfunction getMessageReturn(\n msg: MessageFromRemote\n) {\n if (msg.method === 'getAttachmentData') {\n return msg.return;\n } else {\n if (typeof msg.return === 'string') {\n return JSON.parse(msg.return);\n } else {\n return msg.return;\n }\n }\n}\n\nexport class RxStorageInstanceRemote implements RxStorageInstance {\n private changes$: Subject>, any>> = new Subject();\n private subs: Subscription[] = [];\n\n private closed?: Promise;\n messages$: Observable;\n\n constructor(\n public readonly storage: RxStorageRemote,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: RxStorageRemoteInternals,\n public readonly options: Readonly\n ) {\n this.messages$ = this.internals.messageChannel.messages$.pipe(\n filter(msg => msg.connectionId === this.internals.connectionId)\n );\n this.subs.push(\n this.messages$.subscribe(msg => {\n if (msg.method === 'changeStream') {\n this.changes$.next(getMessageReturn(msg));\n }\n })\n );\n }\n\n private async requestRemote(\n methodName: keyof RxStorageInstance,\n params: any\n ) {\n const requestId = this.storage.getRequestId();\n const responsePromise = firstValueFrom(\n this.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n )\n );\n const message: MessageToRemote = {\n connectionId: this.internals.connectionId,\n requestId,\n version: RXDB_VERSION,\n method: methodName,\n params\n };\n this.internals.messageChannel.send(message);\n const response = await responsePromise;\n if (response.error) {\n throw new Error('could not requestRemote: ' + JSON.stringify({\n methodName,\n params,\n error: response.error\n }, null, 4));\n } else {\n return getMessageReturn(response);\n }\n }\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.requestRemote('bulkWrite', [documentWrites, context]);\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise[]> {\n return this.requestRemote('findDocumentsById', [ids, deleted]);\n }\n query(preparedQuery: any): Promise> {\n return this.requestRemote('query', [preparedQuery]);\n }\n count(preparedQuery: any): Promise {\n return this.requestRemote('count', [preparedQuery]);\n }\n getAttachmentData(documentId: string, attachmentId: string, digest: string): Promise {\n return this.requestRemote('getAttachmentData', [documentId, attachmentId, digest]);\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ): Promise<\n {\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n return this.requestRemote('getChangedDocumentsSince', [limit, checkpoint]);\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number): Promise {\n return this.requestRemote('cleanup', [minDeletedTime]);\n }\n async close(): Promise {\n if (this.closed) {\n return this.closed;\n }\n this.closed = (async () => {\n this.subs.forEach(sub => sub.unsubscribe());\n this.changes$.complete();\n await this.requestRemote('close', []);\n await closeMessageChannel(this.internals.messageChannel);\n })();\n return this.closed;\n }\n async remove(): Promise {\n if (this.closed) {\n throw new Error('already closed');\n }\n this.closed = (async () => {\n await this.requestRemote('remove', []);\n await closeMessageChannel(this.internals.messageChannel);\n })();\n return this.closed;\n }\n}\n\nexport function getRxStorageRemote(settings: RxStorageRemoteSettings): RxStorageRemote {\n const withDefaults = Object.assign({\n mode: 'storage'\n }, settings);\n return new RxStorageRemote(withDefaults);\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,KAAA,GAAAC,OAAA;AAoBA,IAAAC,MAAA,GAAAD,OAAA;AAWA,IAAAE,oBAAA,GAAAF,OAAA;AAAoF,IAGvEG,eAAe,GAAAC,OAAA,CAAAD,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IAAI,CAAC+C,MAAM,GAAG,CAAC,YAAY;MACvB,MAAM,IAAI,CAACxB,aAAa,CAAC,QAAQ,EAAE,EAAE,CAAC;MACtC,MAAM,IAAAxB,wCAAmB,EAAC,IAAI,CAACiB,SAAS,CAAC/B,cAAc,CAAC;IAC5D,CAAC,EAAE,CAAC;IACJ,OAAO,IAAI,CAAC8D,MAAM;EACtB,CAAC;EAAA,OAAA5C,uBAAA;AAAA;AAGE,SAASkD,kBAAkBA,CAACzF,QAAiC,EAAmB;EACnF,IAAM0F,YAAY,GAAGC,MAAM,CAACC,MAAM,CAAC;IAC/BrF,IAAI,EAAE;EACV,CAAC,EAAEP,QAAQ,CAAC;EACZ,OAAO,IAAIF,eAAe,CAAC4F,YAAY,CAAC;AAC5C","ignoreList":[]} \ No newline at end of file diff --git a/dist/cjs/plugins/storage-remote/storage-remote-types.js.map b/dist/cjs/plugins/storage-remote/storage-remote-types.js.map index c14574b1815..7176174521b 100644 --- a/dist/cjs/plugins/storage-remote/storage-remote-types.js.map +++ b/dist/cjs/plugins/storage-remote/storage-remote-types.js.map @@ -1 +1 @@ -{"version":3,"file":"storage-remote-types.js","names":[],"sources":["../../../../src/plugins/storage-remote/storage-remote-types.ts"],"sourcesContent":["import type { Observable } from 'rxjs';\nimport type {\n MaybePromise,\n PlainJsonError,\n RxDatabase,\n RxStorage,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types/index.d.ts';\n\n\n\nexport type MessageFromRemote = {\n connectionId: string;\n answerTo: string; // id of the request\n method: keyof RxStorageInstance | 'create' | 'custom';\n error?: PlainJsonError;\n return?: any | string;\n};\n\nexport type MessageToRemote = {\n connectionId: string;\n /**\n * Unique ID of the request\n */\n requestId: string;\n method: keyof RxStorageInstance | 'create' | 'custom';\n params:\n RxStorageInstanceCreationParams | // used in the create call\n any[] | // used to call RxStorageInstance methods\n any; // used in custom requests\n};\n\n\n/**\n * A message channel represents a single\n * channel that is able to communicate with the remote.\n * For example a single websocket connection or WebWorker instance.\n * The storage must be able to open and close MessageChannels\n * according to the modes settings.\n */\nexport type RemoteMessageChannel = {\n send(msg: MessageToRemote): void;\n messages$: Observable;\n close(): Promise;\n};\n\nexport type RxStorageRemoteSettings = {\n identifier: string;\n /**\n * There are different modes\n * that determine how many message channels are used.\n * These modes can have different performance patterns.\n *\n * [default='storage']\n */\n mode?:\n // create exactly one RemoteMessageChannel and reuse that everywhere.\n | 'one'\n // storage: create one RemoteMessageChannel per call to getRxStorage...()\n | 'storage'\n // database: create one RemoteMessageChannel for each database\n | 'database'\n // collection: create one RemoteMessageChannel for each collection\n | 'collection';\n messageChannelCreator: () => Promise;\n};\n\nexport type RxStorageRemoteInternals = {\n params: RxStorageInstanceCreationParams;\n connectionId: string;\n messageChannel: RemoteMessageChannel;\n};\n\nexport type RxStorageRemoteExposeSettingsBase = {\n send(msg: MessageFromRemote): void;\n messages$: Observable;\n customRequestHandler?: CustomRequestHandler;\n};\n\nexport type RxStorageRemoteExposeSettingsRxDatabase = RxStorageRemoteExposeSettingsBase & {\n /**\n * The database which must be mapped to the remote storage server.\n */\n database: RxDatabase;\n};\n\nexport type RxStorageRemoteExposeSettingsRxStorage = RxStorageRemoteExposeSettingsBase & {\n /**\n * The original storage\n * which actually stores the data.\n */\n storage: RxStorage;\n};\n\nexport type RxStorageRemoteExposeSettings = RxStorageRemoteExposeSettingsRxDatabase | RxStorageRemoteExposeSettingsRxStorage;\n\nexport type RxStorageRemoteExposeType = {\n instanceByFullName: Map;\n};\n\n/**\n * If set, the clients can send RxDB-unrelated custom messages\n * to the remote storage and it will answer them.\n */\nexport type CustomRequestHandler = (data: In) => MaybePromise;\n"],"mappings":"","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"storage-remote-types.js","names":[],"sources":["../../../../src/plugins/storage-remote/storage-remote-types.ts"],"sourcesContent":["import type { Observable } from 'rxjs';\nimport type {\n MaybePromise,\n PlainJsonError,\n RxDatabase,\n RxStorage,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types/index.d.ts';\n\n\n\nexport type MessageFromRemote = {\n connectionId: string;\n answerTo: string; // id of the request\n method: keyof RxStorageInstance | 'create' | 'custom';\n error?: PlainJsonError;\n return?: any | string;\n};\n\nexport type MessageToRemote = {\n connectionId: string;\n /**\n * Unique ID of the request\n */\n requestId: string;\n method: keyof RxStorageInstance | 'create' | 'custom';\n /**\n * We send the RxDB version to the remote\n * to ensure we are communicating with an RxDB instance\n * of the same version. This is to prevent bugs\n * when people forget to rebuild their workers.\n */\n version: string;\n params:\n RxStorageInstanceCreationParams | // used in the create call\n any[] | // used to call RxStorageInstance methods\n any; // used in custom requests\n};\n\n\n/**\n * A message channel represents a single\n * channel that is able to communicate with the remote.\n * For example a single websocket connection or WebWorker instance.\n * The storage must be able to open and close MessageChannels\n * according to the modes settings.\n */\nexport type RemoteMessageChannel = {\n send(msg: MessageToRemote): void;\n messages$: Observable;\n close(): Promise;\n};\n\nexport type RxStorageRemoteSettings = {\n identifier: string;\n /**\n * There are different modes\n * that determine how many message channels are used.\n * These modes can have different performance patterns.\n *\n * [default='storage']\n */\n mode?:\n // create exactly one RemoteMessageChannel and reuse that everywhere.\n | 'one'\n // storage: create one RemoteMessageChannel per call to getRxStorage...()\n | 'storage'\n // database: create one RemoteMessageChannel for each database\n | 'database'\n // collection: create one RemoteMessageChannel for each collection\n | 'collection';\n messageChannelCreator: () => Promise;\n};\n\nexport type RxStorageRemoteInternals = {\n params: RxStorageInstanceCreationParams;\n connectionId: string;\n messageChannel: RemoteMessageChannel;\n};\n\nexport type RxStorageRemoteExposeSettingsBase = {\n send(msg: MessageFromRemote): void;\n messages$: Observable;\n customRequestHandler?: CustomRequestHandler;\n /**\n * Used in tests to simulate what happens if the remote\n * was build on a different RxDB version.\n */\n fakeVersion?: string;\n};\n\nexport type RxStorageRemoteExposeSettingsRxDatabase = RxStorageRemoteExposeSettingsBase & {\n /**\n * The database which must be mapped to the remote storage server.\n */\n database: RxDatabase;\n};\n\nexport type RxStorageRemoteExposeSettingsRxStorage = RxStorageRemoteExposeSettingsBase & {\n /**\n * The original storage\n * which actually stores the data.\n */\n storage: RxStorage;\n};\n\nexport type RxStorageRemoteExposeSettings = RxStorageRemoteExposeSettingsRxDatabase | RxStorageRemoteExposeSettingsRxStorage;\n\nexport type RxStorageRemoteExposeType = {\n instanceByFullName: Map;\n};\n\n/**\n * If set, the clients can send RxDB-unrelated custom messages\n * to the remote storage and it will answer them.\n */\nexport type CustomRequestHandler = (data: In) => MaybePromise;\n"],"mappings":"","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 8e78f1d5c99..85ae05bd8ee 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.8'; +var RXDB_VERSION = exports.RXDB_VERSION = '16.0.0-beta.9'; //# 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 6582d1722e4..ce8bb8da704 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.8';\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.9';\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/esm/plugins/dev-mode/error-messages.js b/dist/esm/plugins/dev-mode/error-messages.js index 07a0b1c94e7..f34cda8a067 100644 --- a/dist/esm/plugins/dev-mode/error-messages.js +++ b/dist/esm/plugins/dev-mode/error-messages.js @@ -228,6 +228,8 @@ export var ERROR_MESSAGES = { DXE1: 'non-required index fields are not possible with the dexie.js RxStorage: https://github.com/pubkey/rxdb/pull/6643#issuecomment-2505310082', // removed in 15.0.0, added boolean index support to dexie storage - DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index', + // plugins/storage-remote + RM1: 'Cannot communicate with a remote that was build on a different RxDB version. Did you forget to rebuild your workers when updating RxDB?', /** * Should never be thrown, use this for * null checks etc. so you do not have to increase the diff --git a/dist/esm/plugins/dev-mode/error-messages.js.map b/dist/esm/plugins/dev-mode/error-messages.js.map index f788477460c..72c54a2d494 100644 --- a/dist/esm/plugins/dev-mode/error-messages.js.map +++ b/dist/esm/plugins/dev-mode/error-messages.js.map @@ -1 +1 @@ -{"version":3,"file":"error-messages.js","names":["NON_PREMIUM_COLLECTION_LIMIT","ERROR_MESSAGES","UT1","UT2","UT3","UT4","UT5","UT6","UT7","PL1","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","QU16","QU17","QU18","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB9","DB11","DB12","DB13","DB14","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL20","COL21","CONFLICT","COL22","COL23","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DOC20","DOC21","DOC22","DOC23","DOC24","DM1","DM2","DM3","DM4","DM5","AT1","EN1","EN2","EN3","EN4","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC4","RC5","RC6","RC7","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_WEBRTC_PEER","RC_COUCHDB_1","RC_COUCHDB_2","RC_OUTDATED","RC_UNAUTHORIZED","RC_FORBIDDEN","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","SC40","SC41","DVM1","VD1","VD2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","DXE1","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\nimport { NON_PREMIUM_COLLECTION_LIMIT } from '../utils/utils-premium.ts';\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n UT7: 'attachments.compression is enabled but no attachment-compression plugin is used',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin.',\n // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importing a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n QU16: '$regex queries must be defined by a string, not an RegExp instance. ' +\n 'This is because RegExp objects cannot be JSON stringified and also they are mutable which would be dangerous',\n QU17: 'Chained queries cannot be used on findByIds() RxQuery instances',\n QU18: 'Malformated query result data. This likely happens because you create a OPFS-storage RxDatabase inside of a worker but did not set the usesRxDatabaseInWorker setting. https://rxdb.info/rx-storage-opfs.html#setting-usesrxdatabaseinworker-when-a-rxdatabase-is-also-used-inside-of-the-worker ',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://rxdb.info/questions-answers.html?console=qa#cant-change-the-schema ',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'createRxDatabase(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional-\\n' +\n 'This often happens in react projects with hot reload that reloads the code without reloading the process.',\n DB9: 'ignoreDuplicate is only allowed in dev-mode and must never be used in production',\n // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n DB12: 'RxDatabase.addCollections(): could not write to internal store',\n DB13: 'createRxDatabase(): Invalid db-name or collection name, name contains the dollar sign',\n DB14: 'no custom reactivity factory added on database creation',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.incrementalUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string. Notice that in RxDB, primary keys must be strings and cannot be numbers.',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n COL20: 'Storage write error',\n COL21: 'The RxCollection is closed or removed already, either from this JavaScript realm or from another, like a browser tab',\n CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision',\n COL22: '.bulkInsert() and .bulkUpsert() cannot be run with multiple documents that have the same primary key',\n COL23: 'In the open-source version of RxDB, the amount of collections that can exist in parallel is limited to '+NON_PREMIUM_COLLECTION_LIMIT+'. If you already purchased the premium access, you can remove this limit: https://rxdb.info/rx-collection.html#faq',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.close() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n DOC20: 'PrimaryKey missing',\n DOC21: 'PrimaryKey must be equal to PrimaryKey.trim(). It cannot start or end with a whitespace',\n DOC22: 'PrimaryKey must not contain a linebreak',\n DOC23: 'PrimaryKey must not contain a double-quote [\"]',\n DOC24: 'Given document data could not be structured cloned. This happens if you pass non-plain-json data into it, like a Date() object or a Function. ' +\n 'In vue.js this happens if you use ref() on the document data which transforms it into a Proxy object.',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n DM4: 'Migration errored',\n DM5: 'Cannot open database state with newer RxDB version. You have to migrate your database state first. See https://rxdb.info/migration-storage.html?console=storage ',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption-crypto-js.js\n EN1: 'password is not valid',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n EN4: 'Password not valid',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'replicateCouchDB() query must be from the same RxCollection',\n // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC7: 'SimplePeer requires to have process.nextTick() polyfilled, see https://rxdb.info/replication-webrtc.html?console=webrtc ',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_WEBRTC_PEER: 'RxReplication WebRTC Peer has error',\n RC_COUCHDB_1: 'replicateCouchDB() url must end with a slash like \\'https://example.com/mydatabase/\\'',\n RC_COUCHDB_2: 'replicateCouchDB() did not get valid result with rows.',\n RC_OUTDATED: 'Outdated client, update required. Replication was canceled',\n RC_UNAUTHORIZED: 'Unauthorized client, update the replicationState.headers to set correct auth data',\n RC_FORBIDDEN: 'Client behaves wrong so the replication was canceled. Mostly happens if the client tries to write data that it is not allowed to',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n // removed in 16.0.0 - SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n SC40: '$ref fields in the schema are not allowed. RxDB cannot resolve related schemas because it would have a negative performance impact.' +\n 'It would have to run http requests on runtime. $ref fields should be resolved during build time.',\n SC41: 'minimum, maximum and maxLength values for indexes must be real numbers, not Infinity or -Infinity',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 instead - DEV1: 'dev-mode added multiple times',\n DVM1: 'When dev-mode is enabled, your storage must use one of the schema validators at the top level. This is because most problems people have with RxDB is because they store data that is not valid to the schema which causes strange bugs and problems.',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/storage-dexie/\n DXE1: 'non-required index fields are not possible with the dexie.js RxStorage: https://github.com/pubkey/rxdb/pull/6643#issuecomment-2505310082',\n // removed in 15.0.0, added boolean index support to dexie storage - DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,SAASA,4BAA4B,QAAQ,2BAA2B;AAGxE,OAAO,IAA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AC,GAAG,EAAE,kEAAkE;EACvEC,GAAG,EAAE,8BAA8B;EAEnC;EACA;EACA;;EAEA;EACAC,EAAE,EAAE,iEAAiE;EAErE;EACAC,IAAI,EAAE,oDAAoD;EAC1D;EACAC,IAAI,EAAE,iEAAiE;EACvE;;EAEA;EACAC,KAAK,EAAE,oFAAoF;EAC3FC,KAAK,EAAE,yEAAyE;EAChFC,KAAK,EAAE,wGAAwG;EAE/G;EACAC,IAAI,EAAE,0IAA0I;EAChJ;;EAEA;AACJ;AACA;AACA;AACA;EACIC,GAAG,EAAE;AACT,CAAC","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"error-messages.js","names":["NON_PREMIUM_COLLECTION_LIMIT","ERROR_MESSAGES","UT1","UT2","UT3","UT4","UT5","UT6","UT7","PL1","PL3","P2","QU1","QU4","QU5","QU6","QU9","QU10","QU11","QU12","QU13","QU14","QU15","QU16","QU17","QU18","MQ1","MQ2","MQ3","MQ4","MQ5","MQ6","MQ7","MQ8","DB1","DB2","DB3","DB4","DB5","DB6","DB8","DB9","DB11","DB12","DB13","DB14","COL1","COL2","COL3","COL4","COL5","COL6","COL7","COL8","COL9","COL10","COL11","COL12","COL13","COL14","COL15","COL16","COL17","COL18","COL20","COL21","CONFLICT","COL22","COL23","DOC1","DOC2","DOC3","DOC4","DOC5","DOC6","DOC7","DOC8","DOC9","DOC10","DOC11","DOC13","DOC14","DOC15","DOC16","DOC17","DOC18","DOC19","DOC20","DOC21","DOC22","DOC23","DOC24","DM1","DM2","DM3","DM4","DM5","AT1","EN1","EN2","EN3","EN4","JD1","JD2","JD3","LD1","LD2","LD3","LD4","LD5","LD6","LD7","LD8","RC1","RC2","RC4","RC5","RC6","RC7","RC_PULL","RC_STREAM","RC_PUSH","RC_PUSH_NO_AR","RC_WEBRTC_PEER","RC_COUCHDB_1","RC_COUCHDB_2","RC_OUTDATED","RC_UNAUTHORIZED","RC_FORBIDDEN","SC1","SC2","SC3","SC4","SC6","SC7","SC8","SC10","SC11","SC13","SC14","SC15","SC16","SC17","SC18","SC19","SC20","SC21","SC22","SC23","SC24","SC25","SC26","SC28","SC29","SC30","SC32","SC33","SC34","SC35","SC36","SC37","SC38","SC39","SC40","SC41","DVM1","VD1","VD2","S1","GQL1","GQL3","CRDT1","CRDT2","CRDT3","DXE1","RM1","SNH"],"sources":["../../../../src/plugins/dev-mode/error-messages.ts"],"sourcesContent":["/**\n * this plugin adds the error-messages\n * without it, only error-codes will be shown\n * This is mainly because error-string are hard to compress and we need a smaller build\n */\n\nimport { NON_PREMIUM_COLLECTION_LIMIT } from '../utils/utils-premium.ts';\n\n\nexport const ERROR_MESSAGES = {\n // util.js / config\n UT1: 'given name is no string or empty',\n UT2: `collection- and database-names must match the regex to be compatible with couchdb databases.\n See https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/\n info: if your database-name specifies a folder, the name must contain the slash-char '/' or '\\\\'`,\n UT3: 'replication-direction must either be push or pull or both. But not none',\n UT4: 'given leveldown is no valid adapter',\n UT5: 'keyCompression is set to true in the schema but no key-compression handler is used in the storage',\n UT6: 'schema contains encrypted fields but no encryption handler is used in the storage',\n UT7: 'attachments.compression is enabled but no attachment-compression plugin is used',\n\n // plugins\n PL1: 'Given plugin is not RxDB plugin.',\n // removed in 14.0.0 - PouchDB RxStorage was removed - PL2: 'You tried importing a RxDB plugin to pouchdb. Use addRxPlugin() instead.',\n PL3: 'A plugin with the same name was already added but it was not the exact same JavaScript object',\n\n // pouch-db.js\n // removed in 12.0.0 - P1: 'PouchDB.getBatch: limit must be > 2',\n P2: 'bulkWrite() cannot be called with an empty array',\n // removed in 12.0.0 - P3: 'bulkAddRevisions cannot be called with an empty array',\n\n // rx-query\n QU1: 'RxQuery._execOverDatabase(): op not known',\n // removed in 9.0.0 - QU2: 'limit() must get a number',\n // removed in 9.0.0 - QU3: 'skip() must get a number',\n QU4: 'RxQuery.regex(): You cannot use .regex() on the primary field',\n QU5: 'RxQuery.sort(): does not work because key is not defined in the schema',\n QU6: 'RxQuery.limit(): cannot be called on .findOne()',\n // removed in 12.0.0 (should by ensured by the typings) - QU7: 'query must be an object',\n // removed in 12.0.0 (should by ensured by the typings) - QU8: 'query cannot be an array',\n QU9: 'throwIfMissing can only be used in findOne queries',\n QU10: 'result empty and throwIfMissing: true',\n QU11: 'RxQuery: no valid query params given',\n QU12: 'Given index is not in schema',\n QU13: 'A top level field of the query is not included in the schema',\n QU14: 'Running a count() query in slow mode is now allowed. Either run a count() query with a selector that fully matches an index ' +\n 'or set allowSlowCount=true when calling the createRxDatabase',\n QU15: 'For count queries it is not allowed to use skip or limit',\n QU16: '$regex queries must be defined by a string, not an RegExp instance. ' +\n 'This is because RegExp objects cannot be JSON stringified and also they are mutable which would be dangerous',\n QU17: 'Chained queries cannot be used on findByIds() RxQuery instances',\n QU18: 'Malformated query result data. This likely happens because you create a OPFS-storage RxDatabase inside of a worker but did not set the usesRxDatabaseInWorker setting. https://rxdb.info/rx-storage-opfs.html#setting-usesrxdatabaseinworker-when-a-rxdatabase-is-also-used-inside-of-the-worker ',\n\n // mquery.js\n MQ1: 'path must be a string or object',\n MQ2: 'Invalid argument',\n MQ3: 'Invalid sort() argument. Must be a string, object, or array',\n MQ4: 'Invalid argument. Expected instanceof mquery or plain object',\n MQ5: 'method must be used after where() when called with these arguments',\n MQ6: 'Can\\'t mix sort syntaxes. Use either array or object | .sort([[\\'field\\', 1], [\\'test\\', -1]]) | .sort({ field: 1, test: -1 })',\n MQ7: 'Invalid sort value',\n MQ8: 'Can\\'t mix sort syntaxes. Use either array or object',\n\n // rx-database\n DB1: 'RxDocument.prepare(): another instance on this adapter has a different password',\n DB2: 'RxDatabase.addCollections(): collection-names cannot start with underscore _',\n DB3: 'RxDatabase.addCollections(): collection already exists. use myDatabase[collectionName] to get it',\n DB4: 'RxDatabase.addCollections(): schema is missing',\n DB5: 'RxDatabase.addCollections(): collection-name not allowed',\n DB6: 'RxDatabase.addCollections(): another instance created this collection with a different schema. Read this https://rxdb.info/questions-answers.html?console=qa#cant-change-the-schema ',\n // removed in 13.0.0 (now part of the encryption plugin) DB7: 'RxDatabase.addCollections(): schema encrypted but no password given',\n DB8: 'createRxDatabase(): A RxDatabase with the same name and adapter already exists.\\n' +\n 'Make sure to use this combination only once or set ignoreDuplicate to true if you do this intentional-\\n' +\n 'This often happens in react projects with hot reload that reloads the code without reloading the process.',\n DB9: 'ignoreDuplicate is only allowed in dev-mode and must never be used in production',\n // removed in 14.0.0 - PouchDB RxStorage is removed - DB9: 'createRxDatabase(): Adapter not added. Use addPouchPlugin(require(\\'pouchdb-adapter-[adaptername]\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed DB10: 'createRxDatabase(): To use leveldown-adapters, you have to add the leveldb-plugin. Use addPouchPlugin(require(\\'pouchdb-adapter-leveldb\\'));',\n DB11: 'createRxDatabase(): Invalid db-name, folder-paths must not have an ending slash',\n DB12: 'RxDatabase.addCollections(): could not write to internal store',\n DB13: 'createRxDatabase(): Invalid db-name or collection name, name contains the dollar sign',\n DB14: 'no custom reactivity factory added on database creation',\n\n // rx-collection\n COL1: 'RxDocument.insert() You cannot insert an existing document',\n COL2: 'RxCollection.insert() fieldName ._id can only be used as primaryKey',\n COL3: 'RxCollection.upsert() does not work without primary',\n COL4: 'RxCollection.incrementalUpsert() does not work without primary',\n COL5: 'RxCollection.find() if you want to search by _id, use .findOne(_id)',\n COL6: 'RxCollection.findOne() needs a queryObject or string. Notice that in RxDB, primary keys must be strings and cannot be numbers.',\n COL7: 'hook must be a function',\n COL8: 'hooks-when not known',\n COL9: 'RxCollection.addHook() hook-name not known',\n COL10: 'RxCollection .postCreate-hooks cannot be async',\n COL11: 'migrationStrategies must be an object',\n COL12: 'A migrationStrategy is missing or too much',\n COL13: 'migrationStrategy must be a function',\n COL14: 'given static method-name is not a string',\n COL15: 'static method-names cannot start with underscore _',\n COL16: 'given static method is not a function',\n COL17: 'RxCollection.ORM: statics-name not allowed',\n COL18: 'collection-method not allowed because fieldname is in the schema',\n // removed in 14.0.0, use CONFLICT instead - COL19: 'Document update conflict. When changing a document you must work on the previous revision',\n COL20: 'Storage write error',\n COL21: 'The RxCollection is closed or removed already, either from this JavaScript realm or from another, like a browser tab',\n CONFLICT: 'Document update conflict. When changing a document you must work on the previous revision',\n COL22: '.bulkInsert() and .bulkUpsert() cannot be run with multiple documents that have the same primary key',\n COL23: 'In the open-source version of RxDB, the amount of collections that can exist in parallel is limited to ' + NON_PREMIUM_COLLECTION_LIMIT + '. If you already purchased the premium access, you can remove this limit: https://rxdb.info/rx-collection.html#faq',\n\n // rx-document.js\n DOC1: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n DOC2: 'cannot observe primary path',\n DOC3: 'final fields cannot be observed',\n DOC4: 'RxDocument.get$ cannot observe a non-existed field',\n DOC5: 'RxDocument.populate() cannot populate a non-existed field',\n DOC6: 'RxDocument.populate() cannot populate because path has no ref',\n DOC7: 'RxDocument.populate() ref-collection not in database',\n DOC8: 'RxDocument.set(): primary-key cannot be modified',\n DOC9: 'final fields cannot be modified',\n DOC10: 'RxDocument.set(): cannot set childpath when rootPath not selected',\n DOC11: 'RxDocument.save(): can\\'t save deleted document',\n // removed in 10.0.0 DOC12: 'RxDocument.save(): error',\n DOC13: 'RxDocument.remove(): Document is already deleted',\n DOC14: 'RxDocument.close() does not exist',\n DOC15: 'query cannot be an array',\n DOC16: 'Since version 8.0.0 RxDocument.set() can only be called on temporary RxDocuments',\n DOC17: 'Since version 8.0.0 RxDocument.save() can only be called on non-temporary documents',\n DOC18: 'Document property for composed primary key is missing',\n DOC19: 'Value of primary key(s) cannot be changed',\n DOC20: 'PrimaryKey missing',\n DOC21: 'PrimaryKey must be equal to PrimaryKey.trim(). It cannot start or end with a whitespace',\n DOC22: 'PrimaryKey must not contain a linebreak',\n DOC23: 'PrimaryKey must not contain a double-quote [\"]',\n DOC24: 'Given document data could not be structured cloned. This happens if you pass non-plain-json data into it, like a Date() object or a Function. ' +\n 'In vue.js this happens if you use ref() on the document data which transforms it into a Proxy object.',\n\n // data-migrator.js\n DM1: 'migrate() Migration has already run',\n DM2: 'migration of document failed final document does not match final schema',\n DM3: 'migration already running',\n DM4: 'Migration errored',\n DM5: 'Cannot open database state with newer RxDB version. You have to migrate your database state first. See https://rxdb.info/migration-storage.html?console=storage ',\n\n // plugins/attachments.js\n AT1: 'to use attachments, please define this in your schema',\n\n // plugins/encryption-crypto-js.js\n EN1: 'password is not valid',\n EN2: 'validatePassword: min-length of password not complied',\n EN3: 'Schema contains encrypted properties but no password is given',\n EN4: 'Password not valid',\n\n // plugins/json-dump.js\n JD1: 'You must create the collections before you can import their data',\n JD2: 'RxCollection.importJSON(): the imported json relies on a different schema',\n JD3: 'RxCollection.importJSON(): json.passwordHash does not match the own',\n\n // plugins/leader-election.js\n\n // plugins/local-documents.js\n LD1: 'RxDocument.allAttachments$ can\\'t use attachments on local documents',\n LD2: 'RxDocument.get(): objPath must be a string',\n LD3: 'RxDocument.get$ cannot get observable of in-array fields because order cannot be guessed',\n LD4: 'cannot observe primary path',\n LD5: 'RxDocument.set() id cannot be modified',\n LD6: 'LocalDocument: Function is not usable on local documents',\n LD7: 'Local document already exists',\n LD8: 'localDocuments not activated. Set localDocuments=true on creation, when you want to store local documents on the RxDatabase or RxCollection.',\n\n // plugins/replication.js\n RC1: 'Replication: already added',\n RC2: 'replicateCouchDB() query must be from the same RxCollection',\n // removed in 14.0.0 - PouchDB RxStorage is removed RC3: 'RxCollection.syncCouchDB() Do not use a collection\\'s pouchdb as remote, use the collection instead',\n RC4: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication when live: true',\n RC5: 'RxCouchDBReplicationState.awaitInitialReplication() cannot await initial replication if multiInstance because the replication might run on another instance',\n RC6: 'syncFirestore() serverTimestampField MUST NOT be part of the collections schema and MUST NOT be nested.',\n RC7: 'SimplePeer requires to have process.nextTick() polyfilled, see https://rxdb.info/replication-webrtc.html?console=webrtc ',\n RC_PULL: 'RxReplication pull handler threw an error - see .errors for more details',\n RC_STREAM: 'RxReplication pull stream$ threw an error - see .errors for more details',\n RC_PUSH: 'RxReplication push handler threw an error - see .errors for more details',\n RC_PUSH_NO_AR: 'RxReplication push handler did not return an array with the conflicts',\n RC_WEBRTC_PEER: 'RxReplication WebRTC Peer has error',\n RC_COUCHDB_1: 'replicateCouchDB() url must end with a slash like \\'https://example.com/mydatabase/\\'',\n RC_COUCHDB_2: 'replicateCouchDB() did not get valid result with rows.',\n RC_OUTDATED: 'Outdated client, update required. Replication was canceled',\n RC_UNAUTHORIZED: 'Unauthorized client, update the replicationState.headers to set correct auth data',\n RC_FORBIDDEN: 'Client behaves wrong so the replication was canceled. Mostly happens if the client tries to write data that it is not allowed to',\n\n // plugins/dev-mode/check-schema.js\n SC1: 'fieldnames do not match the regex',\n SC2: 'SchemaCheck: name \\'item\\' reserved for array-fields',\n SC3: 'SchemaCheck: fieldname has a ref-array but items-type is not string',\n SC4: 'SchemaCheck: fieldname has a ref but is not type string, [string,null] or array',\n SC6: 'SchemaCheck: primary can only be defined at top-level',\n SC7: 'SchemaCheck: default-values can only be defined at top-level',\n SC8: 'SchemaCheck: first level-fields cannot start with underscore _',\n SC10: 'SchemaCheck: schema defines ._rev, this will be done automatically',\n SC11: 'SchemaCheck: schema needs a number >=0 as version',\n // removed in 10.0.0 - SC12: 'SchemaCheck: primary can only be defined once',\n SC13: 'SchemaCheck: primary is always index, do not declare it as index',\n SC14: 'SchemaCheck: primary is always unique, do not declare it as index',\n SC15: 'SchemaCheck: primary cannot be encrypted',\n SC16: 'SchemaCheck: primary must have type: string',\n SC17: 'SchemaCheck: top-level fieldname is not allowed',\n SC18: 'SchemaCheck: indexes must be an array',\n SC19: 'SchemaCheck: indexes must contain strings or arrays of strings',\n SC20: 'SchemaCheck: indexes.array must contain strings',\n SC21: 'SchemaCheck: given index is not defined in schema',\n SC22: 'SchemaCheck: given indexKey is not type:string',\n SC23: 'SchemaCheck: fieldname is not allowed',\n SC24: 'SchemaCheck: required fields must be set via array. See https://spacetelescope.github.io/understanding-json-schema/reference/object.html#required',\n SC25: 'SchemaCheck: compoundIndexes needs to be specified in the indexes field',\n SC26: 'SchemaCheck: indexes needs to be specified at collection schema level',\n // removed in 16.0.0 - SC27: 'SchemaCheck: encrypted fields need to be specified at collection schema level',\n SC28: 'SchemaCheck: encrypted fields is not defined in the schema',\n SC29: 'SchemaCheck: missing object key \\'properties\\'',\n SC30: 'SchemaCheck: primaryKey is required',\n SC32: 'SchemaCheck: primary field must have the type string/number/integer',\n SC33: 'SchemaCheck: used primary key is not a property in the schema',\n SC34: 'Fields of type string that are used in an index, must have set the maxLength attribute in the schema',\n SC35: 'Fields of type number/integer that are used in an index, must have set the multipleOf attribute in the schema',\n SC36: 'A field of this type cannot be used as index',\n SC37: 'Fields of type number that are used in an index, must have set the minimum and maximum attribute in the schema',\n SC38: 'Fields of type boolean that are used in an index, must be required in the schema',\n SC39: 'The primary key must have the maxLength attribute set',\n SC40: '$ref fields in the schema are not allowed. RxDB cannot resolve related schemas because it would have a negative performance impact.' +\n 'It would have to run http requests on runtime. $ref fields should be resolved during build time.',\n SC41: 'minimum, maximum and maxLength values for indexes must be real numbers, not Infinity or -Infinity',\n\n // plugins/dev-mode\n // removed in 13.9.0, use PL3 instead - DEV1: 'dev-mode added multiple times',\n DVM1: 'When dev-mode is enabled, your storage must use one of the schema validators at the top level. This is because most problems people have with RxDB is because they store data that is not valid to the schema which causes strange bugs and problems.',\n\n // plugins/validate.js\n VD1: 'Sub-schema not found, does the schemaPath exists in your schema?',\n VD2: 'object does not match schema',\n\n // plugins/in-memory.js\n // removed in 14.0.0 - PouchDB RxStorage is removed IM1: 'InMemory: Memory-Adapter must be added. Use addPouchPlugin(require(\\'pouchdb-adapter-memory\\'));',\n // removed in 14.0.0 - PouchDB RxStorage is removed IM2: 'inMemoryCollection.sync(): Do not replicate with the in-memory instance. Replicate with the parent instead',\n\n // plugins/server.js\n S1: 'You cannot create collections after calling RxDatabase.server()',\n\n // plugins/replication-graphql.js\n GQL1: 'GraphQL replication: cannot find sub schema by key',\n // removed in 13.0.0, use RC_PULL instead - GQL2: 'GraphQL replication: unknown errors occurred in replication pull - see innerErrors for more details',\n GQL3: 'GraphQL replication: pull returns more documents then batchSize',\n // removed in 13.0.0, use RC_PUSH instead - GQL4: 'GraphQL replication: unknown errors occurred in replication push - see innerErrors for more details',\n\n // plugins/crdt/\n CRDT1: 'CRDT operations cannot be used because the crdt options are not set in the schema.',\n CRDT2: 'RxDocument.incrementalModify() cannot be used when CRDTs are activated.',\n CRDT3: 'To use CRDTs you MUST NOT set a conflictHandler because the default CRDT conflict handler must be used',\n\n // plugins/storage-dexie/\n DXE1: 'non-required index fields are not possible with the dexie.js RxStorage: https://github.com/pubkey/rxdb/pull/6643#issuecomment-2505310082',\n // removed in 15.0.0, added boolean index support to dexie storage - DXE1: 'The dexie.js RxStorage does not support boolean indexes, see https://rxdb.info/rx-storage-dexie.html#boolean-index',\n\n // plugins/storage-remote\n RM1: 'Cannot communicate with a remote that was build on a different RxDB version. Did you forget to rebuild your workers when updating RxDB?',\n\n /**\n * Should never be thrown, use this for\n * null checks etc. so you do not have to increase the\n * build size with error message strings.\n */\n SNH: 'This should never happen'\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;;AAEA,SAASA,4BAA4B,QAAQ,2BAA2B;AAGxE,OAAO,IAAMC,cAAc,GAAG;EAC1B;EACAC,GAAG,EAAE,kCAAkC;EACvCC,GAAG,kTAE8F;EACjGC,GAAG,EAAE,yEAAyE;EAC9EC,GAAG,EAAE,qCAAqC;EAC1CC,GAAG,EAAE,mGAAmG;EACxGC,GAAG,EAAE,mFAAmF;EACxFC,GAAG,EAAE,iFAAiF;EAEtF;EACAC,GAAG,EAAE,kCAAkC;EACvC;EACAC,GAAG,EAAE,+FAA+F;EAEpG;EACA;EACAC,EAAE,EAAE,kDAAkD;EACtD;;EAEA;EACAC,GAAG,EAAE,2CAA2C;EAChD;EACA;EACAC,GAAG,EAAE,+DAA+D;EACp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","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/replication/index.js b/dist/esm/plugins/replication/index.js index fe054007fd3..307388f69bc 100644 --- a/dist/esm/plugins/replication/index.js +++ b/dist/esm/plugins/replication/index.js @@ -10,7 +10,7 @@ import { RxDBLeaderElectionPlugin } from "../leader-election/index.js"; import { arrayFilterNotEmpty, ensureNotFalsy, errorToPlainJson, flatClone, getFromMapOrCreate, PROMISE_RESOLVE_FALSE, PROMISE_RESOLVE_TRUE, toArray, toPromise } from "../../plugins/utils/index.js"; import { awaitRxStorageReplicationFirstInSync, awaitRxStorageReplicationInSync, cancelRxStorageReplication, getRxReplicationMetaInstanceSchema, replicateRxStorageInstance } from "../../replication-protocol/index.js"; import { newRxError } from "../../rx-error.js"; -import { awaitRetry, DEFAULT_MODIFIER, swapDefaultDeletedTodeletedField, handlePulledDocuments } from "./replication-helper.js"; +import { awaitRetry, DEFAULT_MODIFIER, swapDefaultDeletedTodeletedField, handlePulledDocuments, preventHibernateBrowserTab } from "./replication-helper.js"; import { addConnectedStorageToCollection, removeConnectedStorageFromCollection } from "../../rx-database-internal-store.js"; import { addRxPlugin } from "../../plugin.js"; import { hasEncryption } from "../../rx-storage-helper.js"; @@ -84,6 +84,7 @@ export var RxReplicationState = /*#__PURE__*/function () { if (this.isStopped()) { return; } + preventHibernateBrowserTab(this); // fill in defaults for pull & push var pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER; diff --git a/dist/esm/plugins/replication/index.js.map b/dist/esm/plugins/replication/index.js.map index 71405603281..912f76d5203 100644 --- a/dist/esm/plugins/replication/index.js.map +++ b/dist/esm/plugins/replication/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["BehaviorSubject","combineLatest","filter","mergeMap","Subject","RxDBLeaderElectionPlugin","arrayFilterNotEmpty","ensureNotFalsy","errorToPlainJson","flatClone","getFromMapOrCreate","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_TRUE","toArray","toPromise","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","cancelRxStorageReplication","getRxReplicationMetaInstanceSchema","replicateRxStorageInstance","newRxError","awaitRetry","DEFAULT_MODIFIER","swapDefaultDeletedTodeletedField","handlePulledDocuments","addConnectedStorageToCollection","removeConnectedStorageFromCollection","addRxPlugin","hasEncryption","overwritable","runAsyncPluginHooks","REPLICATION_STATE_BY_COLLECTION","WeakMap","RxReplicationState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","sent","error","canceled","active","received$","asObservable","sent$","error$","canceled$","active$","onCancel","callOnStart","undefined","remoteEvents$","metaInfoPromise","metaInstanceCollectionName","database","hashFunction","name","join","metaInstanceSchema","schema","jsonSchema","collectionName","replicationStates","onClose","cancel","Object","keys","forEach","key","defineProperty","get","startPromise","Promise","res","_proto","prototype","start","isStopped","pullModifier","modifier","pushModifier","metaInfo","metaInstance","all","storage","createStorageInstance","databaseName","databaseInstanceToken","token","multiInstance","options","password","devMode","isDevMode","internalReplicationState","pushBatchSize","batchSize","pullBatchSize","initialCheckpoint","upstream","downstream","forkInstance","storageInstance","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","_v","ev","useEv","documents","map","d","masterChangesSince","checkpoint","done","result","handler","err","emitError","errors","er","direction","next","useResult","masterWrite","rows","useRowsOrNull","row","newDocumentState","assumedMasterState","useRows","length","Array","isArray","pushRows","args","rxdb","conflicts","events","subscribe","processed","down","document","up","writeToMasterRow","isActive","stream$","getValue","awaitInitialReplication","awaitInSync","t","requestIdlePromise","reSync","emitEvent","promises","fn","checkpointQueue","then","close","sub","unsubscribe","complete","remove","replicateRxCollection","waitForLeadership","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxJsonSchema,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport {\n arrayFilterNotEmpty,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n toArray,\n toPromise\n} from '../../plugins/utils/index.ts';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n getRxReplicationMetaInstanceSchema,\n replicateRxStorageInstance\n} from '../../replication-protocol/index.ts';\nimport { newRxError } from '../../rx-error.ts';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n handlePulledDocuments\n} from './replication-helper.ts';\nimport {\n addConnectedStorageToCollection, removeConnectedStorageFromCollection\n} from '../../rx-database-internal-store.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { hasEncryption } from '../../rx-storage-helper.ts';\nimport { overwritable } from '../../overwritable.ts';\nimport {\n runAsyncPluginHooks\n} from '../../hooks.ts';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n sent: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false) // true when something is running, false when not\n };\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly sent$: Observable> = this.subjects.sent.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n readonly metaInfoPromise: Promise<{ collectionName: string, schema: RxJsonSchema>> }>;\n\n public startPromise: Promise;\n\n public onCancel: (() => void)[] = [];\n\n constructor(\n /**\n * The identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n this.metaInfoPromise = (async () => {\n const metaInstanceCollectionName = 'rx-replication-meta-' + await collection.database.hashFunction([\n this.collection.name,\n this.replicationIdentifier\n ].join('-'));\n const metaInstanceSchema = getRxReplicationMetaInstanceSchema(\n this.collection.schema.jsonSchema,\n hasEncryption(this.collection.schema.jsonSchema)\n );\n return {\n collectionName: metaInstanceCollectionName,\n schema: metaInstanceSchema\n };\n })();\n const replicationStates = getFromMapOrCreate(\n REPLICATION_STATE_BY_COLLECTION,\n collection,\n () => []\n );\n replicationStates.push(this);\n\n // stop the replication when the collection gets closed\n this.collection.onClose.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance, any, {}, any>;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n\n const metaInfo = await this.metaInfoPromise;\n\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance>({\n databaseName: database.name,\n collectionName: metaInfo.collectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance,\n options: {},\n schema: metaInfo.schema,\n password: database.password,\n devMode: overwritable.isDevMode()\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInfo.collectionName,\n metaInfo.schema\n )\n ]);\n this.metaInstance = metaInstance;\n\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n initialCheckpoint: {\n upstream: this.push ? this.push.initialCheckpoint : undefined,\n downstream: this.pull ? this.pull.initialCheckpoint : undefined\n },\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rxdbreplication' + this.replicationIdentifier,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n filter(_v => !!this.pull),\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n useEv.documents = handlePulledDocuments(this.collection, this.deletedField, useEv.documents);\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType | undefined,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n useResult.documents = handlePulledDocuments(this.collection, this.deletedField, useResult.documents);\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n\n await runAsyncPluginHooks('preReplicationMasterWrite', {\n rows,\n collection: this.collection\n });\n\n const useRowsOrNull = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.newDocumentState === null) {\n return null;\n }\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n return row;\n })\n );\n const useRows: RxReplicationWriteToMasterRow[] = useRowsOrNull.filter(arrayFilterNotEmpty);\n\n let result: WithDeleted[] = null as any;\n\n // In case all the rows have been filtered and nothing has to be sent\n if (useRows.length === 0) {\n done = true;\n result = [];\n }\n\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n if (this.isStopped()) {\n return [];\n }\n\n await runAsyncPluginHooks('preReplicationMasterWriteDocumentsHandle', {\n result,\n collection: this.collection\n });\n\n const conflicts = handlePulledDocuments(this.collection, this.deletedField, ensureNotFalsy(result));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.sent.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * To reduce the amount of re-renders and make testing\n * and to make the whole behavior more predictable,\n * we await these things multiple times.\n * For example the state might be in sync already and at the\n * exact same time a pull.stream$ event comes in and we want to catch\n * that in the same call to awaitInSync() instead of resolving\n * while actually the state is not in sync.\n */\n let t = 2;\n while (t > 0) {\n t--;\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n }\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n async cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = this.onCancel.map(fn => toPromise(fn()));\n\n if (this.internalReplicationState) {\n await cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.sent.complete();\n\n return Promise.all(promises);\n }\n\n async remove() {\n await ensureNotFalsy(this.metaInstance).remove();\n const metaInfo = await this.metaInfoPromise;\n await this.cancel();\n await removeConnectedStorageFromCollection(\n this.collection,\n metaInfo.collectionName,\n metaInfo.schema\n );\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n /**\n * It is a common error to forget to add these config\n * objects. So we check here because it makes no sense\n * to start a replication with neither push nor pull.\n */\n if (!pull && !push) {\n throw newRxError('UT3', {\n collection: collection.name,\n args: {\n replicationIdentifier\n }\n });\n }\n\n const replicationState = new RxReplicationState(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\n replicationState.start();\n }\n });\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;;AAEA,SACIA,eAAe,EACfC,aAAa,EACbC,MAAM,EACNC,QAAQ,EAERC,OAAO,QAEJ,MAAM;AAkBb,SAASC,wBAAwB,QAAQ,6BAA6B;AACtE,SACIC,mBAAmB,EACnBC,cAAc,EACdC,gBAAgB,EAChBC,SAAS,EACTC,kBAAkB,EAClBC,qBAAqB,EACrBC,oBAAoB,EACpBC,OAAO,EACPC,SAAS,QACN,8BAA8B;AACrC,SACIC,oCAAoC,EACpCC,+BAA+B,EAC/BC,0BAA0B,EAC1BC,kCAAkC,EAClCC,0BAA0B,QACvB,qCAAqC;AAC5C,SAASC,UAAU,QAAQ,mBAAmB;AAC9C,SACIC,UAAU,EACVC,gBAAgB,EAChBC,gCAAgC,EAChCC,qBAAqB,QAClB,yBAAyB;AAChC,SACIC,+BAA+B,EAAEC,oCAAoC,Q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AgB,CAAC3I,UAAU,CAAC0B,QAAQ,CAACgH,iBAAiB,CAAC,CAAC,GAAGjK,oBAAoB;EACzI,OAAOqK,WAAW,CAACX,IAAI,CAAC,MAAM;IAC1B,IAAIQ,gBAAgB,CAAC1F,SAAS,CAAC,CAAC,EAAE;MAC9B;IACJ;IACA,IAAI0F,gBAAgB,CAACrI,SAAS,EAAE;MAC5BqI,gBAAgB,CAAC3F,KAAK,CAAC,CAAC;IAC5B;EACJ,CAAC,CAAC;AACN","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["BehaviorSubject","combineLatest","filter","mergeMap","Subject","RxDBLeaderElectionPlugin","arrayFilterNotEmpty","ensureNotFalsy","errorToPlainJson","flatClone","getFromMapOrCreate","PROMISE_RESOLVE_FALSE","PROMISE_RESOLVE_TRUE","toArray","toPromise","awaitRxStorageReplicationFirstInSync","awaitRxStorageReplicationInSync","cancelRxStorageReplication","getRxReplicationMetaInstanceSchema","replicateRxStorageInstance","newRxError","awaitRetry","DEFAULT_MODIFIER","swapDefaultDeletedTodeletedField","handlePulledDocuments","preventHibernateBrowserTab","addConnectedStorageToCollection","removeConnectedStorageFromCollection","addRxPlugin","hasEncryption","overwritable","runAsyncPluginHooks","REPLICATION_STATE_BY_COLLECTION","WeakMap","RxReplicationState","replicationIdentifier","collection","deletedField","pull","push","live","retryTime","autoStart","subs","subjects","received","sent","error","canceled","active","received$","asObservable","sent$","error$","canceled$","active$","onCancel","callOnStart","undefined","remoteEvents$","metaInfoPromise","metaInstanceCollectionName","database","hashFunction","name","join","metaInstanceSchema","schema","jsonSchema","collectionName","replicationStates","onClose","cancel","Object","keys","forEach","key","defineProperty","get","startPromise","Promise","res","_proto","prototype","start","isStopped","pullModifier","modifier","pushModifier","metaInfo","metaInstance","all","storage","createStorageInstance","databaseName","databaseInstanceToken","token","multiInstance","options","password","devMode","isDevMode","internalReplicationState","pushBatchSize","batchSize","pullBatchSize","initialCheckpoint","upstream","downstream","forkInstance","storageInstance","identifier","conflictHandler","replicationHandler","masterChangeStream$","pipe","_v","ev","useEv","documents","map","d","masterChangesSince","checkpoint","done","result","handler","err","emitError","errors","er","direction","next","useResult","masterWrite","rows","useRowsOrNull","row","newDocumentState","assumedMasterState","useRows","length","Array","isArray","pushRows","args","rxdb","conflicts","events","subscribe","processed","down","document","up","writeToMasterRow","isActive","stream$","getValue","awaitInitialReplication","awaitInSync","t","requestIdlePromise","reSync","emitEvent","promises","fn","checkpointQueue","then","close","sub","unsubscribe","complete","remove","replicateRxCollection","waitForLeadership","replicationState","startReplicationOnLeaderShip","mustWaitForLeadership","waitTillRun"],"sources":["../../../../src/plugins/replication/index.ts"],"sourcesContent":["/**\n * This plugin contains the primitives to create\n * a RxDB client-server replication.\n * It is used in the other replication plugins\n * but also can be used as standalone with a custom replication handler.\n */\n\nimport {\n BehaviorSubject,\n combineLatest,\n filter,\n mergeMap,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n ReplicationOptions,\n ReplicationPullHandlerResult,\n ReplicationPullOptions,\n ReplicationPushOptions,\n RxCollection,\n RxDocumentData,\n RxError,\n RxJsonSchema,\n RxReplicationPullStreamItem,\n RxReplicationWriteToMasterRow,\n RxStorageInstance,\n RxStorageInstanceReplicationState,\n RxStorageReplicationMeta,\n RxTypeError,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { RxDBLeaderElectionPlugin } from '../leader-election/index.ts';\nimport {\n arrayFilterNotEmpty,\n ensureNotFalsy,\n errorToPlainJson,\n flatClone,\n getFromMapOrCreate,\n PROMISE_RESOLVE_FALSE,\n PROMISE_RESOLVE_TRUE,\n toArray,\n toPromise\n} from '../../plugins/utils/index.ts';\nimport {\n awaitRxStorageReplicationFirstInSync,\n awaitRxStorageReplicationInSync,\n cancelRxStorageReplication,\n getRxReplicationMetaInstanceSchema,\n replicateRxStorageInstance\n} from '../../replication-protocol/index.ts';\nimport { newRxError } from '../../rx-error.ts';\nimport {\n awaitRetry,\n DEFAULT_MODIFIER,\n swapDefaultDeletedTodeletedField,\n handlePulledDocuments,\n preventHibernateBrowserTab\n} from './replication-helper.ts';\nimport {\n addConnectedStorageToCollection, removeConnectedStorageFromCollection\n} from '../../rx-database-internal-store.ts';\nimport { addRxPlugin } from '../../plugin.ts';\nimport { hasEncryption } from '../../rx-storage-helper.ts';\nimport { overwritable } from '../../overwritable.ts';\nimport {\n runAsyncPluginHooks\n} from '../../hooks.ts';\n\n\nexport const REPLICATION_STATE_BY_COLLECTION: WeakMap[]> = new WeakMap();\n\nexport class RxReplicationState {\n public readonly subs: Subscription[] = [];\n public readonly subjects = {\n received: new Subject>(), // all documents that are received from the endpoint\n sent: new Subject>(), // all documents that are send to the endpoint\n error: new Subject(), // all errors that are received from the endpoint, emits new Error() objects\n canceled: new BehaviorSubject(false), // true when the replication was canceled\n active: new BehaviorSubject(false) // true when something is running, false when not\n };\n\n readonly received$: Observable> = this.subjects.received.asObservable();\n readonly sent$: Observable> = this.subjects.sent.asObservable();\n readonly error$: Observable = this.subjects.error.asObservable();\n readonly canceled$: Observable = this.subjects.canceled.asObservable();\n readonly active$: Observable = this.subjects.active.asObservable();\n\n readonly metaInfoPromise: Promise<{ collectionName: string, schema: RxJsonSchema>> }>;\n\n public startPromise: Promise;\n\n public onCancel: (() => void)[] = [];\n\n constructor(\n /**\n * The identifier, used to flag revisions\n * and to identify which documents state came from the remote.\n */\n public readonly replicationIdentifier: string,\n public readonly collection: RxCollection,\n public readonly deletedField: string,\n public readonly pull?: ReplicationPullOptions,\n public readonly push?: ReplicationPushOptions,\n public readonly live?: boolean,\n public retryTime?: number,\n public autoStart?: boolean,\n ) {\n this.metaInfoPromise = (async () => {\n const metaInstanceCollectionName = 'rx-replication-meta-' + await collection.database.hashFunction([\n this.collection.name,\n this.replicationIdentifier\n ].join('-'));\n const metaInstanceSchema = getRxReplicationMetaInstanceSchema(\n this.collection.schema.jsonSchema,\n hasEncryption(this.collection.schema.jsonSchema)\n );\n return {\n collectionName: metaInstanceCollectionName,\n schema: metaInstanceSchema\n };\n })();\n const replicationStates = getFromMapOrCreate(\n REPLICATION_STATE_BY_COLLECTION,\n collection,\n () => []\n );\n replicationStates.push(this);\n\n // stop the replication when the collection gets closed\n this.collection.onClose.push(() => this.cancel());\n\n // create getters for the observables\n Object.keys(this.subjects).forEach(key => {\n Object.defineProperty(this, key + '$', {\n get: function () {\n return this.subjects[key].asObservable();\n }\n });\n });\n const startPromise = new Promise(res => {\n this.callOnStart = res;\n });\n this.startPromise = startPromise;\n }\n\n private callOnStart: () => void = undefined as any;\n\n public internalReplicationState?: RxStorageInstanceReplicationState;\n public metaInstance?: RxStorageInstance, any, {}, any>;\n public remoteEvents$: Subject> = new Subject();\n\n public async start(): Promise {\n if (this.isStopped()) {\n return;\n }\n\n preventHibernateBrowserTab(this);\n\n\n // fill in defaults for pull & push\n const pullModifier = this.pull && this.pull.modifier ? this.pull.modifier : DEFAULT_MODIFIER;\n const pushModifier = this.push && this.push.modifier ? this.push.modifier : DEFAULT_MODIFIER;\n\n const database = this.collection.database;\n\n const metaInfo = await this.metaInfoPromise;\n\n const [metaInstance] = await Promise.all([\n this.collection.database.storage.createStorageInstance>({\n databaseName: database.name,\n collectionName: metaInfo.collectionName,\n databaseInstanceToken: database.token,\n multiInstance: database.multiInstance,\n options: {},\n schema: metaInfo.schema,\n password: database.password,\n devMode: overwritable.isDevMode()\n }),\n addConnectedStorageToCollection(\n this.collection,\n metaInfo.collectionName,\n metaInfo.schema\n )\n ]);\n this.metaInstance = metaInstance;\n\n\n this.internalReplicationState = replicateRxStorageInstance({\n pushBatchSize: this.push && this.push.batchSize ? this.push.batchSize : 100,\n pullBatchSize: this.pull && this.pull.batchSize ? this.pull.batchSize : 100,\n initialCheckpoint: {\n upstream: this.push ? this.push.initialCheckpoint : undefined,\n downstream: this.pull ? this.pull.initialCheckpoint : undefined\n },\n forkInstance: this.collection.storageInstance,\n metaInstance: this.metaInstance,\n hashFunction: database.hashFunction,\n identifier: 'rxdbreplication' + this.replicationIdentifier,\n conflictHandler: this.collection.conflictHandler,\n replicationHandler: {\n masterChangeStream$: this.remoteEvents$.asObservable().pipe(\n filter(_v => !!this.pull),\n mergeMap(async (ev) => {\n if (ev === 'RESYNC') {\n return ev;\n }\n const useEv = flatClone(ev);\n useEv.documents = handlePulledDocuments(this.collection, this.deletedField, useEv.documents);\n useEv.documents = await Promise.all(\n useEv.documents.map(d => pullModifier(d))\n );\n return useEv;\n })\n ),\n masterChangesSince: async (\n checkpoint: CheckpointType | undefined,\n batchSize: number\n ) => {\n if (!this.pull) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n /**\n * Retries must be done here in the replication primitives plugin,\n * because the replication protocol itself has no\n * error handling.\n */\n let done = false;\n let result: ReplicationPullHandlerResult = {} as any;\n while (!done && !this.isStopped()) {\n try {\n result = await this.pull.handler(\n checkpoint,\n batchSize\n );\n done = true;\n } catch (err: any | Error | Error[]) {\n const emitError = newRxError('RC_PULL', {\n checkpoint,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'pull'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n\n if (this.isStopped()) {\n return {\n checkpoint: null,\n documents: []\n };\n }\n\n const useResult = flatClone(result);\n useResult.documents = handlePulledDocuments(this.collection, this.deletedField, useResult.documents);\n useResult.documents = await Promise.all(\n useResult.documents.map(d => pullModifier(d))\n );\n return useResult;\n },\n masterWrite: async (\n rows: RxReplicationWriteToMasterRow[]\n ) => {\n if (!this.push) {\n return [];\n }\n let done = false;\n\n await runAsyncPluginHooks('preReplicationMasterWrite', {\n rows,\n collection: this.collection\n });\n\n const useRowsOrNull = await Promise.all(\n rows.map(async (row) => {\n row.newDocumentState = await pushModifier(row.newDocumentState);\n if (row.newDocumentState === null) {\n return null;\n }\n if (row.assumedMasterState) {\n row.assumedMasterState = await pushModifier(row.assumedMasterState);\n }\n if (this.deletedField !== '_deleted') {\n row.newDocumentState = swapDefaultDeletedTodeletedField(this.deletedField, row.newDocumentState) as any;\n if (row.assumedMasterState) {\n row.assumedMasterState = swapDefaultDeletedTodeletedField(this.deletedField, row.assumedMasterState) as any;\n }\n }\n return row;\n })\n );\n const useRows: RxReplicationWriteToMasterRow[] = useRowsOrNull.filter(arrayFilterNotEmpty);\n\n let result: WithDeleted[] = null as any;\n\n // In case all the rows have been filtered and nothing has to be sent\n if (useRows.length === 0) {\n done = true;\n result = [];\n }\n\n while (!done && !this.isStopped()) {\n try {\n result = await this.push.handler(useRows);\n /**\n * It is a common problem that people have wrongly behaving backend\n * that do not return an array with the conflicts on push requests.\n * So we run this check here to make it easier to debug.\n * @link https://github.com/pubkey/rxdb/issues/4103\n */\n if (!Array.isArray(result)) {\n throw newRxError(\n 'RC_PUSH_NO_AR',\n {\n pushRows: rows,\n direction: 'push',\n args: { result }\n }\n );\n }\n done = true;\n } catch (err: any | Error | Error[] | RxError) {\n const emitError = (err as RxError).rxdb ? err : newRxError('RC_PUSH', {\n pushRows: rows,\n errors: toArray(err).map(er => errorToPlainJson(er)),\n direction: 'push'\n });\n this.subjects.error.next(emitError);\n await awaitRetry(this.collection, ensureNotFalsy(this.retryTime));\n }\n }\n if (this.isStopped()) {\n return [];\n }\n\n await runAsyncPluginHooks('preReplicationMasterWriteDocumentsHandle', {\n result,\n collection: this.collection\n });\n\n const conflicts = handlePulledDocuments(this.collection, this.deletedField, ensureNotFalsy(result));\n return conflicts;\n }\n }\n });\n this.subs.push(\n this.internalReplicationState.events.error.subscribe(err => {\n this.subjects.error.next(err);\n }),\n this.internalReplicationState.events.processed.down\n .subscribe(row => this.subjects.received.next(row.document as any)),\n this.internalReplicationState.events.processed.up\n .subscribe(writeToMasterRow => {\n this.subjects.sent.next(writeToMasterRow.newDocumentState);\n }),\n combineLatest([\n this.internalReplicationState.events.active.down,\n this.internalReplicationState.events.active.up\n ]).subscribe(([down, up]) => {\n const isActive = down || up;\n this.subjects.active.next(isActive);\n })\n );\n\n if (\n this.pull &&\n this.pull.stream$ &&\n this.live\n ) {\n this.subs.push(\n this.pull.stream$.subscribe({\n next: ev => {\n this.remoteEvents$.next(ev);\n },\n error: err => {\n this.subjects.error.next(err);\n }\n })\n );\n }\n\n /**\n * Non-live replications run once\n * and then automatically get canceled.\n */\n if (!this.live) {\n await awaitRxStorageReplicationFirstInSync(this.internalReplicationState);\n await awaitRxStorageReplicationInSync(this.internalReplicationState);\n await this.cancel();\n }\n this.callOnStart();\n }\n\n isStopped(): boolean {\n if (this.subjects.canceled.getValue()) {\n return true;\n }\n return false;\n }\n\n async awaitInitialReplication(): Promise {\n await this.startPromise;\n return awaitRxStorageReplicationFirstInSync(\n ensureNotFalsy(this.internalReplicationState)\n );\n }\n\n /**\n * Returns a promise that resolves when:\n * - All local data is replicated with the remote\n * - No replication cycle is running or in retry-state\n *\n * WARNING: USing this function directly in a multi-tab browser application\n * is dangerous because only the leading instance will ever be replicated,\n * so this promise will not resolve in the other tabs.\n * For multi-tab support you should set and observe a flag in a local document.\n */\n async awaitInSync(): Promise {\n await this.startPromise;\n await awaitRxStorageReplicationFirstInSync(ensureNotFalsy(this.internalReplicationState));\n\n /**\n * To reduce the amount of re-renders and make testing\n * and to make the whole behavior more predictable,\n * we await these things multiple times.\n * For example the state might be in sync already and at the\n * exact same time a pull.stream$ event comes in and we want to catch\n * that in the same call to awaitInSync() instead of resolving\n * while actually the state is not in sync.\n */\n let t = 2;\n while (t > 0) {\n t--;\n\n /**\n * Often awaitInSync() is called directly after a document write,\n * like in the unit tests.\n * So we first have to await the idleness to ensure that all RxChangeEvents\n * are processed already.\n */\n await this.collection.database.requestIdlePromise();\n await awaitRxStorageReplicationInSync(ensureNotFalsy(this.internalReplicationState));\n }\n\n return true;\n }\n\n reSync() {\n this.remoteEvents$.next('RESYNC');\n }\n emitEvent(ev: RxReplicationPullStreamItem) {\n this.remoteEvents$.next(ev);\n }\n\n async cancel(): Promise {\n if (this.isStopped()) {\n return PROMISE_RESOLVE_FALSE;\n }\n\n const promises: Promise[] = this.onCancel.map(fn => toPromise(fn()));\n\n if (this.internalReplicationState) {\n await cancelRxStorageReplication(this.internalReplicationState);\n }\n if (this.metaInstance) {\n promises.push(\n ensureNotFalsy(this.internalReplicationState).checkpointQueue\n .then(() => ensureNotFalsy(this.metaInstance).close())\n );\n }\n\n this.subs.forEach(sub => sub.unsubscribe());\n this.subjects.canceled.next(true);\n\n this.subjects.active.complete();\n this.subjects.canceled.complete();\n this.subjects.error.complete();\n this.subjects.received.complete();\n this.subjects.sent.complete();\n\n return Promise.all(promises);\n }\n\n async remove() {\n await ensureNotFalsy(this.metaInstance).remove();\n const metaInfo = await this.metaInfoPromise;\n await this.cancel();\n await removeConnectedStorageFromCollection(\n this.collection,\n metaInfo.collectionName,\n metaInfo.schema\n );\n }\n}\n\n\nexport function replicateRxCollection(\n {\n replicationIdentifier,\n collection,\n deletedField = '_deleted',\n pull,\n push,\n live = true,\n retryTime = 1000 * 5,\n waitForLeadership = true,\n autoStart = true,\n }: ReplicationOptions\n): RxReplicationState {\n addRxPlugin(RxDBLeaderElectionPlugin);\n\n /**\n * It is a common error to forget to add these config\n * objects. So we check here because it makes no sense\n * to start a replication with neither push nor pull.\n */\n if (!pull && !push) {\n throw newRxError('UT3', {\n collection: collection.name,\n args: {\n replicationIdentifier\n }\n });\n }\n\n const replicationState = new RxReplicationState(\n replicationIdentifier,\n collection,\n deletedField,\n pull,\n push,\n live,\n retryTime,\n autoStart\n );\n\n\n startReplicationOnLeaderShip(waitForLeadership, replicationState);\n return replicationState as any;\n}\n\n\nexport function startReplicationOnLeaderShip(\n waitForLeadership: boolean,\n replicationState: RxReplicationState\n) {\n /**\n * Always await this Promise to ensure that the current instance\n * is leader when waitForLeadership=true\n */\n const mustWaitForLeadership = waitForLeadership && replicationState.collection.database.multiInstance;\n const waitTillRun: Promise = mustWaitForLeadership ? replicationState.collection.database.waitForLeadership() : PROMISE_RESOLVE_TRUE;\n return waitTillRun.then(() => {\n if (replicationState.isStopped()) {\n return;\n }\n if (replicationState.autoStart) {\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iC,IAAI,IAAI,CAACC,IAAI,EAAE;IAChB,MAAMnB,UAAU,CAAC,KAAK,EAAE;MACpBgB,UAAU,EAAEA,UAAU,CAAC4B,IAAI;MAC3BiF,IAAI,EAAE;QACF9G;MACJ;IACJ,CAAC,CAAC;EACN;EAEA,IAAM4I,gBAAgB,GAAG,IAAI7I,kBAAkB,CAC3CC,qBAAqB,EACrBC,UAAU,EACVC,YAAY,EACZC,IAAI,EACJC,IAAI,EACJC,IAAI,EACJC,SAAS,EACTC,SACJ,CAAC;EAGDsI,4BAA4B,CAACF,iBAAiB,EAAEC,gBAAgB,CAAC;EACjE,OAAOA,gBAAgB;AAC3B;AAGA,OAAO,SAASC,4BAA4BA,CACxCF,iBAA0B,EAC1BC,gBAA8C,EAChD;EACE;AACJ;AACA;AACA;EACI,IAAME,qBAAqB,GAAGH,iBAAiB,IAAIC,gBAAgB,CAAC3I,UAAU,CAAC0B,QAAQ,CAACmC,aAAa;EACrG,IAAMiF,WAAyB,GAAGD,qBAAqB,GAAGF,gBAAgB,CAAC3I,UAAU,CAAC0B,QAAQ,CAACgH,iBAAiB,CAAC,CAAC,GAAGlK,oBAAoB;EACzI,OAAOsK,WAAW,CAACX,IAAI,CAAC,MAAM;IAC1B,IAAIQ,gBAAgB,CAAC1F,SAAS,CAAC,CAAC,EAAE;MAC9B;IACJ;IACA,IAAI0F,gBAAgB,CAACrI,SAAS,EAAE;MAC5BqI,gBAAgB,CAAC3F,KAAK,CAAC,CAAC;IAC5B;EACJ,CAAC,CAAC;AACN","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/replication/replication-helper.js b/dist/esm/plugins/replication/replication-helper.js index 6130c1c8b91..e0d55ccbee6 100644 --- a/dist/esm/plugins/replication/replication-helper.js +++ b/dist/esm/plugins/replication/replication-helper.js @@ -1,6 +1,5 @@ import { flatClone } from "../../plugins/utils/index.js"; import { getComposedPrimaryKeyOfDocumentData } from "../../rx-schema-helper.js"; - // does nothing export var DEFAULT_MODIFIER = d => Promise.resolve(d); export function swapDefaultDeletedTodeletedField(deletedField, doc) { @@ -65,4 +64,23 @@ export function awaitRetry(collection, retryTime) { window.removeEventListener('online', listener); }); } + +/** + * When a replication is running and the leading tab get hibernated + * by the browser, the replication will be stuck. + * To prevent this, we fire a mouseeven each X seconds while the replication is not canceled. + * + * If you find a better way to prevent hibernation, please make a pull request. + */ +export function preventHibernateBrowserTab(replicationState) { + function simulateActivity() { + if (typeof document === 'undefined' || typeof document.dispatchEvent !== 'function') { + return; + } + var event = new Event('mousemove'); + document.dispatchEvent(event); + } + var intervalId = setInterval(simulateActivity, 20 * 1000); // Simulate activity every 20 seconds + replicationState.onCancel.push(() => clearInterval(intervalId)); +} //# sourceMappingURL=replication-helper.js.map \ No newline at end of file diff --git a/dist/esm/plugins/replication/replication-helper.js.map b/dist/esm/plugins/replication/replication-helper.js.map index e93415c6f0d..c4ed0ef7002 100644 --- a/dist/esm/plugins/replication/replication-helper.js.map +++ b/dist/esm/plugins/replication/replication-helper.js.map @@ -1 +1 @@ -{"version":3,"file":"replication-helper.js","names":["flatClone","getComposedPrimaryKeyOfDocumentData","DEFAULT_MODIFIER","d","Promise","resolve","swapDefaultDeletedTodeletedField","deletedField","doc","isDeleted","_deleted","handlePulledDocuments","collection","docs","map","useDoc","primaryPath","schema","jsonSchema","awaitRetry","retryTime","window","addEventListener","navigator","onLine","promiseWait","listener","onlineAgain","res","removeEventListener","race","then"],"sources":["../../../../src/plugins/replication/replication-helper.ts"],"sourcesContent":["import type {\n RxCollection,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { flatClone } from '../../plugins/utils/index.ts';\nimport { getComposedPrimaryKeyOfDocumentData } from '../../rx-schema-helper.ts';\n\n// does nothing\nexport const DEFAULT_MODIFIER = (d: any) => Promise.resolve(d);\n\n\nexport function swapDefaultDeletedTodeletedField(\n deletedField: string,\n doc: WithDeleted\n): RxDocType {\n if (deletedField === '_deleted') {\n return doc;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!doc._deleted;\n (doc as any)[deletedField] = isDeleted;\n delete (doc as any)._deleted;\n return doc;\n }\n}\n\n/**\n * Must be run over all plain document data\n * that was pulled from the remote.\n * Used to fill up fields or modify the deleted field etc.\n */\nexport function handlePulledDocuments(\n collection: RxCollection,\n deletedField: string,\n docs: RxDocType[]\n): WithDeleted[] {\n return docs.map(doc => {\n const useDoc: WithDeleted = flatClone(doc) as any;\n\n /**\n * Swap out the deleted field\n */\n if (deletedField !== '_deleted') {\n const isDeleted = !!(useDoc as any)[deletedField];\n (useDoc as any)._deleted = isDeleted;\n delete (useDoc as any)[deletedField];\n } else {\n // ensure we have a boolean.\n useDoc._deleted = !!useDoc._deleted;\n }\n\n /**\n * Fill up composed primary\n */\n const primaryPath = collection.schema.primaryPath;\n (useDoc as any)[primaryPath] = getComposedPrimaryKeyOfDocumentData(\n collection.schema.jsonSchema,\n useDoc\n );\n return useDoc as any;\n });\n}\n\n\n/**\n * Like normal promiseWait()\n * but will skip the wait time if the online-state changes.\n */\nexport function awaitRetry(\n collection: RxCollection,\n retryTime: number\n) {\n if (\n typeof window === 'undefined' ||\n typeof window !== 'object' ||\n typeof window.addEventListener === 'undefined' ||\n navigator.onLine\n ) {\n return collection.promiseWait(retryTime);\n }\n\n let listener: any;\n const onlineAgain = new Promise(res => {\n listener = () => {\n window.removeEventListener('online', listener);\n res();\n };\n window.addEventListener('online', listener);\n });\n\n return Promise.race([\n onlineAgain,\n collection.promiseWait(retryTime)\n ]).then(() => {\n window.removeEventListener('online', listener);\n });\n}\n"],"mappings":"AAIA,SAASA,SAAS,QAAQ,8BAA8B;AACxD,SAASC,mCAAmC,QAAQ,2BAA2B;;AAE/E;AACA,OAAO,IAAMC,gBAAgB,GAAIC,CAAM,IAAKC,OAAO,CAACC,OAAO,CAACF,CAAC,CAAC;AAG9D,OAAO,SAASG,gCAAgCA,CAC5CC,YAAoB,EACpBC,GAA2B,EAClB;EACT,IAAID,YAAY,KAAK,UAAU,EAAE;IAC7B,OAAOC,GA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AEA,IAAIM,QAAa;EACjB,IAAMC,WAAW,GAAG,IAAIvB,OAAO,CAAOwB,GAAG,IAAI;IACzCF,QAAQ,GAAGA,CAAA,KAAM;MACbL,MAAM,CAACQ,mBAAmB,CAAC,QAAQ,EAAEH,QAAQ,CAAC;MAC9CE,GAAG,CAAC,CAAC;IACT,CAAC;IACDP,MAAM,CAACC,gBAAgB,CAAC,QAAQ,EAAEI,QAAQ,CAAC;EAC/C,CAAC,CAAC;EAEF,OAAOtB,OAAO,CAAC0B,IAAI,CAAC,CAChBH,WAAW,EACXf,UAAU,CAACa,WAAW,CAACL,SAAS,CAAC,CACpC,CAAC,CAACW,IAAI,CAAC,MAAM;IACVV,MAAM,CAACQ,mBAAmB,CAAC,QAAQ,EAAEH,QAAQ,CAAC;EAClD,CAAC,CAAC;AACN","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"replication-helper.js","names":["flatClone","getComposedPrimaryKeyOfDocumentData","DEFAULT_MODIFIER","d","Promise","resolve","swapDefaultDeletedTodeletedField","deletedField","doc","isDeleted","_deleted","handlePulledDocuments","collection","docs","map","useDoc","primaryPath","schema","jsonSchema","awaitRetry","retryTime","window","addEventListener","navigator","onLine","promiseWait","listener","onlineAgain","res","removeEventListener","race","then","preventHibernateBrowserTab","replicationState","simulateActivity","document","dispatchEvent","event","Event","intervalId","setInterval","onCancel","push","clearInterval"],"sources":["../../../../src/plugins/replication/replication-helper.ts"],"sourcesContent":["import type {\n RxCollection,\n WithDeleted\n} from '../../types/index.d.ts';\nimport { flatClone } from '../../plugins/utils/index.ts';\nimport { getComposedPrimaryKeyOfDocumentData } from '../../rx-schema-helper.ts';\nimport type { RxReplicationState } from './index.ts';\n\n// does nothing\nexport const DEFAULT_MODIFIER = (d: any) => Promise.resolve(d);\n\n\nexport function swapDefaultDeletedTodeletedField(\n deletedField: string,\n doc: WithDeleted\n): RxDocType {\n if (deletedField === '_deleted') {\n return doc;\n } else {\n doc = flatClone(doc);\n const isDeleted = !!doc._deleted;\n (doc as any)[deletedField] = isDeleted;\n delete (doc as any)._deleted;\n return doc;\n }\n}\n\n/**\n * Must be run over all plain document data\n * that was pulled from the remote.\n * Used to fill up fields or modify the deleted field etc.\n */\nexport function handlePulledDocuments(\n collection: RxCollection,\n deletedField: string,\n docs: RxDocType[]\n): WithDeleted[] {\n return docs.map(doc => {\n const useDoc: WithDeleted = flatClone(doc) as any;\n\n /**\n * Swap out the deleted field\n */\n if (deletedField !== '_deleted') {\n const isDeleted = !!(useDoc as any)[deletedField];\n (useDoc as any)._deleted = isDeleted;\n delete (useDoc as any)[deletedField];\n } else {\n // ensure we have a boolean.\n useDoc._deleted = !!useDoc._deleted;\n }\n\n /**\n * Fill up composed primary\n */\n const primaryPath = collection.schema.primaryPath;\n (useDoc as any)[primaryPath] = getComposedPrimaryKeyOfDocumentData(\n collection.schema.jsonSchema,\n useDoc\n );\n return useDoc as any;\n });\n}\n\n\n/**\n * Like normal promiseWait()\n * but will skip the wait time if the online-state changes.\n */\nexport function awaitRetry(\n collection: RxCollection,\n retryTime: number\n) {\n if (\n typeof window === 'undefined' ||\n typeof window !== 'object' ||\n typeof window.addEventListener === 'undefined' ||\n navigator.onLine\n ) {\n return collection.promiseWait(retryTime);\n }\n\n let listener: any;\n const onlineAgain = new Promise(res => {\n listener = () => {\n window.removeEventListener('online', listener);\n res();\n };\n window.addEventListener('online', listener);\n });\n\n return Promise.race([\n onlineAgain,\n collection.promiseWait(retryTime)\n ]).then(() => {\n window.removeEventListener('online', listener);\n });\n}\n\n\n/**\n * When a replication is running and the leading tab get hibernated\n * by the browser, the replication will be stuck.\n * To prevent this, we fire a mouseeven each X seconds while the replication is not canceled.\n * \n * If you find a better way to prevent hibernation, please make a pull request.\n */\nexport function preventHibernateBrowserTab(replicationState: RxReplicationState) {\n function simulateActivity() {\n if (\n typeof document === 'undefined' ||\n typeof document.dispatchEvent !== 'function'\n ) {\n return;\n }\n const event = new Event('mousemove');\n document.dispatchEvent(event);\n }\n\n const intervalId = setInterval(simulateActivity, 20 * 1000); // Simulate activity every 20 seconds\n replicationState.onCancel.push(() => clearInterval(intervalId));\n}\n"],"mappings":"AAIA,SAASA,SAAS,QAAQ,8BAA8B;AACxD,SAASC,mCAAmC,QAAQ,2BAA2B;AAG/E;AACA,OAAO,IAAMC,gBAAgB,GAAIC,CAAM,IAAKC,OAAO,CAACC,OAAO,CAACF,CAAC,CAAC;AAG9D,OAAO,SAASG,gCAAgCA,CAC5CC,YAAoB,EACpBC,GAA2B,EAClB;EACT,IAAID,YAAY,KAAK,UAAU,EAAE;IAC7B,OAAOC,GAAG;EACd,CAAC,MAAM;IACHA,GAAG,GAAGR,SAAS,CAACQ,GAAG,CAAC;IACpB,IAAMC,SAAS,GAAG,CAAC,CAACD,GAAG,CAACE,QAAQ;IAC/BF,GAAG,CAASD,YAAY,CAAC,GAAGE,SAAS;IACtC,OAAQD,GAAG,CAASE,QAAQ;IAC5B,OAAOF,GAAG;EACd;AACJ;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASG,qBAAqBA,CACjCC,UAAmC,EACnCL,YAAoB,EACpBM,IAAiB,EACO;EACxB,OAAOA,IAAI,CAACC,GAAG,CAACN,GAAG,IAAI;IACnB,IAAMO,MAA8B,GAAGf,SAAS,CAACQ,GAAG,CAAQ;;IAE5D;AACR;AACA;IACQ,IAAID,YAAY,KAAK,UAAU,EAAE;MAC7B,IAAME,SAAS,GAAG,CAAC,CAAEM,MAAM,CAASR,YAAY,CAAC;MAChDQ,MAAM,CAASL,QAAQ,GAAGD,SAAS;MACpC,OAAQM,MAAM,CAASR,YAAY,CAAC;IACxC,CAAC,MAAM;MACH;MACAQ,MAAM,CAACL,QAAQ,GAAG,CAAC,CAACK,MAAM,CAACL,QAAQ;IACvC;;IAEA;AACR;AACA;IACQ,IAAMM,WAAW,GAAGJ,UAAU,CAACK,MAAM,CAACD,WAAW;IAChDD,MAAM,CAASC,WAAW,CAAC,GAAGf,mCAAmC,CAC9DW,UAAU,CAACK,MAAM,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AgB,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;EAC7DD,gBAAgB,CAACQ,QAAQ,CAACC,IAAI,CAAC,MAAMC,aAAa,CAACJ,UAAU,CAAC,CAAC;AACnE","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/storage-remote-websocket/index.js b/dist/esm/plugins/storage-remote-websocket/index.js index bc68ecc115f..bfe88e2f551 100644 --- a/dist/esm/plugins/storage-remote-websocket/index.js +++ b/dist/esm/plugins/storage-remote-websocket/index.js @@ -16,7 +16,8 @@ export function startRxStorageRemoteWebsocketServer(options) { send(msg) { var ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId); ws.send(JSON.stringify(msg)); - } + }, + fakeVersion: options.fakeVersion }; var exposeState = exposeRxStorageRemote(exposeSettings); serverState.onConnection$.subscribe(ws => { diff --git a/dist/esm/plugins/storage-remote-websocket/index.js.map b/dist/esm/plugins/storage-remote-websocket/index.js.map index c4a1a283bb9..c9cf6ffe0d9 100644 --- a/dist/esm/plugins/storage-remote-websocket/index.js.map +++ b/dist/esm/plugins/storage-remote-websocket/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","names":["Subject","PROMISE_RESOLVE_VOID","getFromMapOrThrow","createWebSocketClient","startSocketServer","exposeRxStorageRemote","getRxStorageRemote","createErrorAnswer","startRxStorageRemoteWebsocketServer","options","serverState","websocketByConnectionId","Map","messages$","exposeSettings","asObservable","storage","database","customRequestHandler","send","msg","ws","connectionId","JSON","stringify","exposeState","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","Error","set","next","getRxStorageRemoteWebsocket","identifier","url","join","mode","messageChannelCreator","websocketClient","message$","socket","close"],"sources":["../../../../src/plugins/storage-remote-websocket/index.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport {\n PROMISE_RESOLVE_VOID,\n getFromMapOrThrow\n} from '../../plugins/utils/index.ts';\nimport {\n createWebSocketClient,\n startSocketServer\n} from '../replication-websocket/index.ts';\nimport { exposeRxStorageRemote } from '../storage-remote/remote.ts';\nimport { getRxStorageRemote } from '../storage-remote/rx-storage-remote.ts';\nimport { createErrorAnswer } from '../storage-remote/storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport type {\n RxStorageRemoteWebsocketClient,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './types.ts';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage as any,\n database: options.database as any,\n customRequestHandler: options.customRequestHandler,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n }\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (\n message.method !== 'create' &&\n message.method !== 'custom'\n ) {\n ws.send(\n JSON.stringify(\n createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))\n )\n );\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\nexport function getRxStorageRemoteWebsocket(\n options: RxStorageRemoteWebsocketClientOptions\n): RxStorageRemoteWebsocketClient {\n const identifier = [\n options.url,\n 'rx-remote-storage-websocket'\n ].join('');\n const storage = getRxStorageRemote({\n identifier,\n mode: options.mode,\n async messageChannelCreator() {\n const messages$ = new Subject();\n const websocketClient = await createWebSocketClient(options as any);\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n return {\n messages$,\n send(msg) {\n return websocketClient.socket.send(JSON.stringify(msg));\n },\n close() {\n websocketClient.socket.close();\n return PROMISE_RESOLVE_VOID;\n }\n };\n\n }\n });\n return storage;\n}\n\n\nexport * from './types.ts';\n\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,MAAM;AAI9B,SACIC,oBAAoB,EACpBC,iBAAiB,QACd,8BAA8B;AACrC,SACIC,qBAAqB,EACrBC,iBAAiB,QACd,mCAAmC;AAC1C,SAASC,qBAAqB,QAAQ,6BAA6B;AACnE,SAASC,kBAAkB,QAAQ,wCAAwC;AAC3E,SAASC,iBAAiB,QAAQ,6CAA6C;AAY/E,OAAO,SAASC,mCAAmCA,CAC/CC,OAA8C,EACX;EACnC,IAAMC,WAAW,GAAGN,iBAAiB,CAACK,OAAO,CAAC;EAE9C,IAAME,uBAAuB,GAAG,IAAIC,GAAG,CAAoB,CAAC;EAC5D,IAAMC,SAAS,GAAG,IAAIb,OAAO,CAAkB,CAAC;EAChD,IAAMc,cAA6C,GAAG;IAClDD,SAAS,EAAEA,SAAS,CAACE,YAAY,CAAC,CAAC;IACnCC,OAAO,EAAEP,OAAO,CAACO,OAAc;IAC/BC,QAAQ,EAAER,OAAO,CAACQ,QAAe;IACjCC,oBAAoB,EAAET,OAAO,CAACS,oBAAoB;IAClDC,IAAIA,CAACC,GAAG,EAAE;MACN,IAAMC,EAAE,GAAGnB,iBAAiB,CAACS,uBAAuB,EAAES,GAAG,CAACE,YAAY,CAAC;MACvED,EAAE,CAACF,IAAI,CAACI,IAAI,CAACC,SAAS,CAACJ,GAAG,CAAC,CAAC;IAChC;EACJ,CAAC;EACD,IAAMK,WAAW,GAAGpB,qBAAqB,CAACS,cAAc,CAAC;EAEzDJ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SAAS,GAAG,IAAIb,OAAO,CAAoB,CAAC;MAClD,IAAM+C,eAAe,GAAG,MAAM5C,qBAAqB,CAACM,OAAc,CAAC;MACnEsC,eAAe,CAACC,QAAQ,CAACrB,SAAS,CAACP,GAAG,IAAIP,SAAS,CAAC2B,IAAI,CAACpB,GAAG,CAAC,CAAC;MAC9D,OAAO;QACHP,SAAS;QACTM,IAAIA,CAACC,GAAG,EAAE;UACN,OAAO2B,eAAe,CAACE,MAAM,CAAC9B,IAAI,CAACI,IAAI,CAACC,SAAS,CAACJ,GAAG,CAAC,CAAC;QAC3D,CAAC;QACD8B,KAAKA,CAAA,EAAG;UACJH,eAAe,CAACE,MAAM,CAACC,KAAK,CAAC,CAAC;UAC9B,OAAOjD,oBAAoB;QAC/B;MACJ,CAAC;IAEL;EACJ,CAAC,CAAC;EACF,OAAOe,OAAO;AAClB;AAGA,cAAc,YAAY","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"index.js","names":["Subject","PROMISE_RESOLVE_VOID","getFromMapOrThrow","createWebSocketClient","startSocketServer","exposeRxStorageRemote","getRxStorageRemote","createErrorAnswer","startRxStorageRemoteWebsocketServer","options","serverState","websocketByConnectionId","Map","messages$","exposeSettings","asObservable","storage","database","customRequestHandler","send","msg","ws","connectionId","JSON","stringify","fakeVersion","exposeState","onConnection$","subscribe","onCloseHandlers","onclose","map","fn","on","messageString","message","parse","has","method","Error","set","next","getRxStorageRemoteWebsocket","identifier","url","join","mode","messageChannelCreator","websocketClient","message$","socket","close"],"sources":["../../../../src/plugins/storage-remote-websocket/index.ts"],"sourcesContent":["import { Subject } from 'rxjs';\nimport type {\n WebSocket\n} from 'ws';\nimport {\n PROMISE_RESOLVE_VOID,\n getFromMapOrThrow\n} from '../../plugins/utils/index.ts';\nimport {\n createWebSocketClient,\n startSocketServer\n} from '../replication-websocket/index.ts';\nimport { exposeRxStorageRemote } from '../storage-remote/remote.ts';\nimport { getRxStorageRemote } from '../storage-remote/rx-storage-remote.ts';\nimport { createErrorAnswer } from '../storage-remote/storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport type {\n RxStorageRemoteWebsocketClient,\n RxStorageRemoteWebsocketClientOptions,\n RxStorageRemoteWebsocketServerOptions,\n RxStorageRemoteWebsocketServerState\n} from './types.ts';\nexport function startRxStorageRemoteWebsocketServer(\n options: RxStorageRemoteWebsocketServerOptions\n): RxStorageRemoteWebsocketServerState {\n const serverState = startSocketServer(options);\n\n const websocketByConnectionId = new Map();\n const messages$ = new Subject();\n const exposeSettings: RxStorageRemoteExposeSettings = {\n messages$: messages$.asObservable(),\n storage: options.storage as any,\n database: options.database as any,\n customRequestHandler: options.customRequestHandler,\n send(msg) {\n const ws = getFromMapOrThrow(websocketByConnectionId, msg.connectionId);\n ws.send(JSON.stringify(msg));\n },\n fakeVersion: options.fakeVersion\n };\n const exposeState = exposeRxStorageRemote(exposeSettings);\n\n serverState.onConnection$.subscribe(ws => {\n const onCloseHandlers: Function[] = [];\n ws.onclose = () => {\n onCloseHandlers.map(fn => fn());\n };\n ws.on('message', (messageString: string) => {\n const message: MessageToRemote = JSON.parse(messageString);\n const connectionId = message.connectionId;\n if (!websocketByConnectionId.has(connectionId)) {\n /**\n * If first message is not 'create',\n * it is an error.\n */\n if (\n message.method !== 'create' &&\n message.method !== 'custom'\n ) {\n ws.send(\n JSON.stringify(\n createErrorAnswer(message, new Error('First call must be a create call but is: ' + JSON.stringify(message)))\n )\n );\n return;\n }\n websocketByConnectionId.set(connectionId, ws);\n }\n messages$.next(message);\n });\n });\n\n return {\n serverState,\n exposeState\n };\n}\n\nexport function getRxStorageRemoteWebsocket(\n options: RxStorageRemoteWebsocketClientOptions\n): RxStorageRemoteWebsocketClient {\n const identifier = [\n options.url,\n 'rx-remote-storage-websocket'\n ].join('');\n const storage = getRxStorageRemote({\n identifier,\n mode: options.mode,\n async messageChannelCreator() {\n const messages$ = new Subject();\n const websocketClient = await createWebSocketClient(options as any);\n websocketClient.message$.subscribe(msg => messages$.next(msg));\n return {\n messages$,\n send(msg) {\n return websocketClient.socket.send(JSON.stringify(msg));\n },\n close() {\n websocketClient.socket.close();\n return PROMISE_RESOLVE_VOID;\n }\n };\n\n }\n });\n return storage;\n}\n\n\nexport * from './types.ts';\n\n"],"mappings":"AAAA,SAASA,OAAO,QAAQ,MAAM;AAI9B,SACIC,oBAAoB,EACpBC,iBAAiB,QACd,8BAA8B;AACrC,SACIC,qBAAqB,EACrBC,iBAAiB,QACd,mCAAmC;AAC1C,SAASC,qBAAqB,QAAQ,6BAA6B;AACnE,SAASC,kBAAkB,QAAQ,wCAAwC;AAC3E,SAASC,iBAAiB,QAAQ,6CAA6C;AAY/E,OAAO,SAASC,mCAAmCA,CAC/CC,OAA8C,EACX;EACnC,IAAMC,WAAW,GAAGN,iBAAiB,CAACK,OAAO,CAAC;EAE9C,IAAME,uBAAuB,GAAG,IAAIC,GAAG,CAAoB,CAAC;EAC5D,IAAMC,SAAS,GAAG,IAAIb,OAAO,CAAkB,CAAC;EAChD,IAAMc,cAA6C,GAAG;IAClDD,SAAS,EAAEA,SAAS,CAACE,YAAY,CAAC,CAAC;IACnCC,OAAO,EAAEP,OAAO,CAACO,OAAc;IAC/BC,QAAQ,EAAER,OAAO,CAACQ,QAAe;IACjCC,oBAAoB,EAAET,OAAO,CAACS,oBAAoB;IAClDC,IAAIA,CAACC,GAAG,EAAE;MACN,IAAMC,EAAE,GAAGnB,iBAAiB,CAACS,uBAAuB,EAAES,GAAG,CAACE,YAAY,CAAC;MACvED,EAAE,CAACF,IAAI,CAACI,IAAI,CAACC,SAAS,CAACJ,GAAG,CAAC,CAAC;IAChC,CAAC;IACDK,WAAW,EAAEhB,OAAO,CAACgB;EACzB,CAAC;EACD,IAAMC,WAAW,GAAGrB,qBAAqB,CAACS,cAAc,CAAC;EAEzDJ,WAAW,CAACiB,aAAa,CAACC,SAAS,CAACP,EAAE,IAAI;IACtC,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eAAe,GAAG,MAAM7C,qBAAqB,CAACM,OAAc,CAAC;MACnEuC,eAAe,CAACC,QAAQ,CAACrB,SAAS,CAACR,GAAG,IAAIP,SAAS,CAAC4B,IAAI,CAACrB,GAAG,CAAC,CAAC;MAC9D,OAAO;QACHP,SAAS;QACTM,IAAIA,CAACC,GAAG,EAAE;UACN,OAAO4B,eAAe,CAACE,MAAM,CAAC/B,IAAI,CAACI,IAAI,CAACC,SAAS,CAACJ,GAAG,CAAC,CAAC;QAC3D,CAAC;QACD+B,KAAKA,CAAA,EAAG;UACJH,eAAe,CAACE,MAAM,CAACC,KAAK,CAAC,CAAC;UAC9B,OAAOlD,oBAAoB;QAC/B;MACJ,CAAC;IAEL;EACJ,CAAC,CAAC;EACF,OAAOe,OAAO;AAClB;AAGA,cAAc,YAAY","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/storage-remote-websocket/types.js.map b/dist/esm/plugins/storage-remote-websocket/types.js.map index dd77baacfbb..37578fa1cc3 100644 --- a/dist/esm/plugins/storage-remote-websocket/types.js.map +++ b/dist/esm/plugins/storage-remote-websocket/types.js.map @@ -1 +1 @@ -{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/storage-remote-websocket/types.ts"],"sourcesContent":["import type {\n WebsocketServerState\n} from '../replication-websocket/index.ts';\nimport type { ServerOptions, ClientOptions } from 'ws';\nimport type { RxDatabase, RxStorage } from '../../types/index.d.ts';\nimport type {\n CustomRequestHandler,\n RxStorageRemoteExposeType,\n RxStorageRemoteSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport { RxStorageRemote } from '../storage-remote/index.ts';\n\nexport type RxStorageRemoteWebsocketServerOptions = ServerOptions & {\n storage?: RxStorage;\n database?: RxDatabase;\n customRequestHandler?: CustomRequestHandler;\n};\n\nexport type RxStorageRemoteWebsocketServerState = {\n serverState: WebsocketServerState;\n exposeState: RxStorageRemoteExposeType;\n};\n\nexport type RxStorageRemoteWebsocketClientOptions = ClientOptions & {\n url: string;\n mode: RxStorageRemoteSettings['mode'];\n};\n\nexport type RxStorageRemoteWebsocketClient = RxStorageRemote;\n"],"mappings":"","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"types.js","names":[],"sources":["../../../../src/plugins/storage-remote-websocket/types.ts"],"sourcesContent":["import type {\n WebsocketServerState\n} from '../replication-websocket/index.ts';\nimport type { ServerOptions, ClientOptions } from 'ws';\nimport type { RxDatabase, RxStorage } from '../../types/index.d.ts';\nimport type {\n CustomRequestHandler,\n RxStorageRemoteExposeType,\n RxStorageRemoteSettings\n} from '../storage-remote/storage-remote-types.ts';\nimport { RxStorageRemote } from '../storage-remote/index.ts';\n\nexport type RxStorageRemoteWebsocketServerOptions = ServerOptions & {\n storage?: RxStorage;\n database?: RxDatabase;\n customRequestHandler?: CustomRequestHandler;\n /**\n * Used in tests to simulate what happens if the remote\n * was build on a different RxDB version.\n */\n fakeVersion?: string;\n};\n\nexport type RxStorageRemoteWebsocketServerState = {\n serverState: WebsocketServerState;\n exposeState: RxStorageRemoteExposeType;\n};\n\nexport type RxStorageRemoteWebsocketClientOptions = ClientOptions & {\n url: string;\n mode: RxStorageRemoteSettings['mode'];\n};\n\nexport type RxStorageRemoteWebsocketClient = RxStorageRemote;\n"],"mappings":"","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/storage-remote/remote.js b/dist/esm/plugins/storage-remote/remote.js index c4043ada5ef..aa6b3d6a070 100644 --- a/dist/esm/plugins/storage-remote/remote.js +++ b/dist/esm/plugins/storage-remote/remote.js @@ -1,7 +1,8 @@ import { filter } from 'rxjs'; -import { deepEqual, ensureNotFalsy } from "../../plugins/utils/index.js"; +import { deepEqual, ensureNotFalsy, RXDB_VERSION } from "../../plugins/utils/index.js"; import { createAnswer, createErrorAnswer } from "./storage-remote-helpers.js"; import { getChangedDocumentsSince } from "../../rx-storage-helper.js"; +import { newRxError } from "../../rx-error.js"; /** * Run this on the 'remote' part, @@ -46,7 +47,17 @@ export function exposeRxStorageRemote(settings) { throw new Error('no base given'); } } + var mustBeRxDBVersion = settings.fakeVersion ? settings.fakeVersion : RXDB_VERSION; settings.messages$.pipe(filter(msg => msg.method === 'create')).subscribe(async msg => { + if (msg.version !== mustBeRxDBVersion) { + settings.send(createErrorAnswer(msg, newRxError('RM1', { + args: { + mainVersion: msg.version, + remoteVersion: mustBeRxDBVersion + } + }))); + return; + } var connectionId = msg.connectionId; /** diff --git a/dist/esm/plugins/storage-remote/remote.js.map b/dist/esm/plugins/storage-remote/remote.js.map index 29b9cd43cd6..c63be596a5d 100644 --- a/dist/esm/plugins/storage-remote/remote.js.map +++ b/dist/esm/plugins/storage-remote/remote.js.map @@ -1 +1 @@ -{"version":3,"file":"remote.js","names":["filter","deepEqual","ensureNotFalsy","createAnswer","createErrorAnswer","getChangedDocumentsSince","exposeRxStorageRemote","settings","instanceByFullName","Map","messages$","pipe","msg","method","subscribe","customRequestHandler","send","Error","result","params","err","getRxStorageInstance","storage","createStorageInstance","database","storageInstances","Array","from","collectionName","storageInstance","find","instance","console","dir","JSON","stringify","schema","existingSchema","Promise","resolve","connectionId","isArray","fullName","databaseName","version","join","state","get","storageInstancePromise","connectionIds","Set","set","add","subs","push","changeStream","changes","message","answerTo","return","connectionClosed","closeThisConnection","forEach","sub","unsubscribe","delete","collection","collections","onClose","subMsg","plainMessage","size"],"sources":["../../../../src/plugins/storage-remote/remote.ts"],"sourcesContent":["import { filter, Subscription } from 'rxjs';\nimport type {\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types/index.d.ts';\nimport {\n deepEqual,\n ensureNotFalsy\n} from '../../plugins/utils/index.ts';\nimport { createAnswer, createErrorAnswer } from './storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteExposeSettingsRxDatabase,\n RxStorageRemoteExposeSettingsRxStorage,\n RxStorageRemoteExposeType\n} from './storage-remote-types.ts';\nimport { getChangedDocumentsSince } from '../../rx-storage-helper.ts';\n\n/**\n * Run this on the 'remote' part,\n * so that RxStorageMessageChannel can connect to it.\n */\nexport function exposeRxStorageRemote(settings: RxStorageRemoteExposeSettings): RxStorageRemoteExposeType {\n type InstanceState = {\n storageInstancePromise: Promise>;\n connectionIds: Set;\n params: RxStorageInstanceCreationParams;\n };\n const instanceByFullName: Map = new Map();\n\n\n settings.messages$.pipe(\n filter(msg => msg.method === 'custom')\n ).subscribe(async (msg) => {\n if (!settings.customRequestHandler) {\n settings.send(createErrorAnswer(\n msg,\n new Error('Remote storage: cannot resolve custom request because settings.customRequestHandler is not set')\n ));\n } else {\n try {\n const result = await settings.customRequestHandler(msg.params);\n settings.send(createAnswer(msg, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(\n msg,\n err\n ));\n }\n }\n });\n\n\n function getRxStorageInstance(params: any): Promise> {\n if ((settings as RxStorageRemoteExposeSettingsRxStorage).storage) {\n return (settings as RxStorageRemoteExposeSettingsRxStorage).storage.createStorageInstance(params);\n } else if ((settings as RxStorageRemoteExposeSettingsRxDatabase).database) {\n const storageInstances = Array.from((settings as RxStorageRemoteExposeSettingsRxDatabase).database.storageInstances);\n const collectionName = params.collectionName;\n const storageInstance = storageInstances.find(instance => instance.collectionName === collectionName);\n if (!storageInstance) {\n console.dir(storageInstances);\n throw new Error('storageInstance does not exist ' + JSON.stringify({\n collectionName\n }));\n }\n const schema = params.schema;\n if (!deepEqual(schema, storageInstance.schema)) {\n throw new Error('Wrong schema ' + JSON.stringify({\n schema,\n existingSchema: storageInstance.schema\n }));\n }\n return Promise.resolve(storageInstance);\n } else {\n throw new Error('no base given');\n }\n }\n\n settings.messages$.pipe(\n filter(msg => msg.method === 'create')\n ).subscribe(async (msg) => {\n const connectionId = msg.connectionId;\n\n /**\n * Do an isArray check here\n * for runtime check types to ensure we have\n * instance creation params and not method input params.\n */\n if (Array.isArray(msg.params)) {\n return;\n }\n const params = msg.params;\n const collectionName = params.collectionName;\n\n /**\n * We de-duplicate the storage instances.\n * This makes sense in many environments like\n * electron where on main process contains the storage\n * for multiple renderer processes. Same goes for SharedWorkers etc.\n */\n const fullName = [\n params.databaseName,\n params.collectionName,\n params.schema.version\n ].join('|');\n let state = instanceByFullName.get(fullName);\n if (!state) {\n try {\n state = {\n /**\n * We work with a promise here to ensure\n * that parallel create-calls will still end up\n * with exactly one instance and not more.\n */\n storageInstancePromise: getRxStorageInstance(params),\n connectionIds: new Set(),\n params\n };\n instanceByFullName.set(fullName, state);\n\n /**\n * Must await the creation here\n * so that in case of an error,\n * it knows about the error message and can send\n * that back to the main process. \n */\n await state.storageInstancePromise;\n } catch (err: any) {\n settings.send(createErrorAnswer(msg, err));\n return;\n }\n } else {\n // if instance already existed, ensure that the schema is equal\n if (!deepEqual(params.schema, state.params.schema)) {\n settings.send(createErrorAnswer(msg, new Error('Remote storage: schema not equal to existing storage')));\n return;\n }\n }\n state.connectionIds.add(msg.connectionId);\n const subs: Subscription[] = [];\n\n const storageInstance = await state.storageInstancePromise;\n /**\n * Automatically subscribe to the changeStream()\n * because we always need them.\n */\n subs.push(\n storageInstance.changeStream().subscribe(changes => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'changestream',\n method: 'changeStream',\n return: changes\n };\n settings.send(message);\n })\n );\n\n let connectionClosed = false;\n function closeThisConnection() {\n if (connectionClosed) {\n return;\n }\n connectionClosed = true;\n subs.forEach(sub => sub.unsubscribe());\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n instanceByFullName.delete(fullName);\n /**\n * TODO how to notify the other ports on remove() ?\n */\n }\n\n // also close the connection when the collection gets closed\n if ((settings as RxStorageRemoteExposeSettingsRxDatabase).database) {\n const database = (settings as RxStorageRemoteExposeSettingsRxDatabase).database;\n const collection = database.collections[collectionName];\n if (collection) {\n collection.onClose.push(() => closeThisConnection());\n } else {\n database.onClose.push(() => closeThisConnection());\n }\n }\n\n subs.push(\n settings.messages$.pipe(\n filter(subMsg => (subMsg as MessageToRemote).connectionId === connectionId)\n ).subscribe(async (plainMessage) => {\n const message: MessageToRemote = plainMessage as any;\n if (\n message.method === 'create' ||\n message.method === 'custom'\n ) {\n return;\n }\n if (!Array.isArray(message.params)) {\n return;\n }\n let result;\n try {\n if (\n message.method === 'close' &&\n (settings as RxStorageRemoteExposeSettingsRxDatabase).database\n ) {\n /**\n * Do not close the storageInstance if it was taken from\n * a running RxDatabase.\n * In that case we only close the instance\n * when the RxDatabase gets closed.\n */\n settings.send(createAnswer(message, null));\n return;\n }\n /**\n * On calls to 'close()',\n * we only close the main instance if there are no other\n * ports connected.\n */\n if (\n message.method === 'close' &&\n ensureNotFalsy(state).connectionIds.size > 1\n ) {\n settings.send(createAnswer(message, null));\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n subs.forEach(sub => sub.unsubscribe());\n return;\n }\n\n if (message.method === 'getChangedDocumentsSince' && !storageInstance.getChangedDocumentsSince) {\n result = await getChangedDocumentsSince(\n storageInstance,\n message.params[0],\n message.params[1]\n );\n } else {\n result = await (storageInstance as any)[message.method](\n message.params[0],\n message.params[1],\n message.params[2],\n message.params[3]\n );\n }\n if (\n message.method === 'close' ||\n message.method === 'remove'\n ) {\n closeThisConnection();\n }\n settings.send(createAnswer(message, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(message, err));\n }\n })\n );\n\n settings.send(createAnswer(msg, 'ok'));\n });\n\n return {\n instanceByFullName\n };\n}\n"],"mappings":"AAAA,SAASA,MAAM,QAAsB,MAAM;AAK3C,SACIC,SAAS,EACTC,cAAc,QACX,8BAA8B;AACrC,SAASC,YAAY,EAAEC,iBAAiB,QAAQ,6BAA6B;AAS7E,SAASC,wBAAwB,QAAQ,4BAA4B;;AAErE;AACA;AACA;AACA;AACA,OAAO,SAASC,qBAAqBA,CAACC,QAAuC,EAA6B;EAMtG,IAAMC,kBAA8C,GAAG,IAAIC,GAAG,CAAC,CAAC;EAGhEF,QAAQ,CAACG,SAAS,CAACC,IAAI,CACnBX,MAAM,CAACY,GAAG,IAAIA,GAAG,CAACC,MAAM,KAAK,QAAQ,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AI,CAAC,CAAC;EAC1C,CAAC,CAAC;EAEF,OAAO;IACHJ;EACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"remote.js","names":["filter","deepEqual","ensureNotFalsy","RXDB_VERSION","createAnswer","createErrorAnswer","getChangedDocumentsSince","newRxError","exposeRxStorageRemote","settings","instanceByFullName","Map","messages$","pipe","msg","method","subscribe","customRequestHandler","send","Error","result","params","err","getRxStorageInstance","storage","createStorageInstance","database","storageInstances","Array","from","collectionName","storageInstance","find","instance","console","dir","JSON","stringify","schema","existingSchema","Promise","resolve","mustBeRxDBVersion","fakeVersion","version","args","mainVersion","remoteVersion","connectionId","isArray","fullName","databaseName","join","state","get","storageInstancePromise","connectionIds","Set","set","add","subs","push","changeStream","changes","message","answerTo","return","connectionClosed","closeThisConnection","forEach","sub","unsubscribe","delete","collection","collections","onClose","subMsg","plainMessage","size"],"sources":["../../../../src/plugins/storage-remote/remote.ts"],"sourcesContent":["import { filter, Subscription } from 'rxjs';\nimport type {\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types/index.d.ts';\nimport {\n deepEqual,\n ensureNotFalsy,\n RXDB_VERSION\n} from '../../plugins/utils/index.ts';\nimport { createAnswer, createErrorAnswer } from './storage-remote-helpers.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RxStorageRemoteExposeSettings,\n RxStorageRemoteExposeSettingsRxDatabase,\n RxStorageRemoteExposeSettingsRxStorage,\n RxStorageRemoteExposeType\n} from './storage-remote-types.ts';\nimport { getChangedDocumentsSince } from '../../rx-storage-helper.ts';\nimport { newRxError } from '../../rx-error.ts';\n\n/**\n * Run this on the 'remote' part,\n * so that RxStorageMessageChannel can connect to it.\n */\nexport function exposeRxStorageRemote(settings: RxStorageRemoteExposeSettings): RxStorageRemoteExposeType {\n type InstanceState = {\n storageInstancePromise: Promise>;\n connectionIds: Set;\n params: RxStorageInstanceCreationParams;\n };\n const instanceByFullName: Map = new Map();\n\n\n settings.messages$.pipe(\n filter(msg => msg.method === 'custom')\n ).subscribe(async (msg) => {\n if (!settings.customRequestHandler) {\n settings.send(createErrorAnswer(\n msg,\n new Error('Remote storage: cannot resolve custom request because settings.customRequestHandler is not set')\n ));\n } else {\n try {\n const result = await settings.customRequestHandler(msg.params);\n settings.send(createAnswer(msg, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(\n msg,\n err\n ));\n }\n }\n });\n\n\n function getRxStorageInstance(params: any): Promise> {\n if ((settings as RxStorageRemoteExposeSettingsRxStorage).storage) {\n return (settings as RxStorageRemoteExposeSettingsRxStorage).storage.createStorageInstance(params);\n } else if ((settings as RxStorageRemoteExposeSettingsRxDatabase).database) {\n const storageInstances = Array.from((settings as RxStorageRemoteExposeSettingsRxDatabase).database.storageInstances);\n const collectionName = params.collectionName;\n const storageInstance = storageInstances.find(instance => instance.collectionName === collectionName);\n if (!storageInstance) {\n console.dir(storageInstances);\n throw new Error('storageInstance does not exist ' + JSON.stringify({\n collectionName\n }));\n }\n const schema = params.schema;\n if (!deepEqual(schema, storageInstance.schema)) {\n throw new Error('Wrong schema ' + JSON.stringify({\n schema,\n existingSchema: storageInstance.schema\n }));\n }\n return Promise.resolve(storageInstance);\n } else {\n throw new Error('no base given');\n }\n }\n\n const mustBeRxDBVersion = settings.fakeVersion ? settings.fakeVersion : RXDB_VERSION;\n settings.messages$.pipe(\n filter(msg => msg.method === 'create')\n ).subscribe(async (msg) => {\n if (msg.version !== mustBeRxDBVersion) {\n settings.send(createErrorAnswer(msg, newRxError('RM1', {\n args: {\n mainVersion: msg.version,\n remoteVersion: mustBeRxDBVersion\n }\n })));\n return;\n }\n\n const connectionId = msg.connectionId;\n\n /**\n * Do an isArray check here\n * for runtime check types to ensure we have\n * instance creation params and not method input params.\n */\n if (Array.isArray(msg.params)) {\n return;\n }\n const params = msg.params;\n const collectionName = params.collectionName;\n\n /**\n * We de-duplicate the storage instances.\n * This makes sense in many environments like\n * electron where on main process contains the storage\n * for multiple renderer processes. Same goes for SharedWorkers etc.\n */\n const fullName = [\n params.databaseName,\n params.collectionName,\n params.schema.version\n ].join('|');\n let state = instanceByFullName.get(fullName);\n if (!state) {\n try {\n state = {\n /**\n * We work with a promise here to ensure\n * that parallel create-calls will still end up\n * with exactly one instance and not more.\n */\n storageInstancePromise: getRxStorageInstance(params),\n connectionIds: new Set(),\n params\n };\n instanceByFullName.set(fullName, state);\n\n /**\n * Must await the creation here\n * so that in case of an error,\n * it knows about the error message and can send\n * that back to the main process. \n */\n await state.storageInstancePromise;\n } catch (err: any) {\n settings.send(createErrorAnswer(msg, err));\n return;\n }\n } else {\n // if instance already existed, ensure that the schema is equal\n if (!deepEqual(params.schema, state.params.schema)) {\n settings.send(createErrorAnswer(msg, new Error('Remote storage: schema not equal to existing storage')));\n return;\n }\n }\n state.connectionIds.add(msg.connectionId);\n const subs: Subscription[] = [];\n\n const storageInstance = await state.storageInstancePromise;\n /**\n * Automatically subscribe to the changeStream()\n * because we always need them.\n */\n subs.push(\n storageInstance.changeStream().subscribe(changes => {\n const message: MessageFromRemote = {\n connectionId,\n answerTo: 'changestream',\n method: 'changeStream',\n return: changes\n };\n settings.send(message);\n })\n );\n\n let connectionClosed = false;\n function closeThisConnection() {\n if (connectionClosed) {\n return;\n }\n connectionClosed = true;\n subs.forEach(sub => sub.unsubscribe());\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n instanceByFullName.delete(fullName);\n /**\n * TODO how to notify the other ports on remove() ?\n */\n }\n\n // also close the connection when the collection gets closed\n if ((settings as RxStorageRemoteExposeSettingsRxDatabase).database) {\n const database = (settings as RxStorageRemoteExposeSettingsRxDatabase).database;\n const collection = database.collections[collectionName];\n if (collection) {\n collection.onClose.push(() => closeThisConnection());\n } else {\n database.onClose.push(() => closeThisConnection());\n }\n }\n\n subs.push(\n settings.messages$.pipe(\n filter(subMsg => (subMsg as MessageToRemote).connectionId === connectionId)\n ).subscribe(async (plainMessage) => {\n const message: MessageToRemote = plainMessage as any;\n if (\n message.method === 'create' ||\n message.method === 'custom'\n ) {\n return;\n }\n if (!Array.isArray(message.params)) {\n return;\n }\n let result;\n try {\n if (\n message.method === 'close' &&\n (settings as RxStorageRemoteExposeSettingsRxDatabase).database\n ) {\n /**\n * Do not close the storageInstance if it was taken from\n * a running RxDatabase.\n * In that case we only close the instance\n * when the RxDatabase gets closed.\n */\n settings.send(createAnswer(message, null));\n return;\n }\n /**\n * On calls to 'close()',\n * we only close the main instance if there are no other\n * ports connected.\n */\n if (\n message.method === 'close' &&\n ensureNotFalsy(state).connectionIds.size > 1\n ) {\n settings.send(createAnswer(message, null));\n ensureNotFalsy(state).connectionIds.delete(connectionId);\n subs.forEach(sub => sub.unsubscribe());\n return;\n }\n\n if (message.method === 'getChangedDocumentsSince' && !storageInstance.getChangedDocumentsSince) {\n result = await getChangedDocumentsSince(\n storageInstance,\n message.params[0],\n message.params[1]\n );\n } else {\n result = await (storageInstance as any)[message.method](\n message.params[0],\n message.params[1],\n message.params[2],\n message.params[3]\n );\n }\n if (\n message.method === 'close' ||\n message.method === 'remove'\n ) {\n closeThisConnection();\n }\n settings.send(createAnswer(message, result));\n } catch (err: any) {\n settings.send(createErrorAnswer(message, err));\n }\n })\n );\n\n settings.send(createAnswer(msg, 'ok'));\n });\n\n return {\n instanceByFullName\n };\n}\n"],"mappings":"AAAA,SAASA,MAAM,QAAsB,MAAM;AAK3C,SACIC,SAAS,EACTC,cAAc,EACdC,YAAY,QACT,8BAA8B;AACrC,SAASC,YAAY,EAAEC,iBAAiB,QAAQ,6BAA6B;AAS7E,SAASC,wBAAwB,QAAQ,4BAA4B;AACrE,SAASC,UAAU,QAAQ,mBAAmB;;AAE9C;AACA;AACA;AACA;AACA,OAAO,SAASC,qBAAqBA,CAACC,QAAuC,EAA6B;EAMtG,IAAMC,kBAA8C,GAAG,IAAIC,GAAG,CAAC,CAAC;EAGhEF,QAAQ,CAACG,SAAS,CAACC,IAAI,CACnBb,MAAM,CAACc,GAAG,IAAIA,GAAG,CAACC,MAAM,KAAK,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C1BiD,OAAO,CAACjD,MAAM,KAAK,QAAQ,EAC7B;UACEqD,mBAAmB,CAAC,CAAC;QACzB;QACA3D,QAAQ,CAACS,IAAI,CAACd,YAAY,CAAC4D,OAAO,EAAE5C,MAAM,CAAC,CAAC;MAChD,CAAC,CAAC,OAAOE,GAAQ,EAAE;QACfb,QAAQ,CAACS,IAAI,CAACb,iBAAiB,CAAC2D,OAAO,EAAE1C,GAAG,CAAC,CAAC;MAClD;IACJ,CAAC,CACL,CAAC;IAEDb,QAAQ,CAACS,IAAI,CAACd,YAAY,CAACU,GAAG,EAAE,IAAI,CAAC,CAAC;EAC1C,CAAC,CAAC;EAEF,OAAO;IACHJ;EACJ,CAAC;AACL","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/storage-remote/rx-storage-remote.js b/dist/esm/plugins/storage-remote/rx-storage-remote.js index 6f739d4e020..6a74d1ad2fd 100644 --- a/dist/esm/plugins/storage-remote/rx-storage-remote.js +++ b/dist/esm/plugins/storage-remote/rx-storage-remote.js @@ -36,6 +36,7 @@ export var RxStorageRemote = /*#__PURE__*/function () { messageChannel.send({ connectionId, method: 'create', + version: RXDB_VERSION, requestId, params }); @@ -58,6 +59,7 @@ export var RxStorageRemote = /*#__PURE__*/function () { messageChannel.send({ connectionId, method: 'custom', + version: RXDB_VERSION, requestId, params: data }); @@ -118,6 +120,7 @@ export var RxStorageInstanceRemote = /*#__PURE__*/function () { var message = { connectionId: this.internals.connectionId, requestId, + version: RXDB_VERSION, method: methodName, params }; diff --git a/dist/esm/plugins/storage-remote/rx-storage-remote.js.map b/dist/esm/plugins/storage-remote/rx-storage-remote.js.map index 3b24807593b..c6192ff808d 100644 --- a/dist/esm/plugins/storage-remote/rx-storage-remote.js.map +++ b/dist/esm/plugins/storage-remote/rx-storage-remote.js.map @@ -1 +1 @@ -{"version":3,"file":"rx-storage-remote.js","names":["firstValueFrom","filter","Subject","RXDB_VERSION","randomToken","closeMessageChannel","getMessageChannel","RxStorageRemote","settings","name","rxdbVersion","seed","lastRequestId","mode","messageChannelIfOneMode","_proto","prototype","getRequestId","newId","createStorageInstance","params","connectionId","cacheKeys","push","collectionName","databaseName","messageChannel","requestId","waitForOkPromise","messages$","pipe","msg","answerTo","send","method","waitForOkResult","error","Error","JSON","stringify","RxStorageInstanceRemote","schema","options","customRequest","data","messageChannelCreator","waitForAnswerPromise","response","close","return","getMessageReturn","parse","storage","internals","changes$","subs","subscribe","next","_proto2","requestRemote","methodName","responsePromise","message","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","digest","getChangedDocumentsSince","limit","checkpoint","changeStream","asObservable","cleanup","minDeletedTime","closed","forEach","sub","unsubscribe","complete","remove","getRxStorageRemote","withDefaults","Object","assign"],"sources":["../../../../src/plugins/storage-remote/rx-storage-remote.ts"],"sourcesContent":["import {\n firstValueFrom,\n filter,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from '../../types/index.d.ts';\nimport {\n RXDB_VERSION,\n randomToken\n} from '../../plugins/utils/index.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RemoteMessageChannel,\n RxStorageRemoteInternals,\n RxStorageRemoteSettings\n} from './storage-remote-types.ts';\nimport { closeMessageChannel, getMessageChannel } from './message-channel-cache.ts';\nimport { ensureRxStorageInstanceParamsAreCorrect } from '../../rx-storage-helper.ts';\n\n\nexport class RxStorageRemote implements RxStorage {\n public readonly name: string = 'remote';\n public readonly rxdbVersion = RXDB_VERSION;\n\n private seed: string = randomToken(10);\n private lastRequestId: number = 0;\n public messageChannelIfOneMode?: Promise;\n constructor(\n public readonly settings: RxStorageRemoteSettings\n ) {\n if (settings.mode === 'one') {\n this.messageChannelIfOneMode = getMessageChannel(\n settings,\n [],\n true\n );\n }\n }\n\n public getRequestId() {\n const newId = this.lastRequestId++;\n return this.seed + '|' + newId;\n }\n\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n const connectionId = 'c|' + this.getRequestId();\n\n const cacheKeys: string[] = [\n 'mode-' + this.settings.mode\n ];\n switch (this.settings.mode) {\n case 'collection':\n cacheKeys.push('collection-' + params.collectionName);\n // eslint-disable-next-line no-fallthrough\n case 'database':\n cacheKeys.push('database-' + params.databaseName);\n // eslint-disable-next-line no-fallthrough\n case 'storage':\n cacheKeys.push('seed-' + this.seed);\n }\n const messageChannel = await (this.messageChannelIfOneMode ?\n this.messageChannelIfOneMode :\n getMessageChannel(\n this.settings,\n cacheKeys\n )\n );\n\n const requestId = this.getRequestId();\n const waitForOkPromise = firstValueFrom(messageChannel.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n messageChannel.send({\n connectionId,\n method: 'create',\n requestId,\n params\n });\n\n const waitForOkResult = await waitForOkPromise;\n if (waitForOkResult.error) {\n await closeMessageChannel(messageChannel);\n throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error));\n }\n\n return new RxStorageInstanceRemote(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n params,\n connectionId,\n messageChannel\n },\n params.options\n );\n }\n\n async customRequest(data: In): Promise {\n const messageChannel = await this.settings.messageChannelCreator();\n const requestId = this.getRequestId();\n const connectionId = 'custom|request|' + requestId;\n const waitForAnswerPromise = firstValueFrom(messageChannel.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n messageChannel.send({\n connectionId,\n method: 'custom',\n requestId,\n params: data\n });\n const response = await waitForAnswerPromise;\n if (response.error) {\n await messageChannel.close();\n throw new Error('could not run customRequest(): ' + JSON.stringify({\n data,\n error: response.error\n }));\n } else {\n await messageChannel.close();\n return response.return;\n }\n\n }\n}\n\n/**\n * Because postMessage() can be very slow on complex objects,\n * and some RxStorage implementations do need a JSON-string internally\n * anyway, it is allowed to transfer a string instead of an object\n * which must then be JSON.parse()-ed before RxDB can use it.\n * @link https://surma.dev/things/is-postmessage-slow/\n */\nfunction getMessageReturn(\n msg: MessageFromRemote\n) {\n if (msg.method === 'getAttachmentData') {\n return msg.return;\n } else {\n if (typeof msg.return === 'string') {\n return JSON.parse(msg.return);\n } else {\n return msg.return;\n }\n }\n}\n\nexport class RxStorageInstanceRemote implements RxStorageInstance {\n private changes$: Subject>, any>> = new Subject();\n private subs: Subscription[] = [];\n\n private closed?: Promise;\n messages$: Observable;\n\n constructor(\n public readonly storage: RxStorageRemote,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: RxStorageRemoteInternals,\n public readonly options: Readonly\n ) {\n this.messages$ = this.internals.messageChannel.messages$.pipe(\n filter(msg => msg.connectionId === this.internals.connectionId)\n );\n this.subs.push(\n this.messages$.subscribe(msg => {\n if (msg.method === 'changeStream') {\n this.changes$.next(getMessageReturn(msg));\n }\n })\n );\n }\n\n private async requestRemote(\n methodName: keyof RxStorageInstance,\n params: any\n ) {\n const requestId = this.storage.getRequestId();\n const responsePromise = firstValueFrom(\n this.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n )\n );\n const message: MessageToRemote = {\n connectionId: this.internals.connectionId,\n requestId,\n method: methodName,\n params\n };\n this.internals.messageChannel.send(message);\n const response = await responsePromise;\n if (response.error) {\n throw new Error('could not requestRemote: ' + JSON.stringify({\n methodName,\n params,\n error: response.error\n }, null, 4));\n } else {\n return getMessageReturn(response);\n }\n }\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.requestRemote('bulkWrite', [documentWrites, context]);\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise[]> {\n return this.requestRemote('findDocumentsById', [ids, deleted]);\n }\n query(preparedQuery: any): Promise> {\n return this.requestRemote('query', [preparedQuery]);\n }\n count(preparedQuery: any): Promise {\n return this.requestRemote('count', [preparedQuery]);\n }\n getAttachmentData(documentId: string, attachmentId: string, digest: string): Promise {\n return this.requestRemote('getAttachmentData', [documentId, attachmentId, digest]);\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ): Promise<\n {\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n return this.requestRemote('getChangedDocumentsSince', [limit, checkpoint]);\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number): Promise {\n return this.requestRemote('cleanup', [minDeletedTime]);\n }\n async close(): Promise {\n if (this.closed) {\n return this.closed;\n }\n this.closed = (async () => {\n this.subs.forEach(sub => sub.unsubscribe());\n this.changes$.complete();\n await this.requestRemote('close', []);\n await closeMessageChannel(this.internals.messageChannel);\n })();\n return this.closed;\n }\n async remove(): Promise {\n if (this.closed) {\n throw new Error('already closed');\n }\n this.closed = (async () => {\n await this.requestRemote('remove', []);\n await closeMessageChannel(this.internals.messageChannel);\n })();\n return this.closed;\n }\n}\n\nexport function getRxStorageRemote(settings: RxStorageRemoteSettings): RxStorageRemote {\n const withDefaults = Object.assign({\n mode: 'storage'\n }, settings);\n return new RxStorageRemote(withDefaults);\n}\n"],"mappings":"AAAA,SACIA,cAAc,EACdC,MAAM,EAENC,OAAO,QAEJ,MAAM;AAcb,SACIC,YAAY,EACZC,WAAW,QACR,8BAA8B;AAQrC,SAASC,mBAAmB,EAAEC,iBAAiB,QAAQ,4BAA4B;AAInF,WAAaC,eAAe;EAOxB,SAAAA,gBACoBC,QAAiC,EACnD;IAAA,KARcC,IAAI,GAAW,QAAQ;IAAA,KACvBC,WAAW,GAAGP,YAAY;IAAA,KAElCQ,IAAI,GAAWP,WAAW,CAAC,EAAE,CAAC;IAAA,KAC9BQ,aAAa,GAAW,CAAC;IAAA,KAGbJ,QAAiC,GAAjCA,QAAiC;IAEjD,IAAIA,QAAQ,CAACK,IAAI,KAAK,KAAK,EAAE;MACzB,IAAI,CAACC,uBAAuB,GAAGR,iBAAiB,CAC5CE,QAAQ,E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firstValueFrom","filter","Subject","RXDB_VERSION","randomToken","closeMessageChannel","getMessageChannel","RxStorageRemote","settings","name","rxdbVersion","seed","lastRequestId","mode","messageChannelIfOneMode","_proto","prototype","getRequestId","newId","createStorageInstance","params","connectionId","cacheKeys","push","collectionName","databaseName","messageChannel","requestId","waitForOkPromise","messages$","pipe","msg","answerTo","send","method","version","waitForOkResult","error","Error","JSON","stringify","RxStorageInstanceRemote","schema","options","customRequest","data","messageChannelCreator","waitForAnswerPromise","response","close","return","getMessageReturn","parse","storage","internals","changes$","subs","subscribe","next","_proto2","requestRemote","methodName","responsePromise","message","bulkWrite","documentWrites","context","findDocumentsById","ids","deleted","query","preparedQuery","count","getAttachmentData","documentId","attachmentId","digest","getChangedDocumentsSince","limit","checkpoint","changeStream","asObservable","cleanup","minDeletedTime","closed","forEach","sub","unsubscribe","complete","remove","getRxStorageRemote","withDefaults","Object","assign"],"sources":["../../../../src/plugins/storage-remote/rx-storage-remote.ts"],"sourcesContent":["import {\n firstValueFrom,\n filter,\n Observable,\n Subject,\n Subscription\n} from 'rxjs';\nimport type {\n BulkWriteRow,\n EventBulk,\n RxDocumentData,\n RxJsonSchema,\n RxStorage,\n RxStorageBulkWriteResponse,\n RxStorageChangeEvent,\n RxStorageCountResult,\n RxStorageInstance,\n RxStorageInstanceCreationParams,\n RxStorageQueryResult\n} from '../../types/index.d.ts';\nimport {\n RXDB_VERSION,\n randomToken\n} from '../../plugins/utils/index.ts';\nimport type {\n MessageFromRemote,\n MessageToRemote,\n RemoteMessageChannel,\n RxStorageRemoteInternals,\n RxStorageRemoteSettings\n} from './storage-remote-types.ts';\nimport { closeMessageChannel, getMessageChannel } from './message-channel-cache.ts';\n\n\nexport class RxStorageRemote implements RxStorage {\n public readonly name: string = 'remote';\n public readonly rxdbVersion = RXDB_VERSION;\n\n private seed: string = randomToken(10);\n private lastRequestId: number = 0;\n public messageChannelIfOneMode?: Promise;\n constructor(\n public readonly settings: RxStorageRemoteSettings\n ) {\n if (settings.mode === 'one') {\n this.messageChannelIfOneMode = getMessageChannel(\n settings,\n [],\n true\n );\n }\n }\n\n public getRequestId() {\n const newId = this.lastRequestId++;\n return this.seed + '|' + newId;\n }\n\n async createStorageInstance(\n params: RxStorageInstanceCreationParams\n ): Promise> {\n const connectionId = 'c|' + this.getRequestId();\n\n const cacheKeys: string[] = [\n 'mode-' + this.settings.mode\n ];\n switch (this.settings.mode) {\n case 'collection':\n cacheKeys.push('collection-' + params.collectionName);\n // eslint-disable-next-line no-fallthrough\n case 'database':\n cacheKeys.push('database-' + params.databaseName);\n // eslint-disable-next-line no-fallthrough\n case 'storage':\n cacheKeys.push('seed-' + this.seed);\n }\n const messageChannel = await (this.messageChannelIfOneMode ?\n this.messageChannelIfOneMode :\n getMessageChannel(\n this.settings,\n cacheKeys\n )\n );\n\n const requestId = this.getRequestId();\n const waitForOkPromise = firstValueFrom(messageChannel.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n messageChannel.send({\n connectionId,\n method: 'create',\n version: RXDB_VERSION,\n requestId,\n params\n });\n\n const waitForOkResult = await waitForOkPromise;\n if (waitForOkResult.error) {\n await closeMessageChannel(messageChannel);\n throw new Error('could not create instance ' + JSON.stringify(waitForOkResult.error));\n }\n\n return new RxStorageInstanceRemote(\n this,\n params.databaseName,\n params.collectionName,\n params.schema,\n {\n params,\n connectionId,\n messageChannel\n },\n params.options\n );\n }\n\n async customRequest(data: In): Promise {\n const messageChannel = await this.settings.messageChannelCreator();\n const requestId = this.getRequestId();\n const connectionId = 'custom|request|' + requestId;\n const waitForAnswerPromise = firstValueFrom(messageChannel.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n ));\n messageChannel.send({\n connectionId,\n method: 'custom',\n version: RXDB_VERSION,\n requestId,\n params: data\n });\n const response = await waitForAnswerPromise;\n if (response.error) {\n await messageChannel.close();\n throw new Error('could not run customRequest(): ' + JSON.stringify({\n data,\n error: response.error\n }));\n } else {\n await messageChannel.close();\n return response.return;\n }\n\n }\n}\n\n/**\n * Because postMessage() can be very slow on complex objects,\n * and some RxStorage implementations do need a JSON-string internally\n * anyway, it is allowed to transfer a string instead of an object\n * which must then be JSON.parse()-ed before RxDB can use it.\n * @link https://surma.dev/things/is-postmessage-slow/\n */\nfunction getMessageReturn(\n msg: MessageFromRemote\n) {\n if (msg.method === 'getAttachmentData') {\n return msg.return;\n } else {\n if (typeof msg.return === 'string') {\n return JSON.parse(msg.return);\n } else {\n return msg.return;\n }\n }\n}\n\nexport class RxStorageInstanceRemote implements RxStorageInstance {\n private changes$: Subject>, any>> = new Subject();\n private subs: Subscription[] = [];\n\n private closed?: Promise;\n messages$: Observable;\n\n constructor(\n public readonly storage: RxStorageRemote,\n public readonly databaseName: string,\n public readonly collectionName: string,\n public readonly schema: Readonly>>,\n public readonly internals: RxStorageRemoteInternals,\n public readonly options: Readonly\n ) {\n this.messages$ = this.internals.messageChannel.messages$.pipe(\n filter(msg => msg.connectionId === this.internals.connectionId)\n );\n this.subs.push(\n this.messages$.subscribe(msg => {\n if (msg.method === 'changeStream') {\n this.changes$.next(getMessageReturn(msg));\n }\n })\n );\n }\n\n private async requestRemote(\n methodName: keyof RxStorageInstance,\n params: any\n ) {\n const requestId = this.storage.getRequestId();\n const responsePromise = firstValueFrom(\n this.messages$.pipe(\n filter(msg => msg.answerTo === requestId)\n )\n );\n const message: MessageToRemote = {\n connectionId: this.internals.connectionId,\n requestId,\n version: RXDB_VERSION,\n method: methodName,\n params\n };\n this.internals.messageChannel.send(message);\n const response = await responsePromise;\n if (response.error) {\n throw new Error('could not requestRemote: ' + JSON.stringify({\n methodName,\n params,\n error: response.error\n }, null, 4));\n } else {\n return getMessageReturn(response);\n }\n }\n bulkWrite(\n documentWrites: BulkWriteRow[],\n context: string\n ): Promise> {\n return this.requestRemote('bulkWrite', [documentWrites, context]);\n }\n findDocumentsById(ids: string[], deleted: boolean): Promise[]> {\n return this.requestRemote('findDocumentsById', [ids, deleted]);\n }\n query(preparedQuery: any): Promise> {\n return this.requestRemote('query', [preparedQuery]);\n }\n count(preparedQuery: any): Promise {\n return this.requestRemote('count', [preparedQuery]);\n }\n getAttachmentData(documentId: string, attachmentId: string, digest: string): Promise {\n return this.requestRemote('getAttachmentData', [documentId, attachmentId, digest]);\n }\n getChangedDocumentsSince(\n limit: number,\n checkpoint?: any\n ): Promise<\n {\n documents: RxDocumentData[];\n checkpoint: any;\n }> {\n return this.requestRemote('getChangedDocumentsSince', [limit, checkpoint]);\n }\n changeStream(): Observable>, any>> {\n return this.changes$.asObservable();\n }\n cleanup(minDeletedTime: number): Promise {\n return this.requestRemote('cleanup', [minDeletedTime]);\n }\n async close(): Promise {\n if (this.closed) {\n return this.closed;\n }\n this.closed = (async () => {\n this.subs.forEach(sub => sub.unsubscribe());\n this.changes$.complete();\n await this.requestRemote('close', []);\n await closeMessageChannel(this.internals.messageChannel);\n })();\n return this.closed;\n }\n async remove(): Promise {\n if (this.closed) {\n throw new Error('already closed');\n }\n this.closed = (async () => {\n await this.requestRemote('remove', []);\n await closeMessageChannel(this.internals.messageChannel);\n })();\n return this.closed;\n }\n}\n\nexport function getRxStorageRemote(settings: RxStorageRemoteSettings): RxStorageRemote {\n const withDefaults = Object.assign({\n mode: 'storage'\n }, settings);\n return new RxStorageRemote(withDefaults);\n}\n"],"mappings":"AAAA,SACIA,cAAc,EACdC,MAAM,EAENC,OAAO,QAEJ,MAAM;AAcb,SACIC,YAAY,EACZC,WAAW,QACR,8BAA8B;AAQrC,SAASC,mBAAmB,EAAEC,iBAAiB,QAAQ,4BAA4B;AAGnF,WAAaC,eAAe;EAOxB,SAAAA,gBACoBC,QAAiC,EACnD;IAAA,KARcC,IAAI,GAAW,QAAQ;IAAA,KACvBC,WAAW,GAAGP,YAAY;IAAA,KAElCQ,IAAI,GAAWP,WAAW,CAAC,EAAE,CAAC;IAAA,KAC9BQ,aAAa,GAAW,CAAC;IAAA,KAGbJ,QAAiC,GAAjCA,QAAiC;IAEjD,IAAIA,QAAQ,CAACK,IAAI,KAA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MAAM,CAAC;IAC/BhF,IAAI,EAAE;EACV,CAAC,EAAEL,QAAQ,CAAC;EACZ,OAAO,IAAID,eAAe,CAACoF,YAAY,CAAC;AAC5C","ignoreList":[]} \ No newline at end of file diff --git a/dist/esm/plugins/storage-remote/storage-remote-types.js.map b/dist/esm/plugins/storage-remote/storage-remote-types.js.map index c14574b1815..7176174521b 100644 --- a/dist/esm/plugins/storage-remote/storage-remote-types.js.map +++ b/dist/esm/plugins/storage-remote/storage-remote-types.js.map @@ -1 +1 @@ -{"version":3,"file":"storage-remote-types.js","names":[],"sources":["../../../../src/plugins/storage-remote/storage-remote-types.ts"],"sourcesContent":["import type { Observable } from 'rxjs';\nimport type {\n MaybePromise,\n PlainJsonError,\n RxDatabase,\n RxStorage,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types/index.d.ts';\n\n\n\nexport type MessageFromRemote = {\n connectionId: string;\n answerTo: string; // id of the request\n method: keyof RxStorageInstance | 'create' | 'custom';\n error?: PlainJsonError;\n return?: any | string;\n};\n\nexport type MessageToRemote = {\n connectionId: string;\n /**\n * Unique ID of the request\n */\n requestId: string;\n method: keyof RxStorageInstance | 'create' | 'custom';\n params:\n RxStorageInstanceCreationParams | // used in the create call\n any[] | // used to call RxStorageInstance methods\n any; // used in custom requests\n};\n\n\n/**\n * A message channel represents a single\n * channel that is able to communicate with the remote.\n * For example a single websocket connection or WebWorker instance.\n * The storage must be able to open and close MessageChannels\n * according to the modes settings.\n */\nexport type RemoteMessageChannel = {\n send(msg: MessageToRemote): void;\n messages$: Observable;\n close(): Promise;\n};\n\nexport type RxStorageRemoteSettings = {\n identifier: string;\n /**\n * There are different modes\n * that determine how many message channels are used.\n * These modes can have different performance patterns.\n *\n * [default='storage']\n */\n mode?:\n // create exactly one RemoteMessageChannel and reuse that everywhere.\n | 'one'\n // storage: create one RemoteMessageChannel per call to getRxStorage...()\n | 'storage'\n // database: create one RemoteMessageChannel for each database\n | 'database'\n // collection: create one RemoteMessageChannel for each collection\n | 'collection';\n messageChannelCreator: () => Promise;\n};\n\nexport type RxStorageRemoteInternals = {\n params: RxStorageInstanceCreationParams;\n connectionId: string;\n messageChannel: RemoteMessageChannel;\n};\n\nexport type RxStorageRemoteExposeSettingsBase = {\n send(msg: MessageFromRemote): void;\n messages$: Observable;\n customRequestHandler?: CustomRequestHandler;\n};\n\nexport type RxStorageRemoteExposeSettingsRxDatabase = RxStorageRemoteExposeSettingsBase & {\n /**\n * The database which must be mapped to the remote storage server.\n */\n database: RxDatabase;\n};\n\nexport type RxStorageRemoteExposeSettingsRxStorage = RxStorageRemoteExposeSettingsBase & {\n /**\n * The original storage\n * which actually stores the data.\n */\n storage: RxStorage;\n};\n\nexport type RxStorageRemoteExposeSettings = RxStorageRemoteExposeSettingsRxDatabase | RxStorageRemoteExposeSettingsRxStorage;\n\nexport type RxStorageRemoteExposeType = {\n instanceByFullName: Map;\n};\n\n/**\n * If set, the clients can send RxDB-unrelated custom messages\n * to the remote storage and it will answer them.\n */\nexport type CustomRequestHandler = (data: In) => MaybePromise;\n"],"mappings":"","ignoreList":[]} \ No newline at end of file +{"version":3,"file":"storage-remote-types.js","names":[],"sources":["../../../../src/plugins/storage-remote/storage-remote-types.ts"],"sourcesContent":["import type { Observable } from 'rxjs';\nimport type {\n MaybePromise,\n PlainJsonError,\n RxDatabase,\n RxStorage,\n RxStorageInstance,\n RxStorageInstanceCreationParams\n} from '../../types/index.d.ts';\n\n\n\nexport type MessageFromRemote = {\n connectionId: string;\n answerTo: string; // id of the request\n method: keyof RxStorageInstance | 'create' | 'custom';\n error?: PlainJsonError;\n return?: any | string;\n};\n\nexport type MessageToRemote = {\n connectionId: string;\n /**\n * Unique ID of the request\n */\n requestId: string;\n method: keyof RxStorageInstance | 'create' | 'custom';\n /**\n * We send the RxDB version to the remote\n * to ensure we are communicating with an RxDB instance\n * of the same version. This is to prevent bugs\n * when people forget to rebuild their workers.\n */\n version: string;\n params:\n RxStorageInstanceCreationParams | // used in the create call\n any[] | // used to call RxStorageInstance methods\n any; // used in custom requests\n};\n\n\n/**\n * A message channel represents a single\n * channel that is able to communicate with the remote.\n * For example a single websocket connection or WebWorker instance.\n * The storage must be able to open and close MessageChannels\n * according to the modes settings.\n */\nexport type RemoteMessageChannel = {\n send(msg: MessageToRemote): void;\n messages$: Observable;\n close(): Promise;\n};\n\nexport type RxStorageRemoteSettings = {\n identifier: string;\n /**\n * There are different modes\n * that determine how many message channels are used.\n * These modes can have different performance patterns.\n *\n * [default='storage']\n */\n mode?:\n // create exactly one RemoteMessageChannel and reuse that everywhere.\n | 'one'\n // storage: create one RemoteMessageChannel per call to getRxStorage...()\n | 'storage'\n // database: create one RemoteMessageChannel for each database\n | 'database'\n // collection: create one RemoteMessageChannel for each collection\n | 'collection';\n messageChannelCreator: () => Promise;\n};\n\nexport type RxStorageRemoteInternals = {\n params: RxStorageInstanceCreationParams;\n connectionId: string;\n messageChannel: RemoteMessageChannel;\n};\n\nexport type RxStorageRemoteExposeSettingsBase = {\n send(msg: MessageFromRemote): void;\n messages$: Observable;\n customRequestHandler?: CustomRequestHandler;\n /**\n * Used in tests to simulate what happens if the remote\n * was build on a different RxDB version.\n */\n fakeVersion?: string;\n};\n\nexport type RxStorageRemoteExposeSettingsRxDatabase = RxStorageRemoteExposeSettingsBase & {\n /**\n * The database which must be mapped to the remote storage server.\n */\n database: RxDatabase;\n};\n\nexport type RxStorageRemoteExposeSettingsRxStorage = RxStorageRemoteExposeSettingsBase & {\n /**\n * The original storage\n * which actually stores the data.\n */\n storage: RxStorage;\n};\n\nexport type RxStorageRemoteExposeSettings = RxStorageRemoteExposeSettingsRxDatabase | RxStorageRemoteExposeSettingsRxStorage;\n\nexport type RxStorageRemoteExposeType = {\n instanceByFullName: Map;\n};\n\n/**\n * If set, the clients can send RxDB-unrelated custom messages\n * to the remote storage and it will answer them.\n */\nexport type CustomRequestHandler = (data: In) => MaybePromise;\n"],"mappings":"","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 305fefb366c..250251cf5ed 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.8'; +export var RXDB_VERSION = '16.0.0-beta.9'; //# 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 cdb2d4a1abf..31c588592c0 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.8';\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.9';\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAO,IAAMA,YAAY,GAAG,eAAe","ignoreList":[]} \ No newline at end of file diff --git a/dist/types/plugins/dev-mode/error-messages.d.ts b/dist/types/plugins/dev-mode/error-messages.d.ts index f1d6b456ee6..7d9fd36eb76 100644 --- a/dist/types/plugins/dev-mode/error-messages.d.ts +++ b/dist/types/plugins/dev-mode/error-messages.d.ts @@ -177,6 +177,7 @@ export declare const ERROR_MESSAGES: { CRDT2: string; CRDT3: string; DXE1: string; + RM1: string; /** * Should never be thrown, use this for * null checks etc. so you do not have to increase the diff --git a/dist/types/plugins/replication/replication-helper.d.ts b/dist/types/plugins/replication/replication-helper.d.ts index 9781c5ab004..e53480ce1ff 100644 --- a/dist/types/plugins/replication/replication-helper.d.ts +++ b/dist/types/plugins/replication/replication-helper.d.ts @@ -1,4 +1,5 @@ import type { RxCollection, WithDeleted } from '../../types/index.d.ts'; +import type { RxReplicationState } from './index.ts'; export declare const DEFAULT_MODIFIER: (d: any) => Promise; export declare function swapDefaultDeletedTodeletedField(deletedField: string, doc: WithDeleted): RxDocType; /** @@ -12,3 +13,11 @@ export declare function handlePulledDocuments(collection: RxCollectio * but will skip the wait time if the online-state changes. */ export declare function awaitRetry(collection: RxCollection, retryTime: number): Promise; +/** + * When a replication is running and the leading tab get hibernated + * by the browser, the replication will be stuck. + * To prevent this, we fire a mouseeven each X seconds while the replication is not canceled. + * + * If you find a better way to prevent hibernation, please make a pull request. + */ +export declare function preventHibernateBrowserTab(replicationState: RxReplicationState): void; diff --git a/dist/types/plugins/storage-denokv/index.d.ts b/dist/types/plugins/storage-denokv/index.d.ts index 15cb316dc52..227fb177f8d 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.8"; + readonly rxdbVersion = "16.0.0-beta.9"; 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 26220678d95..5f45366bf09 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.8"; + readonly rxdbVersion = "16.0.0-beta.9"; 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 1c98bb33095..04706f0386b 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.8"; + readonly rxdbVersion = "16.0.0-beta.9"; constructor(databaseSettings: MongoDBDatabaseSettings); createStorageInstance(params: RxStorageInstanceCreationParams): Promise>; } diff --git a/dist/types/plugins/storage-remote-websocket/types.d.ts b/dist/types/plugins/storage-remote-websocket/types.d.ts index 794d2dccec7..da707eee394 100644 --- a/dist/types/plugins/storage-remote-websocket/types.d.ts +++ b/dist/types/plugins/storage-remote-websocket/types.d.ts @@ -7,6 +7,11 @@ export type RxStorageRemoteWebsocketServerOptions = ServerOptions & { storage?: RxStorage; database?: RxDatabase; customRequestHandler?: CustomRequestHandler; + /** + * Used in tests to simulate what happens if the remote + * was build on a different RxDB version. + */ + fakeVersion?: string; }; export type RxStorageRemoteWebsocketServerState = { serverState: WebsocketServerState; 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 72759adb559..5b422995db7 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.8"; + readonly rxdbVersion = "16.0.0-beta.9"; private seed; private lastRequestId; messageChannelIfOneMode?: Promise; diff --git a/dist/types/plugins/storage-remote/storage-remote-types.d.ts b/dist/types/plugins/storage-remote/storage-remote-types.d.ts index 8c5cf94e022..7adb5ca85a1 100644 --- a/dist/types/plugins/storage-remote/storage-remote-types.d.ts +++ b/dist/types/plugins/storage-remote/storage-remote-types.d.ts @@ -14,6 +14,13 @@ export type MessageToRemote = { */ requestId: string; method: keyof RxStorageInstance | 'create' | 'custom'; + /** + * We send the RxDB version to the remote + * to ensure we are communicating with an RxDB instance + * of the same version. This is to prevent bugs + * when people forget to rebuild their workers. + */ + version: string; params: RxStorageInstanceCreationParams | // used in the create call any[] | // used to call RxStorageInstance methods any; @@ -51,6 +58,11 @@ export type RxStorageRemoteExposeSettingsBase = { send(msg: MessageFromRemote): void; messages$: Observable; customRequestHandler?: CustomRequestHandler; + /** + * Used in tests to simulate what happens if the remote + * was build on a different RxDB version. + */ + fakeVersion?: string; }; export type RxStorageRemoteExposeSettingsRxDatabase = RxStorageRemoteExposeSettingsBase & { /** diff --git a/dist/types/plugins/utils/utils-rxdb-version.d.ts b/dist/types/plugins/utils/utils-rxdb-version.d.ts index 927fa1f3357..f04d37383f9 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.8"; +export declare const RXDB_VERSION = "16.0.0-beta.9"; diff --git a/dist/types/rx-database.d.ts b/dist/types/rx-database.d.ts index c58d5d383c1..30a7b0fc3d4 100644 --- a/dist/types/rx-database.d.ts +++ b/dist/types/rx-database.d.ts @@ -29,7 +29,7 @@ export declare class RxDatabaseBase | undefined; readonly idleQueue: IdleQueue; - readonly rxdbVersion = "16.0.0-beta.8"; + readonly rxdbVersion = "16.0.0-beta.9"; /** * Contains all known non-closed storage instances * that belong to this database. diff --git a/package.json b/package.json index cc3ac97144f..4cb7ff87165 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.8", + "version": "16.0.0-beta.9", "author": "pubkey", "repository": { "type": "git", diff --git a/src/plugins/utils/utils-rxdb-version.ts b/src/plugins/utils/utils-rxdb-version.ts index ea0a7730174..b0ffdd01bd1 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.8'; +export const RXDB_VERSION = '16.0.0-beta.9';