@signaldb/sync 2.0.0-beta.4 → 2.0.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/SyncManager.d.ts +2 -1
- package/dist/index.mjs +0 -6
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +2 -2
package/dist/SyncManager.d.ts
CHANGED
|
@@ -153,7 +153,8 @@ export default class SyncManager<CollectionOptions extends Record<string, any>,
|
|
|
153
153
|
* @param [async] If true, it will check for active syncs in the database. This is useful if you have multiple instances of the application running.
|
|
154
154
|
* @returns True if the collection is currently beeing synced, false otherwise. If async is true, it will return a promise that resolves to true or false.
|
|
155
155
|
*/
|
|
156
|
-
isSyncing
|
|
156
|
+
isSyncing(name: string | undefined, async: true): Promise<boolean>;
|
|
157
|
+
isSyncing(name?: string, async?: false): boolean;
|
|
157
158
|
/**
|
|
158
159
|
* Checks if the sync manager is ready to sync.
|
|
159
160
|
* @returns A promise that resolves when the sync manager is ready to sync.
|
package/dist/index.mjs
CHANGED
|
@@ -382,12 +382,6 @@ ${e.map((t) => `${t.id}: ${t.error.message}`).join(`
|
|
|
382
382
|
|
|
383
383
|
`)}`);
|
|
384
384
|
}
|
|
385
|
-
/**
|
|
386
|
-
* Checks if a collection is currently beeing synced
|
|
387
|
-
* @param [name] Name of the collection. If not provided, it will check if any collection is currently beeing synced.
|
|
388
|
-
* @param [async] If true, it will check for active syncs in the database. This is useful if you have multiple instances of the application running.
|
|
389
|
-
* @returns True if the collection is currently beeing synced, false otherwise. If async is true, it will return a promise that resolves to true or false.
|
|
390
|
-
*/
|
|
391
385
|
isSyncing(e, t) {
|
|
392
386
|
const s = this.syncOperations.findOne({
|
|
393
387
|
...e ? { collectionName: e } : {},
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/utils/debounce.ts","../src/utils/PromiseQueue.ts","../src/computeChanges.ts","../src/getSnapshot.ts","../src/applyChanges.ts","../src/sync.ts","../src/SyncManager.ts"],"sourcesContent":["/**\n * Debounces a function.\n * @param fn Function to debounce\n * @param wait Time to wait before calling the function.\n * @param [options] Debounce options\n * @param [options.leading] Whether to call the function on the leading edge of the wait interval.\n * @param [options.trailing] Whether to call the function on the trailing edge of the wait interval.\n * @returns The debounced function.\n */\nexport default function debounce(fn, wait, options = {}) {\n let timeout;\n let result;\n const { leading = false, trailing = true } = options;\n /**\n * The debounced function that will be returned.\n * @param this The context to bind the function to.\n * @param args The arguments to pass to the function.\n * @returns The result of the debounced function.\n */\n function debounced(...args) {\n const shouldCallImmediately = leading && !timeout;\n const shouldCallTrailing = trailing && !timeout;\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n timeout = null;\n if (trailing && !shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n }, wait);\n if (shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n else if (!shouldCallTrailing) {\n result = null;\n }\n return result;\n }\n return debounced;\n}\n","/**\n * Class for queuing promises to be executed one after the other.\n * This is useful for tasks that should not be executed in parallel.\n * @example\n * const queue = new PromiseQueue();\n * queue.add(() => fetch('https://example.com/api/endpoint1'));\n * queue.add(() => fetch('https://example.com/api/endpoint2'));\n * // The second fetch will only be executed after the first one is done.\n */\nexport default class PromiseQueue {\n queue = [];\n pendingPromise = false;\n /**\n * Method to add a new promise to the queue and returns a promise that resolves when this task is done\n * @param task Function that returns a promise that will be added to the queue\n * @returns Promise that resolves when the task is done\n */\n add(task) {\n return new Promise((resolve, reject) => {\n // Wrap the task with the resolve and reject to control its completion from the outside\n this.queue.push(() => task()\n .then(resolve)\n .catch((error) => {\n reject(error);\n throw error;\n }));\n this.dequeue();\n });\n }\n /**\n * Method to check if there is a pending promise in the queue\n * @returns True if there is a pending promise, false otherwise\n */\n hasPendingPromise() {\n return this.pendingPromise;\n }\n /**\n * Method to process the queue\n */\n dequeue() {\n if (this.pendingPromise || this.queue.length === 0) {\n return;\n }\n const task = this.queue.shift();\n if (!task)\n return;\n this.pendingPromise = true;\n task()\n .then(() => {\n this.pendingPromise = false;\n this.dequeue();\n })\n .catch(() => {\n this.pendingPromise = false;\n this.dequeue();\n });\n }\n}\n","import { isEqual } from '@signaldb/core';\n/**\n * Computes the modified fields between two items recursively.\n * @param oldItem The old item\n * @param newItem The new item\n * @returns The modified fields\n */\nexport function computeModifiedFields(oldItem, newItem) {\n const modifiedFields = [];\n const oldKeys = Object.keys(oldItem);\n const newKeys = Object.keys(newItem);\n const allKeys = new Set([...oldKeys, ...newKeys]);\n for (const key of allKeys) {\n if (newItem[key] !== oldItem[key]) {\n if (typeof newItem[key] === 'object' && typeof oldItem[key] === 'object' && newItem[key] != null && oldItem[key] != null) {\n const nestedModifiedFields = computeModifiedFields(oldItem[key], newItem[key]);\n for (const nestedField of nestedModifiedFields) {\n modifiedFields.push(`${key}.${nestedField}`);\n }\n }\n else {\n modifiedFields.push(key);\n }\n }\n }\n return modifiedFields;\n}\n/**\n * Compute changes between two arrays of items.\n * @param oldItems Array of the old items\n * @param newItems Array of the new items\n * @returns The changeset\n */\nexport default function computeChanges(oldItems, newItems) {\n const added = [];\n const modified = [];\n const modifiedFields = new Map();\n const removed = [];\n const oldItemsMap = new Map(oldItems.map(item => [item.id, item]));\n const newItemsMap = new Map(newItems.map(item => [item.id, item]));\n for (const [id, oldItem] of oldItemsMap) {\n const newItem = newItemsMap.get(id);\n if (!newItem) {\n removed.push(oldItem);\n }\n else if (!isEqual(newItem, oldItem)) {\n modifiedFields.set(newItem.id, computeModifiedFields(oldItem, newItem));\n modified.push(newItem);\n }\n }\n for (const [id, newItem] of newItemsMap) {\n if (!oldItemsMap.has(id)) {\n added.push(newItem);\n }\n }\n return {\n added,\n modified,\n modifiedFields,\n removed,\n };\n}\n","/**\n * Gets the snapshot of items from the last snapshot and the changes.\n * @param lastSnapshot The last snapshot of items\n * @param data The changes to apply to the last snapshot\n * @returns The new snapshot of items\n */\nexport default function getSnapshot(lastSnapshot, data) {\n if (data.items != null)\n return data.items;\n const items = lastSnapshot || [];\n data.changes.added.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.modified.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.removed.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index !== -1)\n items.splice(index, 1);\n });\n return items;\n}\n","import { modify } from '@signaldb/core';\n/**\n * applies changes to a collection of items\n * @param items The items to apply the changes to\n * @param changes The changes to apply to the items\n * @returns The new items after applying the changes\n */\nexport default function applyChanges(items, changes) {\n // Create initial map of items by ID\n const itemMap = new Map(items.map(item => [item.id, item]));\n changes.forEach((change) => {\n if (change.type === 'remove') {\n itemMap.delete(change.data);\n }\n else if (change.type === 'insert') {\n const existingItem = itemMap.get(change.data.id);\n itemMap.set(change.data.id, existingItem ? { ...existingItem, ...change.data } : change.data);\n }\n else { // change.type === 'update'\n const existingItem = itemMap.get(change.data.id);\n itemMap.set(change.data.id, existingItem\n ? modify(existingItem, change.data.modifier)\n : modify({ id: change.data.id }, change.data.modifier));\n }\n });\n // Convert map back to array\n return [...itemMap.values()];\n}\n","import computeChanges from './computeChanges';\nimport getSnapshot from './getSnapshot';\nimport applyChanges from './applyChanges';\n/**\n * Checks if there are any changes in the given changeset.\n * @param changes The changeset to check.\n * @returns True if there are changes, false otherwise.\n */\nfunction hasChanges(changes) {\n return changes.added.length > 0\n || changes.modified.length > 0\n || changes.removed.length > 0;\n}\n/**\n * Checks if there is a difference between the old items and the new items.\n * @param oldItems The old items.\n * @param newItems The new items.\n * @returns True if there is a difference, false otherwise.\n */\nfunction hasDifference(oldItems, newItems) {\n return hasChanges(computeChanges(oldItems, newItems));\n}\n/**\n * Does a sync operation based on the provided options. If changes are supplied, these will be rebased on the new data.\n * Afterwards the push method will be called with the remaining changes. A new snapshot will be created and returned.\n * @param options Sync options\n * @param options.changes Changes to call the push method with\n * @param [options.lastSnapshot] The last snapshot\n * @param options.data The new data\n * @param options.pull Method to pull new data\n * @param options.push Method to push changes\n * @param options.insert Method to insert an item\n * @param options.update Method to update an item\n * @param options.remove Method to remove an item\n * @param options.batch Method to batch multiple operations\n * @returns The new snapshot\n */\nexport default async function sync({ changes, lastSnapshot, data, pull, push, insert, update, remove, batch, }) {\n let newData = data;\n let previousSnapshot = lastSnapshot || [];\n let newSnapshot = getSnapshot(lastSnapshot, newData);\n if (changes.length > 0) {\n // apply changes on last snapshot and check if there is a difference\n const lastSnapshotWithChanges = applyChanges(previousSnapshot, changes);\n if (hasDifference(previousSnapshot, lastSnapshotWithChanges)) {\n // if yes, apply the changes on the newSnapshot and check if there is a difference\n const newSnapshotWithChanges = applyChanges(newSnapshot, changes);\n const changesToPush = computeChanges(newSnapshot, newSnapshotWithChanges);\n if (hasChanges(changesToPush)) {\n // if yes, push the changes to the server\n await push(changesToPush);\n // pull new data afterwards to ensure that all server changes are applied\n newData = await pull();\n newSnapshot = getSnapshot(newSnapshot, newData);\n }\n previousSnapshot = lastSnapshotWithChanges;\n }\n }\n // apply the new changes on the collection\n const newChanges = newData.changes == null\n ? computeChanges(previousSnapshot, newData.items)\n : newData.changes;\n await batch(async () => {\n await Promise.all(newChanges.added.map(item => insert(item)));\n await Promise.all(newChanges.modified.map(item => update(item.id, { $set: item })));\n await Promise.all(newChanges.removed.map(item => remove(item.id)));\n });\n return newSnapshot;\n}\n","import { DefaultDataAdapter, Collection, randomId } from '@signaldb/core';\nimport debounce from './utils/debounce';\nimport PromiseQueue from './utils/PromiseQueue';\nimport sync from './sync';\n/**\n * Class to manage syncing of collections.\n * @template CollectionOptions\n * @template ItemType\n * @template IdType\n * @example\n * const syncManager = new SyncManager({\n * pull: async (collectionOptions) => {\n * const response = await fetch(`/api/collections/${collectionOptions.name}`)\n * return await response.json()\n * },\n * push: async (collectionOptions, { changes }) => {\n * await fetch(`/api/collections/${collectionOptions.name}`, {\n * method: 'POST',\n * body: JSON.stringify(changes),\n * })\n * },\n * })\n *\n * const collection = new Collection()\n * syncManager.addCollection(collection, {\n * name: 'todos',\n * })\n *\n * syncManager.sync('todos')\n */\nexport default class SyncManager {\n options;\n collections = new Map();\n changes;\n snapshots;\n syncOperations;\n scheduledPushes = new Set();\n remoteChanges = [];\n syncQueues = new Map();\n collectionsReady;\n isDisposed = false;\n instanceId = randomId();\n id;\n debouncedFlush;\n /**\n * @param options Collection options\n * @param options.pull Function to pull data from remote source.\n * @param options.push Function to push data to remote source.\n * @param [options.registerRemoteChange] Function to register a callback for remote changes.\n * @param [options.id] Unique identifier for this sync manager. Only nessesary if you have multiple sync managers.\n * @param [options.storageAdapter] Storage adapter to use for storing changes, snapshots and sync operations.\n * @param [options.reactivity] Reactivity adapter to use for reactivity.\n * @param [options.onError] Function to handle errors that occur async during syncing.\n * @param [options.autostart] Whether to automatically start syncing new collections.\n * @param [options.debounceTime] The time in milliseconds to debounce push operations.\n */\n constructor(options) {\n this.options = {\n autostart: true,\n ...options,\n };\n this.id = this.options.id || 'default-sync-manager';\n const { reactivity } = this.options;\n const dataAdapter = this.options.dataAdapter ?? new DefaultDataAdapter();\n this.changes = new Collection(`${this.options.id}-changes`, dataAdapter, {\n indices: ['collectionName'],\n reactivity,\n });\n this.snapshots = new Collection(`${this.options.id}-snapshots`, dataAdapter, {\n indices: ['collectionName'],\n reactivity,\n });\n this.syncOperations = new Collection(`${this.options.id}-sync-operations`, dataAdapter, {\n indices: ['collectionName', 'status'],\n reactivity,\n });\n const readiness = [\n Promise.resolve(this.syncOperations.isReady()),\n Promise.resolve(this.changes.isReady()),\n Promise.resolve(this.snapshots.isReady()),\n ];\n this.collectionsReady = Promise.all(readiness).then(() => { });\n this.changes.setMaxListeners(1000);\n this.snapshots.setMaxListeners(1000);\n this.syncOperations.setMaxListeners(1000);\n this.debouncedFlush = debounce(this.flushScheduledPushes, this.options.debounceTime ?? 100);\n }\n getSyncQueue(name) {\n if (this.syncQueues.get(name) == null) {\n this.syncQueues.set(name, new PromiseQueue());\n }\n return this.syncQueues.get(name);\n }\n /**\n * Clears all internal data structures\n */\n async dispose() {\n this.collections.clear();\n this.syncQueues.clear();\n this.remoteChanges.splice(0);\n await Promise.all([\n this.changes.dispose(),\n this.snapshots.dispose(),\n this.syncOperations.dispose(),\n ]);\n this.isDisposed = true;\n }\n /**\n * Gets a collection with it's options by name\n * @deprecated Use getCollectionProperties instead.\n * @param name Name of the collection\n * @throws {Error} Will throw an error if the name wasn't found\n * @returns Tuple of collection and options\n */\n getCollection(name) {\n const { collection, options } = this.getCollectionProperties(name);\n return [collection, options];\n }\n /**\n * Gets collection options by name\n * @param name Name of the collection\n * @throws {Error} Will throw an error if the name wasn't found\n * @returns An object of all properties of the collection\n */\n getCollectionProperties(name) {\n const collectionParameters = this.collections.get(name);\n if (collectionParameters == null)\n throw new Error(`Collection with id '${name}' not found`);\n return collectionParameters;\n }\n /**\n * Adds a collection to the sync manager.\n * @param collection Collection to add\n * @param options Options for the collection. The object needs at least a `name` property.\n * @param options.name Unique name of the collection\n */\n addCollection(collection, options) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n this.collections.set(options.name, {\n collection: collection,\n options,\n readyPromise: collection.ready(),\n syncPaused: true, // always start paused as the autostart will start it\n });\n const hasRemoteChange = (change) => {\n for (const remoteChange of this.remoteChanges) {\n if (remoteChange == null)\n continue;\n if (remoteChange.collectionName !== change.collectionName)\n continue;\n if (remoteChange.type !== change.type)\n continue;\n if (change.type === 'remove' && remoteChange.data !== change.data)\n continue;\n if (remoteChange.data.id !== change.data.id)\n continue;\n return true;\n }\n return false;\n };\n const removeRemoteChanges = (collectionName, id) => {\n const newRemoteChanges = [...this.remoteChanges];\n for (let i = 0; i < newRemoteChanges.length; i += 1) {\n const item = newRemoteChanges[i];\n if (item == null)\n continue;\n if (item.collectionName !== collectionName)\n continue;\n if (item.type === 'remove' && item.data !== id)\n continue;\n if (item.data.id !== id)\n continue;\n newRemoteChanges[i] = null;\n }\n this.remoteChanges = newRemoteChanges.filter(item => item != null);\n };\n collection.on('added', (item) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'insert', data: item })) {\n removeRemoteChanges(options.name, item.id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'insert',\n data: item,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n collection.on('changed', ({ id }, modifier) => {\n const data = { id, modifier };\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'update', data })) {\n removeRemoteChanges(options.name, id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'update',\n data,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n collection.on('removed', ({ id }) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'remove', data: id })) {\n removeRemoteChanges(options.name, id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'remove',\n data: id,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n if (this.options.autostart) {\n this.startSync(options.name)\n .catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n }\n }\n flushScheduledPushes() {\n this.scheduledPushes.forEach((name) => {\n this.pushChanges(name).catch(() => { });\n });\n this.scheduledPushes.clear();\n }\n schedulePush(name) {\n this.scheduledPushes.add(name);\n this.debouncedFlush();\n }\n /**\n * Setup all collections to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n */\n async startAll() {\n await Promise.all([...this.collections.keys()].map(id => this.startSync(id)));\n }\n /**\n * Setup a collection to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n * @param name Name of the collection\n */\n async startSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (!collectionParameters.syncPaused)\n return; // already started\n this.schedulePush(name); // push changes that were made while paused\n const cleanupFunction = this.options.registerRemoteChange\n ? await this.options.registerRemoteChange(collectionParameters.options, async (data) => {\n await (data == null\n ? this.sync(name)\n : this.getSyncQueue(name).add(async () => {\n const syncTime = Date.now();\n const syncId = await this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n await this.syncWithData(name, data)\n .then(async () => {\n // clean up old sync operations\n await this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n })\n .catch(async (error) => {\n if (this.options.onError) {\n this.options.onError(this.getCollectionProperties(name).options, error);\n }\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n throw error;\n });\n }));\n })\n : undefined;\n this.collections.set(name, {\n ...collectionParameters,\n syncPaused: false,\n cleanupFunction,\n });\n }\n /**\n * Pauses the sync process for all collections.\n * This means that the collections will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n */\n async pauseAll() {\n await Promise.all([...this.collections.keys()].map(id => this.pauseSync(id)));\n }\n /**\n * Pauses the sync process for a collection.\n * This means that the collection will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n * @param name Name of the collection\n */\n async pauseSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (collectionParameters.syncPaused)\n return; // already paused\n if (collectionParameters.cleanupFunction)\n await collectionParameters.cleanupFunction();\n this.collections.set(name, {\n ...collectionParameters,\n cleanupFunction: undefined,\n syncPaused: true,\n });\n }\n /**\n * Starts the sync process for all collections\n */\n async syncAll() {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n const errors = [];\n await Promise.all([...this.collections.keys()].map(id => this.sync(id).catch((error) => {\n errors.push({ id, error });\n })));\n if (errors.length > 0)\n throw new Error(`Error while syncing collections:\\n${errors.map(error => `${error.id}: ${error.error.message}`).join('\\n\\n')}`);\n }\n /**\n * Checks if a collection is currently beeing synced\n * @param [name] Name of the collection. If not provided, it will check if any collection is currently beeing synced.\n * @param [async] If true, it will check for active syncs in the database. This is useful if you have multiple instances of the application running.\n * @returns True if the collection is currently beeing synced, false otherwise. If async is true, it will return a promise that resolves to true or false.\n */\n isSyncing(name, async) {\n const itemOrPromise = this.syncOperations.findOne({\n ...name ? { collectionName: name } : {},\n status: 'active',\n }, { fields: { status: 1 }, async });\n if (itemOrPromise instanceof Promise) {\n return itemOrPromise\n .then(item => item != null);\n }\n return (itemOrPromise != null);\n }\n /**\n * Checks if the sync manager is ready to sync.\n * @returns A promise that resolves when the sync manager is ready to sync.\n */\n async isReady() {\n await this.collectionsReady;\n }\n /**\n * Starts the sync process for a collection\n * @param name Name of the collection\n * @param options Options for the sync process.\n * @param options.force If true, the sync process will be started even if there are no changes and onlyWithChanges is true.\n * @param options.onlyWithChanges If true, the sync process will only be started if there are changes.\n */\n async sync(name, options = {}) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n await this.isReady();\n const { options: collectionOptions, readyPromise } = this.getCollectionProperties(name);\n await readyPromise;\n const hasActiveSyncs = await this.syncOperations.find({\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n }, {\n reactive: false,\n async: true,\n }).count() > 0;\n const syncTime = Date.now();\n let syncId = null;\n // schedule for next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const doSync = async () => {\n const lastFinishedSync = await this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n async: true,\n });\n if (options?.onlyWithChanges) {\n const currentChanges = await this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n async: true,\n }).count();\n if (currentChanges === 0)\n return;\n }\n if (!hasActiveSyncs) {\n syncId = await this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n }\n const data = await this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n });\n await this.syncWithData(name, data);\n };\n await (options?.force ? doSync() : this.getSyncQueue(name).add(doSync))\n .catch(async (error) => {\n if (syncId != null) {\n if (this.options.onError)\n this.options.onError(collectionOptions, error);\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n }\n throw error;\n });\n if (syncId != null) {\n // clean up old sync operations\n await this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n }\n }\n /**\n * Starts the push process for a collection (sync process but only if there are changes)\n * @param name Name of the collection\n */\n async pushChanges(name) {\n await this.sync(name, {\n onlyWithChanges: true,\n });\n }\n async syncWithData(name, data) {\n const { collection, options: collectionOptions } = this.getCollectionProperties(name);\n const syncTime = Date.now();\n const lastFinishedSync = await this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n async: true,\n });\n const lastSnapshot = await this.snapshots.findOne({\n collectionName: name,\n }, {\n sort: { time: -1 },\n reactive: false,\n async: true,\n });\n const currentChanges = await this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n async: true,\n }).fetch();\n await sync({\n changes: currentChanges,\n lastSnapshot: lastSnapshot?.items,\n data,\n pull: () => this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n }),\n push: changes => this.options.push(collectionOptions, {\n changes,\n rawChanges: currentChanges,\n }),\n insert: async (item) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n }, {\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // replace the item\n await collection.replaceOne({ id: item.id }, item, { upsert: true });\n },\n update: async (itemId, modifier) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: { id: itemId, ...modifier.$set },\n }, {\n collectionName: name,\n type: 'update',\n data: { id: itemId, modifier },\n });\n await collection.updateOne({ id: itemId }, {\n ...modifier,\n $setOnInsert: { id: itemId },\n }, { upsert: true });\n },\n remove: async (itemId) => {\n const itemExists = await collection.find({\n id: itemId,\n }, { reactive: false, async: true }).count() > 0;\n if (!itemExists)\n return;\n this.remoteChanges.push({\n collectionName: name,\n type: 'remove',\n data: itemId,\n });\n await collection.removeOne({ id: itemId });\n },\n batch: async (fn) => {\n return collection.batch(async () => {\n await fn();\n });\n },\n })\n .then(async (snapshot) => {\n // clean up old snapshots\n await this.snapshots.removeMany({\n collectionName: name,\n time: { $lte: syncTime },\n });\n // clean up processed changes\n await this.changes.removeMany({\n collectionName: name,\n id: { $in: currentChanges.map(c => c.id) },\n });\n // insert new snapshot\n await this.snapshots.insert({\n time: syncTime,\n collectionName: name,\n items: snapshot,\n });\n // delay sync operation update to next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const hasChanges = await this.changes.find({\n collectionName: name,\n }, { reactive: false, async: true }).count() > 0;\n if (hasChanges) {\n // check if there are unsynced changes to push\n // and sync again if there are any\n await this.sync(name, {\n force: true,\n onlyWithChanges: true,\n });\n return;\n }\n // if there are no unsynced changes apply the last snapshot\n // to make sure that collection and snapshot are in sync\n // find all items that are not in the snapshot\n const nonExistingItemIds = await collection.find({\n id: { $nin: snapshot.map(item => item.id) },\n }, {\n reactive: false,\n async: true,\n }).map(item => item.id);\n await collection.batch(async () => {\n // update all items that are in the snapshot\n await Promise.all(snapshot.map(async (item) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n }, {\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // replace the item\n await collection.replaceOne({ id: item.id }, item, { upsert: true });\n }));\n // remove all items that are not in the snapshot\n await Promise.all(nonExistingItemIds.map(async (id) => {\n await collection.removeOne({ id });\n }));\n });\n });\n }\n}\n"],"names":["debounce","fn","wait","options","timeout","result","leading","trailing","debounced","args","shouldCallImmediately","shouldCallTrailing","PromiseQueue","task","resolve","reject","error","computeModifiedFields","oldItem","newItem","modifiedFields","oldKeys","newKeys","allKeys","key","nestedModifiedFields","nestedField","computeChanges","oldItems","newItems","added","modified","removed","oldItemsMap","item","newItemsMap","id","isEqual","getSnapshot","lastSnapshot","data","items","index","i","applyChanges","changes","itemMap","change","existingItem","modify","hasChanges","hasDifference","sync","pull","push","insert","update","remove","batch","newData","previousSnapshot","newSnapshot","lastSnapshotWithChanges","newSnapshotWithChanges","changesToPush","newChanges","SyncManager","randomId","reactivity","dataAdapter","DefaultDataAdapter","Collection","readiness","name","collection","collectionParameters","hasRemoteChange","remoteChange","removeRemoteChanges","collectionName","newRemoteChanges","modifier","cleanupFunction","syncTime","syncId","errors","async","itemOrPromise","collectionOptions","readyPromise","hasActiveSyncs","doSync","lastFinishedSync","currentChanges","itemId","snapshot","c","nonExistingItemIds"],"mappings":";AASA,SAAwBA,EAASC,GAAIC,GAAMC,IAAU,CAAA,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EAAmB,IAAI,OAAO7D,MAAO;AACnD,gBAAMsC,EAAW,UAAU,EAAE,IAAAtC,GAAI;AAAA,QACrC,CAAC,CAAC;AAAA,MACN,CAAC;AAAA,IACL,CAAC;AAAA,EACL;AACJ;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/utils/debounce.ts","../src/utils/PromiseQueue.ts","../src/computeChanges.ts","../src/getSnapshot.ts","../src/applyChanges.ts","../src/sync.ts","../src/SyncManager.ts"],"sourcesContent":["/**\n * Debounces a function.\n * @param fn Function to debounce\n * @param wait Time to wait before calling the function.\n * @param [options] Debounce options\n * @param [options.leading] Whether to call the function on the leading edge of the wait interval.\n * @param [options.trailing] Whether to call the function on the trailing edge of the wait interval.\n * @returns The debounced function.\n */\nexport default function debounce(fn, wait, options = {}) {\n let timeout;\n let result;\n const { leading = false, trailing = true } = options;\n /**\n * The debounced function that will be returned.\n * @param this The context to bind the function to.\n * @param args The arguments to pass to the function.\n * @returns The result of the debounced function.\n */\n function debounced(...args) {\n const shouldCallImmediately = leading && !timeout;\n const shouldCallTrailing = trailing && !timeout;\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n timeout = null;\n if (trailing && !shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n }, wait);\n if (shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n else if (!shouldCallTrailing) {\n result = null;\n }\n return result;\n }\n return debounced;\n}\n","/**\n * Class for queuing promises to be executed one after the other.\n * This is useful for tasks that should not be executed in parallel.\n * @example\n * const queue = new PromiseQueue();\n * queue.add(() => fetch('https://example.com/api/endpoint1'));\n * queue.add(() => fetch('https://example.com/api/endpoint2'));\n * // The second fetch will only be executed after the first one is done.\n */\nexport default class PromiseQueue {\n queue = [];\n pendingPromise = false;\n /**\n * Method to add a new promise to the queue and returns a promise that resolves when this task is done\n * @param task Function that returns a promise that will be added to the queue\n * @returns Promise that resolves when the task is done\n */\n add(task) {\n return new Promise((resolve, reject) => {\n // Wrap the task with the resolve and reject to control its completion from the outside\n this.queue.push(() => task()\n .then(resolve)\n .catch((error) => {\n reject(error);\n throw error;\n }));\n this.dequeue();\n });\n }\n /**\n * Method to check if there is a pending promise in the queue\n * @returns True if there is a pending promise, false otherwise\n */\n hasPendingPromise() {\n return this.pendingPromise;\n }\n /**\n * Method to process the queue\n */\n dequeue() {\n if (this.pendingPromise || this.queue.length === 0) {\n return;\n }\n const task = this.queue.shift();\n if (!task)\n return;\n this.pendingPromise = true;\n task()\n .then(() => {\n this.pendingPromise = false;\n this.dequeue();\n })\n .catch(() => {\n this.pendingPromise = false;\n this.dequeue();\n });\n }\n}\n","import { isEqual } from '@signaldb/core';\n/**\n * Computes the modified fields between two items recursively.\n * @param oldItem The old item\n * @param newItem The new item\n * @returns The modified fields\n */\nexport function computeModifiedFields(oldItem, newItem) {\n const modifiedFields = [];\n const oldKeys = Object.keys(oldItem);\n const newKeys = Object.keys(newItem);\n const allKeys = new Set([...oldKeys, ...newKeys]);\n for (const key of allKeys) {\n if (newItem[key] !== oldItem[key]) {\n if (typeof newItem[key] === 'object' && typeof oldItem[key] === 'object' && newItem[key] != null && oldItem[key] != null) {\n const nestedModifiedFields = computeModifiedFields(oldItem[key], newItem[key]);\n for (const nestedField of nestedModifiedFields) {\n modifiedFields.push(`${key}.${nestedField}`);\n }\n }\n else {\n modifiedFields.push(key);\n }\n }\n }\n return modifiedFields;\n}\n/**\n * Compute changes between two arrays of items.\n * @param oldItems Array of the old items\n * @param newItems Array of the new items\n * @returns The changeset\n */\nexport default function computeChanges(oldItems, newItems) {\n const added = [];\n const modified = [];\n const modifiedFields = new Map();\n const removed = [];\n const oldItemsMap = new Map(oldItems.map(item => [item.id, item]));\n const newItemsMap = new Map(newItems.map(item => [item.id, item]));\n for (const [id, oldItem] of oldItemsMap) {\n const newItem = newItemsMap.get(id);\n if (!newItem) {\n removed.push(oldItem);\n }\n else if (!isEqual(newItem, oldItem)) {\n modifiedFields.set(newItem.id, computeModifiedFields(oldItem, newItem));\n modified.push(newItem);\n }\n }\n for (const [id, newItem] of newItemsMap) {\n if (!oldItemsMap.has(id)) {\n added.push(newItem);\n }\n }\n return {\n added,\n modified,\n modifiedFields,\n removed,\n };\n}\n","/**\n * Gets the snapshot of items from the last snapshot and the changes.\n * @param lastSnapshot The last snapshot of items\n * @param data The changes to apply to the last snapshot\n * @returns The new snapshot of items\n */\nexport default function getSnapshot(lastSnapshot, data) {\n if (data.items != null)\n return data.items;\n const items = lastSnapshot || [];\n data.changes.added.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.modified.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.removed.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index !== -1)\n items.splice(index, 1);\n });\n return items;\n}\n","import { modify } from '@signaldb/core';\n/**\n * applies changes to a collection of items\n * @param items The items to apply the changes to\n * @param changes The changes to apply to the items\n * @returns The new items after applying the changes\n */\nexport default function applyChanges(items, changes) {\n // Create initial map of items by ID\n const itemMap = new Map(items.map(item => [item.id, item]));\n changes.forEach((change) => {\n if (change.type === 'remove') {\n itemMap.delete(change.data);\n }\n else if (change.type === 'insert') {\n const existingItem = itemMap.get(change.data.id);\n itemMap.set(change.data.id, existingItem ? { ...existingItem, ...change.data } : change.data);\n }\n else { // change.type === 'update'\n const existingItem = itemMap.get(change.data.id);\n itemMap.set(change.data.id, existingItem\n ? modify(existingItem, change.data.modifier)\n : modify({ id: change.data.id }, change.data.modifier));\n }\n });\n // Convert map back to array\n return [...itemMap.values()];\n}\n","import computeChanges from './computeChanges';\nimport getSnapshot from './getSnapshot';\nimport applyChanges from './applyChanges';\n/**\n * Checks if there are any changes in the given changeset.\n * @param changes The changeset to check.\n * @returns True if there are changes, false otherwise.\n */\nfunction hasChanges(changes) {\n return changes.added.length > 0\n || changes.modified.length > 0\n || changes.removed.length > 0;\n}\n/**\n * Checks if there is a difference between the old items and the new items.\n * @param oldItems The old items.\n * @param newItems The new items.\n * @returns True if there is a difference, false otherwise.\n */\nfunction hasDifference(oldItems, newItems) {\n return hasChanges(computeChanges(oldItems, newItems));\n}\n/**\n * Does a sync operation based on the provided options. If changes are supplied, these will be rebased on the new data.\n * Afterwards the push method will be called with the remaining changes. A new snapshot will be created and returned.\n * @param options Sync options\n * @param options.changes Changes to call the push method with\n * @param [options.lastSnapshot] The last snapshot\n * @param options.data The new data\n * @param options.pull Method to pull new data\n * @param options.push Method to push changes\n * @param options.insert Method to insert an item\n * @param options.update Method to update an item\n * @param options.remove Method to remove an item\n * @param options.batch Method to batch multiple operations\n * @returns The new snapshot\n */\nexport default async function sync({ changes, lastSnapshot, data, pull, push, insert, update, remove, batch, }) {\n let newData = data;\n let previousSnapshot = lastSnapshot || [];\n let newSnapshot = getSnapshot(lastSnapshot, newData);\n if (changes.length > 0) {\n // apply changes on last snapshot and check if there is a difference\n const lastSnapshotWithChanges = applyChanges(previousSnapshot, changes);\n if (hasDifference(previousSnapshot, lastSnapshotWithChanges)) {\n // if yes, apply the changes on the newSnapshot and check if there is a difference\n const newSnapshotWithChanges = applyChanges(newSnapshot, changes);\n const changesToPush = computeChanges(newSnapshot, newSnapshotWithChanges);\n if (hasChanges(changesToPush)) {\n // if yes, push the changes to the server\n await push(changesToPush);\n // pull new data afterwards to ensure that all server changes are applied\n newData = await pull();\n newSnapshot = getSnapshot(newSnapshot, newData);\n }\n previousSnapshot = lastSnapshotWithChanges;\n }\n }\n // apply the new changes on the collection\n const newChanges = newData.changes == null\n ? computeChanges(previousSnapshot, newData.items)\n : newData.changes;\n await batch(async () => {\n await Promise.all(newChanges.added.map(item => insert(item)));\n await Promise.all(newChanges.modified.map(item => update(item.id, { $set: item })));\n await Promise.all(newChanges.removed.map(item => remove(item.id)));\n });\n return newSnapshot;\n}\n","import { DefaultDataAdapter, Collection, randomId } from '@signaldb/core';\nimport debounce from './utils/debounce';\nimport PromiseQueue from './utils/PromiseQueue';\nimport sync from './sync';\n/**\n * Class to manage syncing of collections.\n * @template CollectionOptions\n * @template ItemType\n * @template IdType\n * @example\n * const syncManager = new SyncManager({\n * pull: async (collectionOptions) => {\n * const response = await fetch(`/api/collections/${collectionOptions.name}`)\n * return await response.json()\n * },\n * push: async (collectionOptions, { changes }) => {\n * await fetch(`/api/collections/${collectionOptions.name}`, {\n * method: 'POST',\n * body: JSON.stringify(changes),\n * })\n * },\n * })\n *\n * const collection = new Collection()\n * syncManager.addCollection(collection, {\n * name: 'todos',\n * })\n *\n * syncManager.sync('todos')\n */\nexport default class SyncManager {\n options;\n collections = new Map();\n changes;\n snapshots;\n syncOperations;\n scheduledPushes = new Set();\n remoteChanges = [];\n syncQueues = new Map();\n collectionsReady;\n isDisposed = false;\n instanceId = randomId();\n id;\n debouncedFlush;\n /**\n * @param options Collection options\n * @param options.pull Function to pull data from remote source.\n * @param options.push Function to push data to remote source.\n * @param [options.registerRemoteChange] Function to register a callback for remote changes.\n * @param [options.id] Unique identifier for this sync manager. Only nessesary if you have multiple sync managers.\n * @param [options.storageAdapter] Storage adapter to use for storing changes, snapshots and sync operations.\n * @param [options.reactivity] Reactivity adapter to use for reactivity.\n * @param [options.onError] Function to handle errors that occur async during syncing.\n * @param [options.autostart] Whether to automatically start syncing new collections.\n * @param [options.debounceTime] The time in milliseconds to debounce push operations.\n */\n constructor(options) {\n this.options = {\n autostart: true,\n ...options,\n };\n this.id = this.options.id || 'default-sync-manager';\n const { reactivity } = this.options;\n const dataAdapter = this.options.dataAdapter ?? new DefaultDataAdapter();\n this.changes = new Collection(`${this.options.id}-changes`, dataAdapter, {\n indices: ['collectionName'],\n reactivity,\n });\n this.snapshots = new Collection(`${this.options.id}-snapshots`, dataAdapter, {\n indices: ['collectionName'],\n reactivity,\n });\n this.syncOperations = new Collection(`${this.options.id}-sync-operations`, dataAdapter, {\n indices: ['collectionName', 'status'],\n reactivity,\n });\n const readiness = [\n Promise.resolve(this.syncOperations.isReady()),\n Promise.resolve(this.changes.isReady()),\n Promise.resolve(this.snapshots.isReady()),\n ];\n this.collectionsReady = Promise.all(readiness).then(() => { });\n this.changes.setMaxListeners(1000);\n this.snapshots.setMaxListeners(1000);\n this.syncOperations.setMaxListeners(1000);\n this.debouncedFlush = debounce(this.flushScheduledPushes, this.options.debounceTime ?? 100);\n }\n getSyncQueue(name) {\n if (this.syncQueues.get(name) == null) {\n this.syncQueues.set(name, new PromiseQueue());\n }\n return this.syncQueues.get(name);\n }\n /**\n * Clears all internal data structures\n */\n async dispose() {\n this.collections.clear();\n this.syncQueues.clear();\n this.remoteChanges.splice(0);\n await Promise.all([\n this.changes.dispose(),\n this.snapshots.dispose(),\n this.syncOperations.dispose(),\n ]);\n this.isDisposed = true;\n }\n /**\n * Gets a collection with it's options by name\n * @deprecated Use getCollectionProperties instead.\n * @param name Name of the collection\n * @throws {Error} Will throw an error if the name wasn't found\n * @returns Tuple of collection and options\n */\n getCollection(name) {\n const { collection, options } = this.getCollectionProperties(name);\n return [collection, options];\n }\n /**\n * Gets collection options by name\n * @param name Name of the collection\n * @throws {Error} Will throw an error if the name wasn't found\n * @returns An object of all properties of the collection\n */\n getCollectionProperties(name) {\n const collectionParameters = this.collections.get(name);\n if (collectionParameters == null)\n throw new Error(`Collection with id '${name}' not found`);\n return collectionParameters;\n }\n /**\n * Adds a collection to the sync manager.\n * @param collection Collection to add\n * @param options Options for the collection. The object needs at least a `name` property.\n * @param options.name Unique name of the collection\n */\n addCollection(collection, options) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n this.collections.set(options.name, {\n collection: collection,\n options,\n readyPromise: collection.ready(),\n syncPaused: true, // always start paused as the autostart will start it\n });\n const hasRemoteChange = (change) => {\n for (const remoteChange of this.remoteChanges) {\n if (remoteChange == null)\n continue;\n if (remoteChange.collectionName !== change.collectionName)\n continue;\n if (remoteChange.type !== change.type)\n continue;\n if (change.type === 'remove' && remoteChange.data !== change.data)\n continue;\n if (remoteChange.data.id !== change.data.id)\n continue;\n return true;\n }\n return false;\n };\n const removeRemoteChanges = (collectionName, id) => {\n const newRemoteChanges = [...this.remoteChanges];\n for (let i = 0; i < newRemoteChanges.length; i += 1) {\n const item = newRemoteChanges[i];\n if (item == null)\n continue;\n if (item.collectionName !== collectionName)\n continue;\n if (item.type === 'remove' && item.data !== id)\n continue;\n if (item.data.id !== id)\n continue;\n newRemoteChanges[i] = null;\n }\n this.remoteChanges = newRemoteChanges.filter(item => item != null);\n };\n collection.on('added', (item) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'insert', data: item })) {\n removeRemoteChanges(options.name, item.id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'insert',\n data: item,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n collection.on('changed', ({ id }, modifier) => {\n const data = { id, modifier };\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'update', data })) {\n removeRemoteChanges(options.name, id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'update',\n data,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n collection.on('removed', ({ id }) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'remove', data: id })) {\n removeRemoteChanges(options.name, id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'remove',\n data: id,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n if (this.options.autostart) {\n this.startSync(options.name)\n .catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n }\n }\n flushScheduledPushes() {\n this.scheduledPushes.forEach((name) => {\n this.pushChanges(name).catch(() => { });\n });\n this.scheduledPushes.clear();\n }\n schedulePush(name) {\n this.scheduledPushes.add(name);\n this.debouncedFlush();\n }\n /**\n * Setup all collections to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n */\n async startAll() {\n await Promise.all([...this.collections.keys()].map(id => this.startSync(id)));\n }\n /**\n * Setup a collection to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n * @param name Name of the collection\n */\n async startSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (!collectionParameters.syncPaused)\n return; // already started\n this.schedulePush(name); // push changes that were made while paused\n const cleanupFunction = this.options.registerRemoteChange\n ? await this.options.registerRemoteChange(collectionParameters.options, async (data) => {\n await (data == null\n ? this.sync(name)\n : this.getSyncQueue(name).add(async () => {\n const syncTime = Date.now();\n const syncId = await this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n await this.syncWithData(name, data)\n .then(async () => {\n // clean up old sync operations\n await this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n })\n .catch(async (error) => {\n if (this.options.onError) {\n this.options.onError(this.getCollectionProperties(name).options, error);\n }\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n throw error;\n });\n }));\n })\n : undefined;\n this.collections.set(name, {\n ...collectionParameters,\n syncPaused: false,\n cleanupFunction,\n });\n }\n /**\n * Pauses the sync process for all collections.\n * This means that the collections will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n */\n async pauseAll() {\n await Promise.all([...this.collections.keys()].map(id => this.pauseSync(id)));\n }\n /**\n * Pauses the sync process for a collection.\n * This means that the collection will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n * @param name Name of the collection\n */\n async pauseSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (collectionParameters.syncPaused)\n return; // already paused\n if (collectionParameters.cleanupFunction)\n await collectionParameters.cleanupFunction();\n this.collections.set(name, {\n ...collectionParameters,\n cleanupFunction: undefined,\n syncPaused: true,\n });\n }\n /**\n * Starts the sync process for all collections\n */\n async syncAll() {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n const errors = [];\n await Promise.all([...this.collections.keys()].map(id => this.sync(id).catch((error) => {\n errors.push({ id, error });\n })));\n if (errors.length > 0)\n throw new Error(`Error while syncing collections:\\n${errors.map(error => `${error.id}: ${error.error.message}`).join('\\n\\n')}`);\n }\n isSyncing(name, async) {\n const itemOrPromise = this.syncOperations.findOne({\n ...name ? { collectionName: name } : {},\n status: 'active',\n }, { fields: { status: 1 }, async });\n if (itemOrPromise instanceof Promise) {\n return itemOrPromise\n .then(item => item != null);\n }\n return (itemOrPromise != null);\n }\n /**\n * Checks if the sync manager is ready to sync.\n * @returns A promise that resolves when the sync manager is ready to sync.\n */\n async isReady() {\n await this.collectionsReady;\n }\n /**\n * Starts the sync process for a collection\n * @param name Name of the collection\n * @param options Options for the sync process.\n * @param options.force If true, the sync process will be started even if there are no changes and onlyWithChanges is true.\n * @param options.onlyWithChanges If true, the sync process will only be started if there are changes.\n */\n async sync(name, options = {}) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n await this.isReady();\n const { options: collectionOptions, readyPromise } = this.getCollectionProperties(name);\n await readyPromise;\n const hasActiveSyncs = await this.syncOperations.find({\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n }, {\n reactive: false,\n async: true,\n }).count() > 0;\n const syncTime = Date.now();\n let syncId = null;\n // schedule for next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const doSync = async () => {\n const lastFinishedSync = await this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n async: true,\n });\n if (options?.onlyWithChanges) {\n const currentChanges = await this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n async: true,\n }).count();\n if (currentChanges === 0)\n return;\n }\n if (!hasActiveSyncs) {\n syncId = await this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n }\n const data = await this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n });\n await this.syncWithData(name, data);\n };\n await (options?.force ? doSync() : this.getSyncQueue(name).add(doSync))\n .catch(async (error) => {\n if (syncId != null) {\n if (this.options.onError)\n this.options.onError(collectionOptions, error);\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n }\n throw error;\n });\n if (syncId != null) {\n // clean up old sync operations\n await this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n }\n }\n /**\n * Starts the push process for a collection (sync process but only if there are changes)\n * @param name Name of the collection\n */\n async pushChanges(name) {\n await this.sync(name, {\n onlyWithChanges: true,\n });\n }\n async syncWithData(name, data) {\n const { collection, options: collectionOptions } = this.getCollectionProperties(name);\n const syncTime = Date.now();\n const lastFinishedSync = await this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n async: true,\n });\n const lastSnapshot = await this.snapshots.findOne({\n collectionName: name,\n }, {\n sort: { time: -1 },\n reactive: false,\n async: true,\n });\n const currentChanges = await this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n async: true,\n }).fetch();\n await sync({\n changes: currentChanges,\n lastSnapshot: lastSnapshot?.items,\n data,\n pull: () => this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n }),\n push: changes => this.options.push(collectionOptions, {\n changes,\n rawChanges: currentChanges,\n }),\n insert: async (item) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n }, {\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // replace the item\n await collection.replaceOne({ id: item.id }, item, { upsert: true });\n },\n update: async (itemId, modifier) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: { id: itemId, ...modifier.$set },\n }, {\n collectionName: name,\n type: 'update',\n data: { id: itemId, modifier },\n });\n await collection.updateOne({ id: itemId }, {\n ...modifier,\n $setOnInsert: { id: itemId },\n }, { upsert: true });\n },\n remove: async (itemId) => {\n const itemExists = await collection.find({\n id: itemId,\n }, { reactive: false, async: true }).count() > 0;\n if (!itemExists)\n return;\n this.remoteChanges.push({\n collectionName: name,\n type: 'remove',\n data: itemId,\n });\n await collection.removeOne({ id: itemId });\n },\n batch: async (fn) => {\n return collection.batch(async () => {\n await fn();\n });\n },\n })\n .then(async (snapshot) => {\n // clean up old snapshots\n await this.snapshots.removeMany({\n collectionName: name,\n time: { $lte: syncTime },\n });\n // clean up processed changes\n await this.changes.removeMany({\n collectionName: name,\n id: { $in: currentChanges.map(c => c.id) },\n });\n // insert new snapshot\n await this.snapshots.insert({\n time: syncTime,\n collectionName: name,\n items: snapshot,\n });\n // delay sync operation update to next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const hasChanges = await this.changes.find({\n collectionName: name,\n }, { reactive: false, async: true }).count() > 0;\n if (hasChanges) {\n // check if there are unsynced changes to push\n // and sync again if there are any\n await this.sync(name, {\n force: true,\n onlyWithChanges: true,\n });\n return;\n }\n // if there are no unsynced changes apply the last snapshot\n // to make sure that collection and snapshot are in sync\n // find all items that are not in the snapshot\n const nonExistingItemIds = await collection.find({\n id: { $nin: snapshot.map(item => item.id) },\n }, {\n reactive: false,\n async: true,\n }).map(item => item.id);\n await collection.batch(async () => {\n // update all items that are in the snapshot\n await Promise.all(snapshot.map(async (item) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n }, {\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // replace the item\n await collection.replaceOne({ id: item.id }, item, { upsert: true });\n }));\n // remove all items that are not in the snapshot\n await Promise.all(nonExistingItemIds.map(async (id) => {\n await collection.removeOne({ id });\n }));\n });\n });\n }\n}\n"],"names":["debounce","fn","wait","options","timeout","result","leading","trailing","debounced","args","shouldCallImmediately","shouldCallTrailing","PromiseQueue","task","resolve","reject","error","computeModifiedFields","oldItem","newItem","modifiedFields","oldKeys","newKeys","allKeys","key","nestedModifiedFields","nestedField","computeChanges","oldItems","newItems","added","modified","removed","oldItemsMap","item","newItemsMap","id","isEqual","getSnapshot","lastSnapshot","data","items","index","i","applyChanges","changes","itemMap","change","existingItem","modify","hasChanges","hasDifference","sync","pull","push","insert","update","remove","batch","newData","previousSnapshot","newSnapshot","lastSnapshotWithChanges","newSnapshotWithChanges","changesToPush","newChanges","SyncManager","randomId","reactivity","dataAdapter","DefaultDataAdapter","Collection","readiness","name","collection","collectionParameters","hasRemoteChange","remoteChange","removeRemoteChanges","collectionName","newRemoteChanges","modifier","cleanupFunction","syncTime","syncId","errors","async","itemOrPromise","collectionOptions","readyPromise","hasActiveSyncs","doSync","lastFinishedSync","currentChanges","itemId","snapshot","c","nonExistingItemIds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M,QAAQ,IAAI+D,EAAmB,IAAI,OAAO7D,MAAO;AACnD,gBAAMsC,EAAW,UAAU,EAAE,IAAAtC,GAAI;AAAA,QACrC,CAAC,CAAC;AAAA,MACN,CAAC;AAAA,IACL,CAAC;AAAA,EACL;AACJ;"}
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/utils/debounce.ts","../src/utils/PromiseQueue.ts","../src/computeChanges.ts","../src/getSnapshot.ts","../src/applyChanges.ts","../src/sync.ts","../src/SyncManager.ts"],"sourcesContent":["/**\n * Debounces a function.\n * @param fn Function to debounce\n * @param wait Time to wait before calling the function.\n * @param [options] Debounce options\n * @param [options.leading] Whether to call the function on the leading edge of the wait interval.\n * @param [options.trailing] Whether to call the function on the trailing edge of the wait interval.\n * @returns The debounced function.\n */\nexport default function debounce(fn, wait, options = {}) {\n let timeout;\n let result;\n const { leading = false, trailing = true } = options;\n /**\n * The debounced function that will be returned.\n * @param this The context to bind the function to.\n * @param args The arguments to pass to the function.\n * @returns The result of the debounced function.\n */\n function debounced(...args) {\n const shouldCallImmediately = leading && !timeout;\n const shouldCallTrailing = trailing && !timeout;\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n timeout = null;\n if (trailing && !shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n }, wait);\n if (shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n else if (!shouldCallTrailing) {\n result = null;\n }\n return result;\n }\n return debounced;\n}\n","/**\n * Class for queuing promises to be executed one after the other.\n * This is useful for tasks that should not be executed in parallel.\n * @example\n * const queue = new PromiseQueue();\n * queue.add(() => fetch('https://example.com/api/endpoint1'));\n * queue.add(() => fetch('https://example.com/api/endpoint2'));\n * // The second fetch will only be executed after the first one is done.\n */\nexport default class PromiseQueue {\n queue = [];\n pendingPromise = false;\n /**\n * Method to add a new promise to the queue and returns a promise that resolves when this task is done\n * @param task Function that returns a promise that will be added to the queue\n * @returns Promise that resolves when the task is done\n */\n add(task) {\n return new Promise((resolve, reject) => {\n // Wrap the task with the resolve and reject to control its completion from the outside\n this.queue.push(() => task()\n .then(resolve)\n .catch((error) => {\n reject(error);\n throw error;\n }));\n this.dequeue();\n });\n }\n /**\n * Method to check if there is a pending promise in the queue\n * @returns True if there is a pending promise, false otherwise\n */\n hasPendingPromise() {\n return this.pendingPromise;\n }\n /**\n * Method to process the queue\n */\n dequeue() {\n if (this.pendingPromise || this.queue.length === 0) {\n return;\n }\n const task = this.queue.shift();\n if (!task)\n return;\n this.pendingPromise = true;\n task()\n .then(() => {\n this.pendingPromise = false;\n this.dequeue();\n })\n .catch(() => {\n this.pendingPromise = false;\n this.dequeue();\n });\n }\n}\n","import { isEqual } from '@signaldb/core';\n/**\n * Computes the modified fields between two items recursively.\n * @param oldItem The old item\n * @param newItem The new item\n * @returns The modified fields\n */\nexport function computeModifiedFields(oldItem, newItem) {\n const modifiedFields = [];\n const oldKeys = Object.keys(oldItem);\n const newKeys = Object.keys(newItem);\n const allKeys = new Set([...oldKeys, ...newKeys]);\n for (const key of allKeys) {\n if (newItem[key] !== oldItem[key]) {\n if (typeof newItem[key] === 'object' && typeof oldItem[key] === 'object' && newItem[key] != null && oldItem[key] != null) {\n const nestedModifiedFields = computeModifiedFields(oldItem[key], newItem[key]);\n for (const nestedField of nestedModifiedFields) {\n modifiedFields.push(`${key}.${nestedField}`);\n }\n }\n else {\n modifiedFields.push(key);\n }\n }\n }\n return modifiedFields;\n}\n/**\n * Compute changes between two arrays of items.\n * @param oldItems Array of the old items\n * @param newItems Array of the new items\n * @returns The changeset\n */\nexport default function computeChanges(oldItems, newItems) {\n const added = [];\n const modified = [];\n const modifiedFields = new Map();\n const removed = [];\n const oldItemsMap = new Map(oldItems.map(item => [item.id, item]));\n const newItemsMap = new Map(newItems.map(item => [item.id, item]));\n for (const [id, oldItem] of oldItemsMap) {\n const newItem = newItemsMap.get(id);\n if (!newItem) {\n removed.push(oldItem);\n }\n else if (!isEqual(newItem, oldItem)) {\n modifiedFields.set(newItem.id, computeModifiedFields(oldItem, newItem));\n modified.push(newItem);\n }\n }\n for (const [id, newItem] of newItemsMap) {\n if (!oldItemsMap.has(id)) {\n added.push(newItem);\n }\n }\n return {\n added,\n modified,\n modifiedFields,\n removed,\n };\n}\n","/**\n * Gets the snapshot of items from the last snapshot and the changes.\n * @param lastSnapshot The last snapshot of items\n * @param data The changes to apply to the last snapshot\n * @returns The new snapshot of items\n */\nexport default function getSnapshot(lastSnapshot, data) {\n if (data.items != null)\n return data.items;\n const items = lastSnapshot || [];\n data.changes.added.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.modified.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.removed.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index !== -1)\n items.splice(index, 1);\n });\n return items;\n}\n","import { modify } from '@signaldb/core';\n/**\n * applies changes to a collection of items\n * @param items The items to apply the changes to\n * @param changes The changes to apply to the items\n * @returns The new items after applying the changes\n */\nexport default function applyChanges(items, changes) {\n // Create initial map of items by ID\n const itemMap = new Map(items.map(item => [item.id, item]));\n changes.forEach((change) => {\n if (change.type === 'remove') {\n itemMap.delete(change.data);\n }\n else if (change.type === 'insert') {\n const existingItem = itemMap.get(change.data.id);\n itemMap.set(change.data.id, existingItem ? { ...existingItem, ...change.data } : change.data);\n }\n else { // change.type === 'update'\n const existingItem = itemMap.get(change.data.id);\n itemMap.set(change.data.id, existingItem\n ? modify(existingItem, change.data.modifier)\n : modify({ id: change.data.id }, change.data.modifier));\n }\n });\n // Convert map back to array\n return [...itemMap.values()];\n}\n","import computeChanges from './computeChanges';\nimport getSnapshot from './getSnapshot';\nimport applyChanges from './applyChanges';\n/**\n * Checks if there are any changes in the given changeset.\n * @param changes The changeset to check.\n * @returns True if there are changes, false otherwise.\n */\nfunction hasChanges(changes) {\n return changes.added.length > 0\n || changes.modified.length > 0\n || changes.removed.length > 0;\n}\n/**\n * Checks if there is a difference between the old items and the new items.\n * @param oldItems The old items.\n * @param newItems The new items.\n * @returns True if there is a difference, false otherwise.\n */\nfunction hasDifference(oldItems, newItems) {\n return hasChanges(computeChanges(oldItems, newItems));\n}\n/**\n * Does a sync operation based on the provided options. If changes are supplied, these will be rebased on the new data.\n * Afterwards the push method will be called with the remaining changes. A new snapshot will be created and returned.\n * @param options Sync options\n * @param options.changes Changes to call the push method with\n * @param [options.lastSnapshot] The last snapshot\n * @param options.data The new data\n * @param options.pull Method to pull new data\n * @param options.push Method to push changes\n * @param options.insert Method to insert an item\n * @param options.update Method to update an item\n * @param options.remove Method to remove an item\n * @param options.batch Method to batch multiple operations\n * @returns The new snapshot\n */\nexport default async function sync({ changes, lastSnapshot, data, pull, push, insert, update, remove, batch, }) {\n let newData = data;\n let previousSnapshot = lastSnapshot || [];\n let newSnapshot = getSnapshot(lastSnapshot, newData);\n if (changes.length > 0) {\n // apply changes on last snapshot and check if there is a difference\n const lastSnapshotWithChanges = applyChanges(previousSnapshot, changes);\n if (hasDifference(previousSnapshot, lastSnapshotWithChanges)) {\n // if yes, apply the changes on the newSnapshot and check if there is a difference\n const newSnapshotWithChanges = applyChanges(newSnapshot, changes);\n const changesToPush = computeChanges(newSnapshot, newSnapshotWithChanges);\n if (hasChanges(changesToPush)) {\n // if yes, push the changes to the server\n await push(changesToPush);\n // pull new data afterwards to ensure that all server changes are applied\n newData = await pull();\n newSnapshot = getSnapshot(newSnapshot, newData);\n }\n previousSnapshot = lastSnapshotWithChanges;\n }\n }\n // apply the new changes on the collection\n const newChanges = newData.changes == null\n ? computeChanges(previousSnapshot, newData.items)\n : newData.changes;\n await batch(async () => {\n await Promise.all(newChanges.added.map(item => insert(item)));\n await Promise.all(newChanges.modified.map(item => update(item.id, { $set: item })));\n await Promise.all(newChanges.removed.map(item => remove(item.id)));\n });\n return newSnapshot;\n}\n","import { DefaultDataAdapter, Collection, randomId } from '@signaldb/core';\nimport debounce from './utils/debounce';\nimport PromiseQueue from './utils/PromiseQueue';\nimport sync from './sync';\n/**\n * Class to manage syncing of collections.\n * @template CollectionOptions\n * @template ItemType\n * @template IdType\n * @example\n * const syncManager = new SyncManager({\n * pull: async (collectionOptions) => {\n * const response = await fetch(`/api/collections/${collectionOptions.name}`)\n * return await response.json()\n * },\n * push: async (collectionOptions, { changes }) => {\n * await fetch(`/api/collections/${collectionOptions.name}`, {\n * method: 'POST',\n * body: JSON.stringify(changes),\n * })\n * },\n * })\n *\n * const collection = new Collection()\n * syncManager.addCollection(collection, {\n * name: 'todos',\n * })\n *\n * syncManager.sync('todos')\n */\nexport default class SyncManager {\n options;\n collections = new Map();\n changes;\n snapshots;\n syncOperations;\n scheduledPushes = new Set();\n remoteChanges = [];\n syncQueues = new Map();\n collectionsReady;\n isDisposed = false;\n instanceId = randomId();\n id;\n debouncedFlush;\n /**\n * @param options Collection options\n * @param options.pull Function to pull data from remote source.\n * @param options.push Function to push data to remote source.\n * @param [options.registerRemoteChange] Function to register a callback for remote changes.\n * @param [options.id] Unique identifier for this sync manager. Only nessesary if you have multiple sync managers.\n * @param [options.storageAdapter] Storage adapter to use for storing changes, snapshots and sync operations.\n * @param [options.reactivity] Reactivity adapter to use for reactivity.\n * @param [options.onError] Function to handle errors that occur async during syncing.\n * @param [options.autostart] Whether to automatically start syncing new collections.\n * @param [options.debounceTime] The time in milliseconds to debounce push operations.\n */\n constructor(options) {\n this.options = {\n autostart: true,\n ...options,\n };\n this.id = this.options.id || 'default-sync-manager';\n const { reactivity } = this.options;\n const dataAdapter = this.options.dataAdapter ?? new DefaultDataAdapter();\n this.changes = new Collection(`${this.options.id}-changes`, dataAdapter, {\n indices: ['collectionName'],\n reactivity,\n });\n this.snapshots = new Collection(`${this.options.id}-snapshots`, dataAdapter, {\n indices: ['collectionName'],\n reactivity,\n });\n this.syncOperations = new Collection(`${this.options.id}-sync-operations`, dataAdapter, {\n indices: ['collectionName', 'status'],\n reactivity,\n });\n const readiness = [\n Promise.resolve(this.syncOperations.isReady()),\n Promise.resolve(this.changes.isReady()),\n Promise.resolve(this.snapshots.isReady()),\n ];\n this.collectionsReady = Promise.all(readiness).then(() => { });\n this.changes.setMaxListeners(1000);\n this.snapshots.setMaxListeners(1000);\n this.syncOperations.setMaxListeners(1000);\n this.debouncedFlush = debounce(this.flushScheduledPushes, this.options.debounceTime ?? 100);\n }\n getSyncQueue(name) {\n if (this.syncQueues.get(name) == null) {\n this.syncQueues.set(name, new PromiseQueue());\n }\n return this.syncQueues.get(name);\n }\n /**\n * Clears all internal data structures\n */\n async dispose() {\n this.collections.clear();\n this.syncQueues.clear();\n this.remoteChanges.splice(0);\n await Promise.all([\n this.changes.dispose(),\n this.snapshots.dispose(),\n this.syncOperations.dispose(),\n ]);\n this.isDisposed = true;\n }\n /**\n * Gets a collection with it's options by name\n * @deprecated Use getCollectionProperties instead.\n * @param name Name of the collection\n * @throws {Error} Will throw an error if the name wasn't found\n * @returns Tuple of collection and options\n */\n getCollection(name) {\n const { collection, options } = this.getCollectionProperties(name);\n return [collection, options];\n }\n /**\n * Gets collection options by name\n * @param name Name of the collection\n * @throws {Error} Will throw an error if the name wasn't found\n * @returns An object of all properties of the collection\n */\n getCollectionProperties(name) {\n const collectionParameters = this.collections.get(name);\n if (collectionParameters == null)\n throw new Error(`Collection with id '${name}' not found`);\n return collectionParameters;\n }\n /**\n * Adds a collection to the sync manager.\n * @param collection Collection to add\n * @param options Options for the collection. The object needs at least a `name` property.\n * @param options.name Unique name of the collection\n */\n addCollection(collection, options) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n this.collections.set(options.name, {\n collection: collection,\n options,\n readyPromise: collection.ready(),\n syncPaused: true, // always start paused as the autostart will start it\n });\n const hasRemoteChange = (change) => {\n for (const remoteChange of this.remoteChanges) {\n if (remoteChange == null)\n continue;\n if (remoteChange.collectionName !== change.collectionName)\n continue;\n if (remoteChange.type !== change.type)\n continue;\n if (change.type === 'remove' && remoteChange.data !== change.data)\n continue;\n if (remoteChange.data.id !== change.data.id)\n continue;\n return true;\n }\n return false;\n };\n const removeRemoteChanges = (collectionName, id) => {\n const newRemoteChanges = [...this.remoteChanges];\n for (let i = 0; i < newRemoteChanges.length; i += 1) {\n const item = newRemoteChanges[i];\n if (item == null)\n continue;\n if (item.collectionName !== collectionName)\n continue;\n if (item.type === 'remove' && item.data !== id)\n continue;\n if (item.data.id !== id)\n continue;\n newRemoteChanges[i] = null;\n }\n this.remoteChanges = newRemoteChanges.filter(item => item != null);\n };\n collection.on('added', (item) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'insert', data: item })) {\n removeRemoteChanges(options.name, item.id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'insert',\n data: item,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n collection.on('changed', ({ id }, modifier) => {\n const data = { id, modifier };\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'update', data })) {\n removeRemoteChanges(options.name, id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'update',\n data,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n collection.on('removed', ({ id }) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'remove', data: id })) {\n removeRemoteChanges(options.name, id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'remove',\n data: id,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n if (this.options.autostart) {\n this.startSync(options.name)\n .catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n }\n }\n flushScheduledPushes() {\n this.scheduledPushes.forEach((name) => {\n this.pushChanges(name).catch(() => { });\n });\n this.scheduledPushes.clear();\n }\n schedulePush(name) {\n this.scheduledPushes.add(name);\n this.debouncedFlush();\n }\n /**\n * Setup all collections to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n */\n async startAll() {\n await Promise.all([...this.collections.keys()].map(id => this.startSync(id)));\n }\n /**\n * Setup a collection to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n * @param name Name of the collection\n */\n async startSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (!collectionParameters.syncPaused)\n return; // already started\n this.schedulePush(name); // push changes that were made while paused\n const cleanupFunction = this.options.registerRemoteChange\n ? await this.options.registerRemoteChange(collectionParameters.options, async (data) => {\n await (data == null\n ? this.sync(name)\n : this.getSyncQueue(name).add(async () => {\n const syncTime = Date.now();\n const syncId = await this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n await this.syncWithData(name, data)\n .then(async () => {\n // clean up old sync operations\n await this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n })\n .catch(async (error) => {\n if (this.options.onError) {\n this.options.onError(this.getCollectionProperties(name).options, error);\n }\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n throw error;\n });\n }));\n })\n : undefined;\n this.collections.set(name, {\n ...collectionParameters,\n syncPaused: false,\n cleanupFunction,\n });\n }\n /**\n * Pauses the sync process for all collections.\n * This means that the collections will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n */\n async pauseAll() {\n await Promise.all([...this.collections.keys()].map(id => this.pauseSync(id)));\n }\n /**\n * Pauses the sync process for a collection.\n * This means that the collection will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n * @param name Name of the collection\n */\n async pauseSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (collectionParameters.syncPaused)\n return; // already paused\n if (collectionParameters.cleanupFunction)\n await collectionParameters.cleanupFunction();\n this.collections.set(name, {\n ...collectionParameters,\n cleanupFunction: undefined,\n syncPaused: true,\n });\n }\n /**\n * Starts the sync process for all collections\n */\n async syncAll() {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n const errors = [];\n await Promise.all([...this.collections.keys()].map(id => this.sync(id).catch((error) => {\n errors.push({ id, error });\n })));\n if (errors.length > 0)\n throw new Error(`Error while syncing collections:\\n${errors.map(error => `${error.id}: ${error.error.message}`).join('\\n\\n')}`);\n }\n /**\n * Checks if a collection is currently beeing synced\n * @param [name] Name of the collection. If not provided, it will check if any collection is currently beeing synced.\n * @param [async] If true, it will check for active syncs in the database. This is useful if you have multiple instances of the application running.\n * @returns True if the collection is currently beeing synced, false otherwise. If async is true, it will return a promise that resolves to true or false.\n */\n isSyncing(name, async) {\n const itemOrPromise = this.syncOperations.findOne({\n ...name ? { collectionName: name } : {},\n status: 'active',\n }, { fields: { status: 1 }, async });\n if (itemOrPromise instanceof Promise) {\n return itemOrPromise\n .then(item => item != null);\n }\n return (itemOrPromise != null);\n }\n /**\n * Checks if the sync manager is ready to sync.\n * @returns A promise that resolves when the sync manager is ready to sync.\n */\n async isReady() {\n await this.collectionsReady;\n }\n /**\n * Starts the sync process for a collection\n * @param name Name of the collection\n * @param options Options for the sync process.\n * @param options.force If true, the sync process will be started even if there are no changes and onlyWithChanges is true.\n * @param options.onlyWithChanges If true, the sync process will only be started if there are changes.\n */\n async sync(name, options = {}) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n await this.isReady();\n const { options: collectionOptions, readyPromise } = this.getCollectionProperties(name);\n await readyPromise;\n const hasActiveSyncs = await this.syncOperations.find({\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n }, {\n reactive: false,\n async: true,\n }).count() > 0;\n const syncTime = Date.now();\n let syncId = null;\n // schedule for next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const doSync = async () => {\n const lastFinishedSync = await this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n async: true,\n });\n if (options?.onlyWithChanges) {\n const currentChanges = await this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n async: true,\n }).count();\n if (currentChanges === 0)\n return;\n }\n if (!hasActiveSyncs) {\n syncId = await this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n }\n const data = await this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n });\n await this.syncWithData(name, data);\n };\n await (options?.force ? doSync() : this.getSyncQueue(name).add(doSync))\n .catch(async (error) => {\n if (syncId != null) {\n if (this.options.onError)\n this.options.onError(collectionOptions, error);\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n }\n throw error;\n });\n if (syncId != null) {\n // clean up old sync operations\n await this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n }\n }\n /**\n * Starts the push process for a collection (sync process but only if there are changes)\n * @param name Name of the collection\n */\n async pushChanges(name) {\n await this.sync(name, {\n onlyWithChanges: true,\n });\n }\n async syncWithData(name, data) {\n const { collection, options: collectionOptions } = this.getCollectionProperties(name);\n const syncTime = Date.now();\n const lastFinishedSync = await this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n async: true,\n });\n const lastSnapshot = await this.snapshots.findOne({\n collectionName: name,\n }, {\n sort: { time: -1 },\n reactive: false,\n async: true,\n });\n const currentChanges = await this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n async: true,\n }).fetch();\n await sync({\n changes: currentChanges,\n lastSnapshot: lastSnapshot?.items,\n data,\n pull: () => this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n }),\n push: changes => this.options.push(collectionOptions, {\n changes,\n rawChanges: currentChanges,\n }),\n insert: async (item) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n }, {\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // replace the item\n await collection.replaceOne({ id: item.id }, item, { upsert: true });\n },\n update: async (itemId, modifier) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: { id: itemId, ...modifier.$set },\n }, {\n collectionName: name,\n type: 'update',\n data: { id: itemId, modifier },\n });\n await collection.updateOne({ id: itemId }, {\n ...modifier,\n $setOnInsert: { id: itemId },\n }, { upsert: true });\n },\n remove: async (itemId) => {\n const itemExists = await collection.find({\n id: itemId,\n }, { reactive: false, async: true }).count() > 0;\n if (!itemExists)\n return;\n this.remoteChanges.push({\n collectionName: name,\n type: 'remove',\n data: itemId,\n });\n await collection.removeOne({ id: itemId });\n },\n batch: async (fn) => {\n return collection.batch(async () => {\n await fn();\n });\n },\n })\n .then(async (snapshot) => {\n // clean up old snapshots\n await this.snapshots.removeMany({\n collectionName: name,\n time: { $lte: syncTime },\n });\n // clean up processed changes\n await this.changes.removeMany({\n collectionName: name,\n id: { $in: currentChanges.map(c => c.id) },\n });\n // insert new snapshot\n await this.snapshots.insert({\n time: syncTime,\n collectionName: name,\n items: snapshot,\n });\n // delay sync operation update to next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const hasChanges = await this.changes.find({\n collectionName: name,\n }, { reactive: false, async: true }).count() > 0;\n if (hasChanges) {\n // check if there are unsynced changes to push\n // and sync again if there are any\n await this.sync(name, {\n force: true,\n onlyWithChanges: true,\n });\n return;\n }\n // if there are no unsynced changes apply the last snapshot\n // to make sure that collection and snapshot are in sync\n // find all items that are not in the snapshot\n const nonExistingItemIds = await collection.find({\n id: { $nin: snapshot.map(item => item.id) },\n }, {\n reactive: false,\n async: true,\n }).map(item => item.id);\n await collection.batch(async () => {\n // update all items that are in the snapshot\n await Promise.all(snapshot.map(async (item) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n }, {\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // replace the item\n await collection.replaceOne({ id: item.id }, item, { upsert: true });\n }));\n // remove all items that are not in the snapshot\n await Promise.all(nonExistingItemIds.map(async (id) => {\n await collection.removeOne({ id });\n }));\n });\n });\n }\n}\n"],"names":["debounce","fn","wait","options","timeout","result","leading","trailing","debounced","args","shouldCallImmediately","shouldCallTrailing","PromiseQueue","task","resolve","reject","error","computeModifiedFields","oldItem","newItem","modifiedFields","oldKeys","newKeys","allKeys","key","nestedModifiedFields","nestedField","computeChanges","oldItems","newItems","added","modified","removed","oldItemsMap","item","newItemsMap","id","isEqual","getSnapshot","lastSnapshot","data","items","index","i","applyChanges","changes","itemMap","change","existingItem","modify","hasChanges","hasDifference","sync","pull","push","insert","update","remove","batch","newData","previousSnapshot","newSnapshot","lastSnapshotWithChanges","newSnapshotWithChanges","changesToPush","newChanges","SyncManager","randomId","reactivity","dataAdapter","DefaultDataAdapter","Collection","readiness","name","collection","collectionParameters","hasRemoteChange","remoteChange","removeRemoteChanges","collectionName","newRemoteChanges","modifier","cleanupFunction","syncTime","syncId","errors","async","itemOrPromise","collectionOptions","readyPromise","hasActiveSyncs","doSync","lastFinishedSync","currentChanges","itemId","snapshot","c","nonExistingItemIds"],"mappings":"qRASA,SAAwBA,EAASC,EAAIC,EAAMC,EAAU,CAAA,EAAI,CACrD,IAAIC,EACAC,EACJ,KAAM,CAAE,QAAAC,EAAU,GAAO,SAAAC,EAAW,IAASJ,EAO7C,SAASK,KAAaC,EAAM,CACxB,MAAMC,EAAwBJ,GAAW,CAACF,EACpCO,EAAqBJ,GAAY,CAACH,EACxC,OAAIA,GACA,aAAaA,CAAO,EAExBA,EAAU,WAAW,IAAM,CACvBA,EAAU,KACNG,GAAY,CAACG,IACbL,EAASJ,EAAG,MAAM,KAAMQ,CAAI,EAEpC,EAAGP,CAAI,EACHQ,EACAL,EAASJ,EAAG,MAAM,KAAMQ,CAAI,EAEtBE,IACNN,EAAS,MAENA,CACX,CACA,OAAOG,CACX,CC/BA,MAAqBI,CAAa,CAC9B,MAAQ,CAAA,EACR,eAAiB,GAMjB,IAAIC,EAAM,CACN,OAAO,IAAI,QAAQ,CAACC,EAASC,IAAW,CAEpC,KAAK,MAAM,KAAK,IAAMF,EAAA,EACjB,KAAKC,CAAO,EACZ,MAAOE,GAAU,CAClB,MAAAD,EAAOC,CAAK,EACNA,CACV,CAAC,CAAC,EACF,KAAK,QAAA,CACT,CAAC,CACL,CAKA,mBAAoB,CAChB,OAAO,KAAK,cAChB,CAIA,SAAU,CACN,GAAI,KAAK,gBAAkB,KAAK,MAAM,SAAW,EAC7C,OAEJ,MAAMH,EAAO,KAAK,MAAM,MAAA,EACnBA,IAEL,KAAK,eAAiB,GACtBA,EAAA,EACK,KAAK,IAAM,CACZ,KAAK,eAAiB,GACtB,KAAK,QAAA,CACT,CAA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E,GAAAtC,EAAI,CACrC,CAAC,CAAC,CACN,CAAC,CACL,CAAC,CACL,CACJ"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/utils/debounce.ts","../src/utils/PromiseQueue.ts","../src/computeChanges.ts","../src/getSnapshot.ts","../src/applyChanges.ts","../src/sync.ts","../src/SyncManager.ts"],"sourcesContent":["/**\n * Debounces a function.\n * @param fn Function to debounce\n * @param wait Time to wait before calling the function.\n * @param [options] Debounce options\n * @param [options.leading] Whether to call the function on the leading edge of the wait interval.\n * @param [options.trailing] Whether to call the function on the trailing edge of the wait interval.\n * @returns The debounced function.\n */\nexport default function debounce(fn, wait, options = {}) {\n let timeout;\n let result;\n const { leading = false, trailing = true } = options;\n /**\n * The debounced function that will be returned.\n * @param this The context to bind the function to.\n * @param args The arguments to pass to the function.\n * @returns The result of the debounced function.\n */\n function debounced(...args) {\n const shouldCallImmediately = leading && !timeout;\n const shouldCallTrailing = trailing && !timeout;\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n timeout = null;\n if (trailing && !shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n }, wait);\n if (shouldCallImmediately) {\n result = fn.apply(this, args);\n }\n else if (!shouldCallTrailing) {\n result = null;\n }\n return result;\n }\n return debounced;\n}\n","/**\n * Class for queuing promises to be executed one after the other.\n * This is useful for tasks that should not be executed in parallel.\n * @example\n * const queue = new PromiseQueue();\n * queue.add(() => fetch('https://example.com/api/endpoint1'));\n * queue.add(() => fetch('https://example.com/api/endpoint2'));\n * // The second fetch will only be executed after the first one is done.\n */\nexport default class PromiseQueue {\n queue = [];\n pendingPromise = false;\n /**\n * Method to add a new promise to the queue and returns a promise that resolves when this task is done\n * @param task Function that returns a promise that will be added to the queue\n * @returns Promise that resolves when the task is done\n */\n add(task) {\n return new Promise((resolve, reject) => {\n // Wrap the task with the resolve and reject to control its completion from the outside\n this.queue.push(() => task()\n .then(resolve)\n .catch((error) => {\n reject(error);\n throw error;\n }));\n this.dequeue();\n });\n }\n /**\n * Method to check if there is a pending promise in the queue\n * @returns True if there is a pending promise, false otherwise\n */\n hasPendingPromise() {\n return this.pendingPromise;\n }\n /**\n * Method to process the queue\n */\n dequeue() {\n if (this.pendingPromise || this.queue.length === 0) {\n return;\n }\n const task = this.queue.shift();\n if (!task)\n return;\n this.pendingPromise = true;\n task()\n .then(() => {\n this.pendingPromise = false;\n this.dequeue();\n })\n .catch(() => {\n this.pendingPromise = false;\n this.dequeue();\n });\n }\n}\n","import { isEqual } from '@signaldb/core';\n/**\n * Computes the modified fields between two items recursively.\n * @param oldItem The old item\n * @param newItem The new item\n * @returns The modified fields\n */\nexport function computeModifiedFields(oldItem, newItem) {\n const modifiedFields = [];\n const oldKeys = Object.keys(oldItem);\n const newKeys = Object.keys(newItem);\n const allKeys = new Set([...oldKeys, ...newKeys]);\n for (const key of allKeys) {\n if (newItem[key] !== oldItem[key]) {\n if (typeof newItem[key] === 'object' && typeof oldItem[key] === 'object' && newItem[key] != null && oldItem[key] != null) {\n const nestedModifiedFields = computeModifiedFields(oldItem[key], newItem[key]);\n for (const nestedField of nestedModifiedFields) {\n modifiedFields.push(`${key}.${nestedField}`);\n }\n }\n else {\n modifiedFields.push(key);\n }\n }\n }\n return modifiedFields;\n}\n/**\n * Compute changes between two arrays of items.\n * @param oldItems Array of the old items\n * @param newItems Array of the new items\n * @returns The changeset\n */\nexport default function computeChanges(oldItems, newItems) {\n const added = [];\n const modified = [];\n const modifiedFields = new Map();\n const removed = [];\n const oldItemsMap = new Map(oldItems.map(item => [item.id, item]));\n const newItemsMap = new Map(newItems.map(item => [item.id, item]));\n for (const [id, oldItem] of oldItemsMap) {\n const newItem = newItemsMap.get(id);\n if (!newItem) {\n removed.push(oldItem);\n }\n else if (!isEqual(newItem, oldItem)) {\n modifiedFields.set(newItem.id, computeModifiedFields(oldItem, newItem));\n modified.push(newItem);\n }\n }\n for (const [id, newItem] of newItemsMap) {\n if (!oldItemsMap.has(id)) {\n added.push(newItem);\n }\n }\n return {\n added,\n modified,\n modifiedFields,\n removed,\n };\n}\n","/**\n * Gets the snapshot of items from the last snapshot and the changes.\n * @param lastSnapshot The last snapshot of items\n * @param data The changes to apply to the last snapshot\n * @returns The new snapshot of items\n */\nexport default function getSnapshot(lastSnapshot, data) {\n if (data.items != null)\n return data.items;\n const items = lastSnapshot || [];\n data.changes.added.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.modified.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index === -1) {\n items.push(item);\n }\n else {\n items[index] = item;\n }\n });\n data.changes.removed.forEach((item) => {\n const index = items.findIndex(i => i.id === item.id);\n if (index !== -1)\n items.splice(index, 1);\n });\n return items;\n}\n","import { modify } from '@signaldb/core';\n/**\n * applies changes to a collection of items\n * @param items The items to apply the changes to\n * @param changes The changes to apply to the items\n * @returns The new items after applying the changes\n */\nexport default function applyChanges(items, changes) {\n // Create initial map of items by ID\n const itemMap = new Map(items.map(item => [item.id, item]));\n changes.forEach((change) => {\n if (change.type === 'remove') {\n itemMap.delete(change.data);\n }\n else if (change.type === 'insert') {\n const existingItem = itemMap.get(change.data.id);\n itemMap.set(change.data.id, existingItem ? { ...existingItem, ...change.data } : change.data);\n }\n else { // change.type === 'update'\n const existingItem = itemMap.get(change.data.id);\n itemMap.set(change.data.id, existingItem\n ? modify(existingItem, change.data.modifier)\n : modify({ id: change.data.id }, change.data.modifier));\n }\n });\n // Convert map back to array\n return [...itemMap.values()];\n}\n","import computeChanges from './computeChanges';\nimport getSnapshot from './getSnapshot';\nimport applyChanges from './applyChanges';\n/**\n * Checks if there are any changes in the given changeset.\n * @param changes The changeset to check.\n * @returns True if there are changes, false otherwise.\n */\nfunction hasChanges(changes) {\n return changes.added.length > 0\n || changes.modified.length > 0\n || changes.removed.length > 0;\n}\n/**\n * Checks if there is a difference between the old items and the new items.\n * @param oldItems The old items.\n * @param newItems The new items.\n * @returns True if there is a difference, false otherwise.\n */\nfunction hasDifference(oldItems, newItems) {\n return hasChanges(computeChanges(oldItems, newItems));\n}\n/**\n * Does a sync operation based on the provided options. If changes are supplied, these will be rebased on the new data.\n * Afterwards the push method will be called with the remaining changes. A new snapshot will be created and returned.\n * @param options Sync options\n * @param options.changes Changes to call the push method with\n * @param [options.lastSnapshot] The last snapshot\n * @param options.data The new data\n * @param options.pull Method to pull new data\n * @param options.push Method to push changes\n * @param options.insert Method to insert an item\n * @param options.update Method to update an item\n * @param options.remove Method to remove an item\n * @param options.batch Method to batch multiple operations\n * @returns The new snapshot\n */\nexport default async function sync({ changes, lastSnapshot, data, pull, push, insert, update, remove, batch, }) {\n let newData = data;\n let previousSnapshot = lastSnapshot || [];\n let newSnapshot = getSnapshot(lastSnapshot, newData);\n if (changes.length > 0) {\n // apply changes on last snapshot and check if there is a difference\n const lastSnapshotWithChanges = applyChanges(previousSnapshot, changes);\n if (hasDifference(previousSnapshot, lastSnapshotWithChanges)) {\n // if yes, apply the changes on the newSnapshot and check if there is a difference\n const newSnapshotWithChanges = applyChanges(newSnapshot, changes);\n const changesToPush = computeChanges(newSnapshot, newSnapshotWithChanges);\n if (hasChanges(changesToPush)) {\n // if yes, push the changes to the server\n await push(changesToPush);\n // pull new data afterwards to ensure that all server changes are applied\n newData = await pull();\n newSnapshot = getSnapshot(newSnapshot, newData);\n }\n previousSnapshot = lastSnapshotWithChanges;\n }\n }\n // apply the new changes on the collection\n const newChanges = newData.changes == null\n ? computeChanges(previousSnapshot, newData.items)\n : newData.changes;\n await batch(async () => {\n await Promise.all(newChanges.added.map(item => insert(item)));\n await Promise.all(newChanges.modified.map(item => update(item.id, { $set: item })));\n await Promise.all(newChanges.removed.map(item => remove(item.id)));\n });\n return newSnapshot;\n}\n","import { DefaultDataAdapter, Collection, randomId } from '@signaldb/core';\nimport debounce from './utils/debounce';\nimport PromiseQueue from './utils/PromiseQueue';\nimport sync from './sync';\n/**\n * Class to manage syncing of collections.\n * @template CollectionOptions\n * @template ItemType\n * @template IdType\n * @example\n * const syncManager = new SyncManager({\n * pull: async (collectionOptions) => {\n * const response = await fetch(`/api/collections/${collectionOptions.name}`)\n * return await response.json()\n * },\n * push: async (collectionOptions, { changes }) => {\n * await fetch(`/api/collections/${collectionOptions.name}`, {\n * method: 'POST',\n * body: JSON.stringify(changes),\n * })\n * },\n * })\n *\n * const collection = new Collection()\n * syncManager.addCollection(collection, {\n * name: 'todos',\n * })\n *\n * syncManager.sync('todos')\n */\nexport default class SyncManager {\n options;\n collections = new Map();\n changes;\n snapshots;\n syncOperations;\n scheduledPushes = new Set();\n remoteChanges = [];\n syncQueues = new Map();\n collectionsReady;\n isDisposed = false;\n instanceId = randomId();\n id;\n debouncedFlush;\n /**\n * @param options Collection options\n * @param options.pull Function to pull data from remote source.\n * @param options.push Function to push data to remote source.\n * @param [options.registerRemoteChange] Function to register a callback for remote changes.\n * @param [options.id] Unique identifier for this sync manager. Only nessesary if you have multiple sync managers.\n * @param [options.storageAdapter] Storage adapter to use for storing changes, snapshots and sync operations.\n * @param [options.reactivity] Reactivity adapter to use for reactivity.\n * @param [options.onError] Function to handle errors that occur async during syncing.\n * @param [options.autostart] Whether to automatically start syncing new collections.\n * @param [options.debounceTime] The time in milliseconds to debounce push operations.\n */\n constructor(options) {\n this.options = {\n autostart: true,\n ...options,\n };\n this.id = this.options.id || 'default-sync-manager';\n const { reactivity } = this.options;\n const dataAdapter = this.options.dataAdapter ?? new DefaultDataAdapter();\n this.changes = new Collection(`${this.options.id}-changes`, dataAdapter, {\n indices: ['collectionName'],\n reactivity,\n });\n this.snapshots = new Collection(`${this.options.id}-snapshots`, dataAdapter, {\n indices: ['collectionName'],\n reactivity,\n });\n this.syncOperations = new Collection(`${this.options.id}-sync-operations`, dataAdapter, {\n indices: ['collectionName', 'status'],\n reactivity,\n });\n const readiness = [\n Promise.resolve(this.syncOperations.isReady()),\n Promise.resolve(this.changes.isReady()),\n Promise.resolve(this.snapshots.isReady()),\n ];\n this.collectionsReady = Promise.all(readiness).then(() => { });\n this.changes.setMaxListeners(1000);\n this.snapshots.setMaxListeners(1000);\n this.syncOperations.setMaxListeners(1000);\n this.debouncedFlush = debounce(this.flushScheduledPushes, this.options.debounceTime ?? 100);\n }\n getSyncQueue(name) {\n if (this.syncQueues.get(name) == null) {\n this.syncQueues.set(name, new PromiseQueue());\n }\n return this.syncQueues.get(name);\n }\n /**\n * Clears all internal data structures\n */\n async dispose() {\n this.collections.clear();\n this.syncQueues.clear();\n this.remoteChanges.splice(0);\n await Promise.all([\n this.changes.dispose(),\n this.snapshots.dispose(),\n this.syncOperations.dispose(),\n ]);\n this.isDisposed = true;\n }\n /**\n * Gets a collection with it's options by name\n * @deprecated Use getCollectionProperties instead.\n * @param name Name of the collection\n * @throws {Error} Will throw an error if the name wasn't found\n * @returns Tuple of collection and options\n */\n getCollection(name) {\n const { collection, options } = this.getCollectionProperties(name);\n return [collection, options];\n }\n /**\n * Gets collection options by name\n * @param name Name of the collection\n * @throws {Error} Will throw an error if the name wasn't found\n * @returns An object of all properties of the collection\n */\n getCollectionProperties(name) {\n const collectionParameters = this.collections.get(name);\n if (collectionParameters == null)\n throw new Error(`Collection with id '${name}' not found`);\n return collectionParameters;\n }\n /**\n * Adds a collection to the sync manager.\n * @param collection Collection to add\n * @param options Options for the collection. The object needs at least a `name` property.\n * @param options.name Unique name of the collection\n */\n addCollection(collection, options) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n this.collections.set(options.name, {\n collection: collection,\n options,\n readyPromise: collection.ready(),\n syncPaused: true, // always start paused as the autostart will start it\n });\n const hasRemoteChange = (change) => {\n for (const remoteChange of this.remoteChanges) {\n if (remoteChange == null)\n continue;\n if (remoteChange.collectionName !== change.collectionName)\n continue;\n if (remoteChange.type !== change.type)\n continue;\n if (change.type === 'remove' && remoteChange.data !== change.data)\n continue;\n if (remoteChange.data.id !== change.data.id)\n continue;\n return true;\n }\n return false;\n };\n const removeRemoteChanges = (collectionName, id) => {\n const newRemoteChanges = [...this.remoteChanges];\n for (let i = 0; i < newRemoteChanges.length; i += 1) {\n const item = newRemoteChanges[i];\n if (item == null)\n continue;\n if (item.collectionName !== collectionName)\n continue;\n if (item.type === 'remove' && item.data !== id)\n continue;\n if (item.data.id !== id)\n continue;\n newRemoteChanges[i] = null;\n }\n this.remoteChanges = newRemoteChanges.filter(item => item != null);\n };\n collection.on('added', (item) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'insert', data: item })) {\n removeRemoteChanges(options.name, item.id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'insert',\n data: item,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n collection.on('changed', ({ id }, modifier) => {\n const data = { id, modifier };\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'update', data })) {\n removeRemoteChanges(options.name, id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'update',\n data,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n collection.on('removed', ({ id }) => {\n // skip the change if it was a remote change\n if (hasRemoteChange({ collectionName: options.name, type: 'remove', data: id })) {\n removeRemoteChanges(options.name, id);\n return;\n }\n this.changes.insert({\n collectionName: options.name,\n time: Date.now(),\n type: 'remove',\n data: id,\n }).then(() => {\n if (this.getCollectionProperties(options.name).syncPaused)\n return;\n this.schedulePush(options.name);\n }).catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n });\n if (this.options.autostart) {\n this.startSync(options.name)\n .catch((error) => {\n if (!this.options.onError)\n return;\n this.options.onError(this.getCollectionProperties(options.name).options, error);\n });\n }\n }\n flushScheduledPushes() {\n this.scheduledPushes.forEach((name) => {\n this.pushChanges(name).catch(() => { });\n });\n this.scheduledPushes.clear();\n }\n schedulePush(name) {\n this.scheduledPushes.add(name);\n this.debouncedFlush();\n }\n /**\n * Setup all collections to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n */\n async startAll() {\n await Promise.all([...this.collections.keys()].map(id => this.startSync(id)));\n }\n /**\n * Setup a collection to be synced with remote changes\n * and enable automatic pushing changes to the remote source.\n * @param name Name of the collection\n */\n async startSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (!collectionParameters.syncPaused)\n return; // already started\n this.schedulePush(name); // push changes that were made while paused\n const cleanupFunction = this.options.registerRemoteChange\n ? await this.options.registerRemoteChange(collectionParameters.options, async (data) => {\n await (data == null\n ? this.sync(name)\n : this.getSyncQueue(name).add(async () => {\n const syncTime = Date.now();\n const syncId = await this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n await this.syncWithData(name, data)\n .then(async () => {\n // clean up old sync operations\n await this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n })\n .catch(async (error) => {\n if (this.options.onError) {\n this.options.onError(this.getCollectionProperties(name).options, error);\n }\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n throw error;\n });\n }));\n })\n : undefined;\n this.collections.set(name, {\n ...collectionParameters,\n syncPaused: false,\n cleanupFunction,\n });\n }\n /**\n * Pauses the sync process for all collections.\n * This means that the collections will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n */\n async pauseAll() {\n await Promise.all([...this.collections.keys()].map(id => this.pauseSync(id)));\n }\n /**\n * Pauses the sync process for a collection.\n * This means that the collection will not be synced with remote changes\n * and changes will not automatically be pushed to the remote source.\n * @param name Name of the collection\n */\n async pauseSync(name) {\n const collectionParameters = this.getCollectionProperties(name);\n if (collectionParameters.syncPaused)\n return; // already paused\n if (collectionParameters.cleanupFunction)\n await collectionParameters.cleanupFunction();\n this.collections.set(name, {\n ...collectionParameters,\n cleanupFunction: undefined,\n syncPaused: true,\n });\n }\n /**\n * Starts the sync process for all collections\n */\n async syncAll() {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n const errors = [];\n await Promise.all([...this.collections.keys()].map(id => this.sync(id).catch((error) => {\n errors.push({ id, error });\n })));\n if (errors.length > 0)\n throw new Error(`Error while syncing collections:\\n${errors.map(error => `${error.id}: ${error.error.message}`).join('\\n\\n')}`);\n }\n isSyncing(name, async) {\n const itemOrPromise = this.syncOperations.findOne({\n ...name ? { collectionName: name } : {},\n status: 'active',\n }, { fields: { status: 1 }, async });\n if (itemOrPromise instanceof Promise) {\n return itemOrPromise\n .then(item => item != null);\n }\n return (itemOrPromise != null);\n }\n /**\n * Checks if the sync manager is ready to sync.\n * @returns A promise that resolves when the sync manager is ready to sync.\n */\n async isReady() {\n await this.collectionsReady;\n }\n /**\n * Starts the sync process for a collection\n * @param name Name of the collection\n * @param options Options for the sync process.\n * @param options.force If true, the sync process will be started even if there are no changes and onlyWithChanges is true.\n * @param options.onlyWithChanges If true, the sync process will only be started if there are changes.\n */\n async sync(name, options = {}) {\n if (this.isDisposed)\n throw new Error('SyncManager is disposed');\n await this.isReady();\n const { options: collectionOptions, readyPromise } = this.getCollectionProperties(name);\n await readyPromise;\n const hasActiveSyncs = await this.syncOperations.find({\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n }, {\n reactive: false,\n async: true,\n }).count() > 0;\n const syncTime = Date.now();\n let syncId = null;\n // schedule for next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const doSync = async () => {\n const lastFinishedSync = await this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n async: true,\n });\n if (options?.onlyWithChanges) {\n const currentChanges = await this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n async: true,\n }).count();\n if (currentChanges === 0)\n return;\n }\n if (!hasActiveSyncs) {\n syncId = await this.syncOperations.insert({\n start: syncTime,\n collectionName: name,\n instanceId: this.instanceId,\n status: 'active',\n });\n }\n const data = await this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n });\n await this.syncWithData(name, data);\n };\n await (options?.force ? doSync() : this.getSyncQueue(name).add(doSync))\n .catch(async (error) => {\n if (syncId != null) {\n if (this.options.onError)\n this.options.onError(collectionOptions, error);\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'error', end: Date.now(), error: error.stack || error.message },\n });\n }\n throw error;\n });\n if (syncId != null) {\n // clean up old sync operations\n await this.syncOperations.removeMany({\n id: { $ne: syncId },\n collectionName: name,\n $or: [\n { end: { $lte: syncTime } },\n { status: 'active' },\n ],\n });\n // update sync operation status to done after everthing was finished\n await this.syncOperations.updateOne({ id: syncId }, {\n $set: { status: 'done', end: Date.now() },\n });\n }\n }\n /**\n * Starts the push process for a collection (sync process but only if there are changes)\n * @param name Name of the collection\n */\n async pushChanges(name) {\n await this.sync(name, {\n onlyWithChanges: true,\n });\n }\n async syncWithData(name, data) {\n const { collection, options: collectionOptions } = this.getCollectionProperties(name);\n const syncTime = Date.now();\n const lastFinishedSync = await this.syncOperations.findOne({\n collectionName: name,\n status: 'done',\n }, {\n sort: { end: -1 },\n reactive: false,\n async: true,\n });\n const lastSnapshot = await this.snapshots.findOne({\n collectionName: name,\n }, {\n sort: { time: -1 },\n reactive: false,\n async: true,\n });\n const currentChanges = await this.changes.find({\n collectionName: name,\n time: { $lte: syncTime },\n }, {\n sort: { time: 1 },\n reactive: false,\n async: true,\n }).fetch();\n await sync({\n changes: currentChanges,\n lastSnapshot: lastSnapshot?.items,\n data,\n pull: () => this.options.pull(collectionOptions, {\n lastFinishedSyncStart: lastFinishedSync?.start,\n lastFinishedSyncEnd: lastFinishedSync?.end,\n }),\n push: changes => this.options.push(collectionOptions, {\n changes,\n rawChanges: currentChanges,\n }),\n insert: async (item) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n }, {\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // replace the item\n await collection.replaceOne({ id: item.id }, item, { upsert: true });\n },\n update: async (itemId, modifier) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: { id: itemId, ...modifier.$set },\n }, {\n collectionName: name,\n type: 'update',\n data: { id: itemId, modifier },\n });\n await collection.updateOne({ id: itemId }, {\n ...modifier,\n $setOnInsert: { id: itemId },\n }, { upsert: true });\n },\n remove: async (itemId) => {\n const itemExists = await collection.find({\n id: itemId,\n }, { reactive: false, async: true }).count() > 0;\n if (!itemExists)\n return;\n this.remoteChanges.push({\n collectionName: name,\n type: 'remove',\n data: itemId,\n });\n await collection.removeOne({ id: itemId });\n },\n batch: async (fn) => {\n return collection.batch(async () => {\n await fn();\n });\n },\n })\n .then(async (snapshot) => {\n // clean up old snapshots\n await this.snapshots.removeMany({\n collectionName: name,\n time: { $lte: syncTime },\n });\n // clean up processed changes\n await this.changes.removeMany({\n collectionName: name,\n id: { $in: currentChanges.map(c => c.id) },\n });\n // insert new snapshot\n await this.snapshots.insert({\n time: syncTime,\n collectionName: name,\n items: snapshot,\n });\n // delay sync operation update to next tick to allow other tasks to run first\n await new Promise((resolve) => {\n setTimeout(resolve, 0);\n });\n const hasChanges = await this.changes.find({\n collectionName: name,\n }, { reactive: false, async: true }).count() > 0;\n if (hasChanges) {\n // check if there are unsynced changes to push\n // and sync again if there are any\n await this.sync(name, {\n force: true,\n onlyWithChanges: true,\n });\n return;\n }\n // if there are no unsynced changes apply the last snapshot\n // to make sure that collection and snapshot are in sync\n // find all items that are not in the snapshot\n const nonExistingItemIds = await collection.find({\n id: { $nin: snapshot.map(item => item.id) },\n }, {\n reactive: false,\n async: true,\n }).map(item => item.id);\n await collection.batch(async () => {\n // update all items that are in the snapshot\n await Promise.all(snapshot.map(async (item) => {\n // add multiple remote changes as we don't know if the item will be updated or inserted during replace\n this.remoteChanges.push({\n collectionName: name,\n type: 'insert',\n data: item,\n }, {\n collectionName: name,\n type: 'update',\n data: { id: item.id, modifier: { $set: item } },\n });\n // replace the item\n await collection.replaceOne({ id: item.id }, item, { upsert: true });\n }));\n // remove all items that are not in the snapshot\n await Promise.all(nonExistingItemIds.map(async (id) => {\n await collection.removeOne({ id });\n }));\n });\n });\n }\n}\n"],"names":["debounce","fn","wait","options","timeout","result","leading","trailing","debounced","args","shouldCallImmediately","shouldCallTrailing","PromiseQueue","task","resolve","reject","error","computeModifiedFields","oldItem","newItem","modifiedFields","oldKeys","newKeys","allKeys","key","nestedModifiedFields","nestedField","computeChanges","oldItems","newItems","added","modified","removed","oldItemsMap","item","newItemsMap","id","isEqual","getSnapshot","lastSnapshot","data","items","index","i","applyChanges","changes","itemMap","change","existingItem","modify","hasChanges","hasDifference","sync","pull","push","insert","update","remove","batch","newData","previousSnapshot","newSnapshot","lastSnapshotWithChanges","newSnapshotWithChanges","changesToPush","newChanges","SyncManager","randomId","reactivity","dataAdapter","DefaultDataAdapter","Collection","readiness","name","collection","collectionParameters","hasRemoteChange","remoteChange","removeRemoteChanges","collectionName","newRemoteChanges","modifier","cleanupFunction","syncTime","syncId","errors","async","itemOrPromise","collectionOptions","readyPromise","hasActiveSyncs","doSync","lastFinishedSync","currentChanges","itemId","snapshot","c","nonExistingItemIds"],"mappings":"qRASA,SAAwBA,EAASC,EAAIC,EAAMC,EAAU,CAAA,EAAI,CACrD,IAAIC,EACAC,E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MAAM,IAAI,QAASjF,GAAY,CAC3B,WAAWA,EAAS,CAAC,CACzB,CAAC,EACkB,MAAM,KAAK,QAAQ,KAAK,CACvC,eAAgB2D,CAAA,EACjB,CAAE,SAAU,GAAO,MAAO,GAAM,EAAE,MAAA,EAAU,EAC/B,CAGZ,MAAM,KAAK,KAAKA,EAAM,CAClB,MAAO,GACP,gBAAiB,EAAA,CACpB,EACD,MACJ,CAIA,MAAMwB,EAAqB,MAAMvB,EAAW,KAAK,CAC7C,GAAI,CAAE,KAAMqB,EAAS,IAAI7D,GAAQA,EAAK,EAAE,CAAA,CAAE,EAC3C,CACC,SAAU,GACV,MAAO,EAAA,CACV,EAAE,IAAIA,GAAQA,EAAK,EAAE,EACtB,MAAMwC,EAAW,MAAM,SAAY,CAE/B,MAAM,QAAQ,IAAIqB,EAAS,IAAI,MAAO7D,GAAS,CAE3C,KAAK,cAAc,KAAK,CACpB,eAAgBuC,EAChB,KAAM,SACN,KAAMvC,CAAA,EACP,CACC,eAAgBuC,EAChB,KAAM,SACN,KAAM,CAAE,GAAIvC,EAAK,GAAI,SAAU,CAAE,KAAMA,CAAA,CAAK,CAAE,CACjD,EAED,MAAMwC,EAAW,WAAW,CAAE,GAAIxC,EAAK,EAAA,EAAMA,EAAM,CAAE,OAAQ,GAAM,CACvE,CAAC,CAAC,EAEF,MAAM,QAAQ,IAAI+D,EAAmB,IAAI,MAAO7D,GAAO,CACnD,MAAMsC,EAAW,UAAU,CAAE,GAAAtC,EAAI,CACrC,CAAC,CAAC,CACN,CAAC,CACL,CAAC,CACL,CACJ"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@signaldb/sync",
|
|
3
|
-
"version": "2.0.0-beta.
|
|
3
|
+
"version": "2.0.0-beta.6",
|
|
4
4
|
"description": "",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"build": "rimraf dist && vite build",
|
|
@@ -54,6 +54,6 @@
|
|
|
54
54
|
"dist"
|
|
55
55
|
],
|
|
56
56
|
"peerDependencies": {
|
|
57
|
-
"@signaldb/core": "^2.0.0-beta.
|
|
57
|
+
"@signaldb/core": "^2.0.0-beta.6"
|
|
58
58
|
}
|
|
59
59
|
}
|