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zB,OAAO,IAAIwS,GAAWhB,EACxB,EA3ZuB1X,GAAW,IAAImZ,GAAWqL,GAAkBxkB,EAAQ8F,UAAU,GAAI9F,EAAQkG,OAAO,KAy1CtG,KAAQ,IAAoB,EAAI,EACjC,OAOKsE,WAAayZ,GACjB,IAAIljB,SAAW,CACb,MAAO,EACT,CAEAG,QAAU,CAAC,CAMX0O,UAAW/R,CAAK,CAAE,QAChB,IAAQ,CAACvB,WAAW,GAAKuB,EAAMvB,WAAW,GAG1C,IAAI,CAACiB,MAAM,EAAIM,EAAMN,MAAM,CACpB,GACT,CAMA2O,UAAWrP,CAAW,CAAEgP,CAAM,CAAE,CAE9B,IAAoB,EACtB,CAMApC,MAAOnK,CAAO,CAAEuM,CAAM,CAAE,CACtBvM,EAAQwI,SAAS,CAtCO,IAwCxB,IAAqB,CAACxI,EAAQC,WAAW,CAAE,IAAI,CAAChC,MAAM,CAAGsO,EAC3D,CAOAG,WAAYnP,CAAW,CAAEO,CAAK,CAAE,CAC9B,OAAO,IACT,CACF,CAKA,IAAM0oB,GAA0B,oBAAOC,WACnCA,WACA,oBAAOC,OACLA,OAEA,oBAAOC,OAAyBA,OAAS,CAAC,EAE1CC,GAAmB,aAEK,MAA1BJ,EAAG,CAACI,GAAiB,EAevBtY,QAAQC,KAAK,CAAC,6HAEhBiY,EAAG,CAACI,GAAiB,CAAG,E","sources":["webpack://@affine/web/../../../node_modules/yjs/dist/yjs.mjs"],"sourcesContent":["import { ObservableV2 } from 'lib0/observable';\nimport * as array from 'lib0/array';\nimport * as math from 'lib0/math';\nimport * as map from 'lib0/map';\nimport * as encoding from 'lib0/encoding';\nimport * as decoding from 'lib0/decoding';\nimport * as random from 'lib0/random';\nimport * as promise from 'lib0/promise';\nimport * as buffer from 'lib0/buffer';\nimport * as error from 'lib0/error';\nimport * as binary from 'lib0/binary';\nimport * as f from 'lib0/function';\nimport { callAll } from 'lib0/function';\nimport * as set from 'lib0/set';\nimport * as logging from 'lib0/logging';\nimport * as time from 'lib0/time';\nimport * as string from 'lib0/string';\nimport * as iterator from 'lib0/iterator';\nimport * as object from 'lib0/object';\n\n/**\n * This is an abstract interface that all Connectors should implement to keep them interchangeable.\n *\n * @note This interface is experimental and it is not advised to actually inherit this class.\n * It just serves as typing information.\n *\n * @extends {ObservableV2}\n */\nclass AbstractConnector extends ObservableV2 {\n /**\n * @param {Doc} ydoc\n * @param {any} awareness\n */\n constructor (ydoc, awareness) {\n super();\n this.doc = ydoc;\n this.awareness = awareness;\n }\n}\n\nclass DeleteItem {\n /**\n * @param {number} clock\n * @param {number} len\n */\n constructor (clock, len) {\n /**\n * @type {number}\n */\n this.clock = clock;\n /**\n * @type {number}\n */\n this.len = len;\n }\n}\n\n/**\n * We no longer maintain a DeleteStore. DeleteSet is a temporary object that is created when needed.\n * - When created in a transaction, it must only be accessed after sorting, and merging\n * - This DeleteSet is send to other clients\n * - We do not create a DeleteSet when we send a sync message. The DeleteSet message is created directly from StructStore\n * - We read a DeleteSet as part of a sync/update message. In this case the DeleteSet is already sorted and merged.\n */\nclass DeleteSet {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map();\n }\n}\n\n/**\n * Iterate over all structs that the DeleteSet gc's.\n *\n * @param {Transaction} transaction\n * @param {DeleteSet} ds\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nconst iterateDeletedStructs = (transaction, ds, f) =>\n ds.clients.forEach((deletes, clientid) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(clientid));\n for (let i = 0; i < deletes.length; i++) {\n const del = deletes[i];\n iterateStructs(transaction, structs, del.clock, del.len, f);\n }\n });\n\n/**\n * @param {Array} dis\n * @param {number} clock\n * @return {number|null}\n *\n * @private\n * @function\n */\nconst findIndexDS = (dis, clock) => {\n let left = 0;\n let right = dis.length - 1;\n while (left <= right) {\n const midindex = math.floor((left + right) / 2);\n const mid = dis[midindex];\n const midclock = mid.clock;\n if (midclock <= clock) {\n if (clock < midclock + mid.len) {\n return midindex\n }\n left = midindex + 1;\n } else {\n right = midindex - 1;\n }\n }\n return null\n};\n\n/**\n * @param {DeleteSet} ds\n * @param {ID} id\n * @return {boolean}\n *\n * @private\n * @function\n */\nconst isDeleted = (ds, id) => {\n const dis = ds.clients.get(id.client);\n return dis !== undefined && findIndexDS(dis, id.clock) !== null\n};\n\n/**\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nconst sortAndMergeDeleteSet = ds => {\n ds.clients.forEach(dels => {\n dels.sort((a, b) => a.clock - b.clock);\n // merge items without filtering or splicing the array\n // i is the current pointer\n // j refers to the current insert position for the pointed item\n // try to merge dels[i] into dels[j-1] or set dels[j]=dels[i]\n let i, j;\n for (i = 1, j = 1; i < dels.length; i++) {\n const left = dels[j - 1];\n const right = dels[i];\n if (left.clock + left.len >= right.clock) {\n left.len = math.max(left.len, right.clock + right.len - left.clock);\n } else {\n if (j < i) {\n dels[j] = right;\n }\n j++;\n }\n }\n dels.length = j;\n });\n};\n\n/**\n * @param {Array} dss\n * @return {DeleteSet} A fresh DeleteSet\n */\nconst mergeDeleteSets = dss => {\n const merged = new DeleteSet();\n for (let dssI = 0; dssI < dss.length; dssI++) {\n dss[dssI].clients.forEach((delsLeft, client) => {\n if (!merged.clients.has(client)) {\n // Write all missing keys from current ds and all following.\n // If merged already contains `client` current ds has already been added.\n /**\n * @type {Array}\n */\n const dels = delsLeft.slice();\n for (let i = dssI + 1; i < dss.length; i++) {\n array.appendTo(dels, dss[i].clients.get(client) || []);\n }\n merged.clients.set(client, dels);\n }\n });\n }\n sortAndMergeDeleteSet(merged);\n return merged\n};\n\n/**\n * @param {DeleteSet} ds\n * @param {number} client\n * @param {number} clock\n * @param {number} length\n *\n * @private\n * @function\n */\nconst addToDeleteSet = (ds, client, clock, length) => {\n map.setIfUndefined(ds.clients, client, () => /** @type {Array} */ ([])).push(new DeleteItem(clock, length));\n};\n\nconst createDeleteSet = () => new DeleteSet();\n\n/**\n * @param {StructStore} ss\n * @return {DeleteSet} Merged and sorted DeleteSet\n *\n * @private\n * @function\n */\nconst createDeleteSetFromStructStore = ss => {\n const ds = createDeleteSet();\n ss.clients.forEach((structs, client) => {\n /**\n * @type {Array}\n */\n const dsitems = [];\n for (let i = 0; i < structs.length; i++) {\n const struct = structs[i];\n if (struct.deleted) {\n const clock = struct.id.clock;\n let len = struct.length;\n if (i + 1 < structs.length) {\n for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) {\n len += next.length;\n }\n }\n dsitems.push(new DeleteItem(clock, len));\n }\n }\n if (dsitems.length > 0) {\n ds.clients.set(client, dsitems);\n }\n });\n return ds\n};\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {DeleteSet} ds\n *\n * @private\n * @function\n */\nconst writeDeleteSet = (encoder, ds) => {\n encoding.writeVarUint(encoder.restEncoder, ds.clients.size);\n\n // Ensure that the delete set is written in a deterministic order\n array.from(ds.clients.entries())\n .sort((a, b) => b[0] - a[0])\n .forEach(([client, dsitems]) => {\n encoder.resetDsCurVal();\n encoding.writeVarUint(encoder.restEncoder, client);\n const len = dsitems.length;\n encoding.writeVarUint(encoder.restEncoder, len);\n for (let i = 0; i < len; i++) {\n const item = dsitems[i];\n encoder.writeDsClock(item.clock);\n encoder.writeDsLen(item.len);\n }\n });\n};\n\n/**\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @return {DeleteSet}\n *\n * @private\n * @function\n */\nconst readDeleteSet = decoder => {\n const ds = new DeleteSet();\n const numClients = decoding.readVarUint(decoder.restDecoder);\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal();\n const client = decoding.readVarUint(decoder.restDecoder);\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder);\n if (numberOfDeletes > 0) {\n const dsField = map.setIfUndefined(ds.clients, client, () => /** @type {Array} */ ([]));\n for (let i = 0; i < numberOfDeletes; i++) {\n dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()));\n }\n }\n }\n return ds\n};\n\n/**\n * @todo YDecoder also contains references to String and other Decoders. Would make sense to exchange YDecoder.toUint8Array for YDecoder.DsToUint8Array()..\n */\n\n/**\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {Uint8Array|null} Returns a v2 update containing all deletes that couldn't be applied yet; or null if all deletes were applied successfully.\n *\n * @private\n * @function\n */\nconst readAndApplyDeleteSet = (decoder, transaction, store) => {\n const unappliedDS = new DeleteSet();\n const numClients = decoding.readVarUint(decoder.restDecoder);\n for (let i = 0; i < numClients; i++) {\n decoder.resetDsCurVal();\n const client = decoding.readVarUint(decoder.restDecoder);\n const numberOfDeletes = decoding.readVarUint(decoder.restDecoder);\n const structs = store.clients.get(client) || [];\n const state = getState(store, client);\n for (let i = 0; i < numberOfDeletes; i++) {\n const clock = decoder.readDsClock();\n const clockEnd = clock + decoder.readDsLen();\n if (clock < state) {\n if (state < clockEnd) {\n addToDeleteSet(unappliedDS, client, state, clockEnd - state);\n }\n let index = findIndexSS(structs, clock);\n /**\n * We can ignore the case of GC and Delete structs, because we are going to skip them\n * @type {Item}\n */\n // @ts-ignore\n let struct = structs[index];\n // split the first item if necessary\n if (!struct.deleted && struct.id.clock < clock) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));\n index++; // increase we now want to use the next struct\n }\n while (index < structs.length) {\n // @ts-ignore\n struct = structs[index++];\n if (struct.id.clock < clockEnd) {\n if (!struct.deleted) {\n if (clockEnd < struct.id.clock + struct.length) {\n structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock));\n }\n struct.delete(transaction);\n }\n } else {\n break\n }\n }\n } else {\n addToDeleteSet(unappliedDS, client, clock, clockEnd - clock);\n }\n }\n }\n if (unappliedDS.clients.size > 0) {\n const ds = new UpdateEncoderV2();\n encoding.writeVarUint(ds.restEncoder, 0); // encode 0 structs\n writeDeleteSet(ds, unappliedDS);\n return ds.toUint8Array()\n }\n return null\n};\n\n/**\n * @param {DeleteSet} ds1\n * @param {DeleteSet} ds2\n */\nconst equalDeleteSets = (ds1, ds2) => {\n if (ds1.clients.size !== ds2.clients.size) return false\n for (const [client, deleteItems1] of ds1.clients.entries()) {\n const deleteItems2 = /** @type {Array} */ (ds2.clients.get(client));\n if (deleteItems2 === undefined || deleteItems1.length !== deleteItems2.length) return false\n for (let i = 0; i < deleteItems1.length; i++) {\n const di1 = deleteItems1[i];\n const di2 = deleteItems2[i];\n if (di1.clock !== di2.clock || di1.len !== di2.len) {\n return false\n }\n }\n }\n return true\n};\n\n/**\n * @module Y\n */\n\n\nconst generateNewClientId = random.uint53;\n\n/**\n * @typedef {Object} DocOpts\n * @property {boolean} [DocOpts.gc=true] Disable garbage collection (default: gc=true)\n * @property {function(Item):boolean} [DocOpts.gcFilter] Will be called before an Item is garbage collected. Return false to keep the Item.\n * @property {string} [DocOpts.guid] Define a globally unique identifier for this document\n * @property {string | null} [DocOpts.collectionid] Associate this document with a collection. This only plays a role if your provider has a concept of collection.\n * @property {any} [DocOpts.meta] Any kind of meta information you want to associate with this document. If this is a subdocument, remote peers will store the meta information as well.\n * @property {boolean} [DocOpts.autoLoad] If a subdocument, automatically load document. If this is a subdocument, remote peers will load the document as well automatically.\n * @property {boolean} [DocOpts.shouldLoad] Whether the document should be synced by the provider now. This is toggled to true when you call ydoc.load()\n */\n\n/**\n * @typedef {Object} DocEvents\n * @property {function(Doc):void} DocEvents.destroy\n * @property {function(Doc):void} DocEvents.load\n * @property {function(boolean, Doc):void} DocEvents.sync\n * @property {function(Uint8Array, any, Doc, Transaction):void} DocEvents.update\n * @property {function(Uint8Array, any, Doc, Transaction):void} DocEvents.updateV2\n * @property {function(Doc):void} DocEvents.beforeAllTransactions\n * @property {function(Transaction, Doc):void} DocEvents.beforeTransaction\n * @property {function(Transaction, Doc):void} DocEvents.beforeObserverCalls\n * @property {function(Transaction, Doc):void} DocEvents.afterTransaction\n * @property {function(Transaction, Doc):void} DocEvents.afterTransactionCleanup\n * @property {function(Doc, Array):void} DocEvents.afterAllTransactions\n * @property {function({ loaded: Set, added: Set, removed: Set }, Doc, Transaction):void} DocEvents.subdocs\n */\n\n/**\n * A Yjs instance handles the state of shared data.\n * @extends ObservableV2\n */\nclass Doc extends ObservableV2 {\n /**\n * @param {DocOpts} opts configuration\n */\n constructor ({ guid = random.uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) {\n super();\n this.gc = gc;\n this.gcFilter = gcFilter;\n this.clientID = generateNewClientId();\n this.guid = guid;\n this.collectionid = collectionid;\n /**\n * @type {Map>>}\n */\n this.share = new Map();\n this.store = new StructStore();\n /**\n * @type {Transaction | null}\n */\n this._transaction = null;\n /**\n * @type {Array}\n */\n this._transactionCleanups = [];\n /**\n * @type {Set}\n */\n this.subdocs = new Set();\n /**\n * If this document is a subdocument - a document integrated into another document - then _item is defined.\n * @type {Item?}\n */\n this._item = null;\n this.shouldLoad = shouldLoad;\n this.autoLoad = autoLoad;\n this.meta = meta;\n /**\n * This is set to true when the persistence provider loaded the document from the database or when the `sync` event fires.\n * Note that not all providers implement this feature. Provider authors are encouraged to fire the `load` event when the doc content is loaded from the database.\n *\n * @type {boolean}\n */\n this.isLoaded = false;\n /**\n * This is set to true when the connection provider has successfully synced with a backend.\n * Note that when using peer-to-peer providers this event may not provide very useful.\n * Also note that not all providers implement this feature. Provider authors are encouraged to fire\n * the `sync` event when the doc has been synced (with `true` as a parameter) or if connection is\n * lost (with false as a parameter).\n */\n this.isSynced = false;\n /**\n * Promise that resolves once the document has been loaded from a presistence provider.\n */\n this.whenLoaded = promise.create(resolve => {\n this.on('load', () => {\n this.isLoaded = true;\n resolve(this);\n });\n });\n const provideSyncedPromise = () => promise.create(resolve => {\n /**\n * @param {boolean} isSynced\n */\n const eventHandler = (isSynced) => {\n if (isSynced === undefined || isSynced === true) {\n this.off('sync', eventHandler);\n resolve();\n }\n };\n this.on('sync', eventHandler);\n });\n this.on('sync', isSynced => {\n if (isSynced === false && this.isSynced) {\n this.whenSynced = provideSyncedPromise();\n }\n this.isSynced = isSynced === undefined || isSynced === true;\n if (this.isSynced && !this.isLoaded) {\n this.emit('load', [this]);\n }\n });\n /**\n * Promise that resolves once the document has been synced with a backend.\n * This promise is recreated when the connection is lost.\n * Note the documentation about the `isSynced` property.\n */\n this.whenSynced = provideSyncedPromise();\n }\n\n /**\n * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).\n *\n * `load()` might be used in the future to request any provider to load the most current data.\n *\n * It is safe to call `load()` multiple times.\n */\n load () {\n const item = this._item;\n if (item !== null && !this.shouldLoad) {\n transact(/** @type {any} */ (item.parent).doc, transaction => {\n transaction.subdocsLoaded.add(this);\n }, null, true);\n }\n this.shouldLoad = true;\n }\n\n getSubdocs () {\n return this.subdocs\n }\n\n getSubdocGuids () {\n return new Set(array.from(this.subdocs).map(doc => doc.guid))\n }\n\n /**\n * Changes that happen inside of a transaction are bundled. This means that\n * the observer fires _after_ the transaction is finished and that all changes\n * that happened inside of the transaction are sent as one message to the\n * other peers.\n *\n * @template T\n * @param {function(Transaction):T} f The function that should be executed as a transaction\n * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin\n * @return T\n *\n * @public\n */\n transact (f, origin = null) {\n return transact(this, f, origin)\n }\n\n /**\n * Define a shared data type.\n *\n * Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result\n * and do not overwrite each other. I.e.\n * `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)`\n *\n * After this method is called, the type is also available on `ydoc.share.get(name)`.\n *\n * *Best Practices:*\n * Define all types right after the Y.Doc instance is created and store them in a separate object.\n * Also use the typed methods `getText(name)`, `getArray(name)`, ..\n *\n * @template {typeof AbstractType} Type\n * @example\n * const ydoc = new Y.Doc(..)\n * const appState = {\n * document: ydoc.getText('document')\n * comments: ydoc.getArray('comments')\n * }\n *\n * @param {string} name\n * @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...\n * @return {InstanceType} The created type. Constructed with TypeConstructor\n *\n * @public\n */\n get (name, TypeConstructor = /** @type {any} */ (AbstractType)) {\n const type = map.setIfUndefined(this.share, name, () => {\n // @ts-ignore\n const t = new TypeConstructor();\n t._integrate(this, null);\n return t\n });\n const Constr = type.constructor;\n if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {\n if (Constr === AbstractType) {\n // @ts-ignore\n const t = new TypeConstructor();\n t._map = type._map;\n type._map.forEach(/** @param {Item?} n */ n => {\n for (; n !== null; n = n.left) {\n // @ts-ignore\n n.parent = t;\n }\n });\n t._start = type._start;\n for (let n = t._start; n !== null; n = n.right) {\n n.parent = t;\n }\n t._length = type._length;\n this.share.set(name, t);\n t._integrate(this, null);\n return /** @type {InstanceType} */ (t)\n } else {\n throw new Error(`Type with the name ${name} has already been defined with a different constructor`)\n }\n }\n return /** @type {InstanceType} */ (type)\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YArray}\n *\n * @public\n */\n getArray (name = '') {\n return /** @type {YArray} */ (this.get(name, YArray))\n }\n\n /**\n * @param {string} [name]\n * @return {YText}\n *\n * @public\n */\n getText (name = '') {\n return this.get(name, YText)\n }\n\n /**\n * @template T\n * @param {string} [name]\n * @return {YMap}\n *\n * @public\n */\n getMap (name = '') {\n return /** @type {YMap} */ (this.get(name, YMap))\n }\n\n /**\n * @param {string} [name]\n * @return {YXmlElement}\n *\n * @public\n */\n getXmlElement (name = '') {\n return /** @type {YXmlElement<{[key:string]:string}>} */ (this.get(name, YXmlElement))\n }\n\n /**\n * @param {string} [name]\n * @return {YXmlFragment}\n *\n * @public\n */\n getXmlFragment (name = '') {\n return this.get(name, YXmlFragment)\n }\n\n /**\n * Converts the entire document into a js object, recursively traversing each yjs type\n * Doesn't log types that have not been defined (using ydoc.getType(..)).\n *\n * @deprecated Do not use this method and rather call toJSON directly on the shared types.\n *\n * @return {Object}\n */\n toJSON () {\n /**\n * @type {Object}\n */\n const doc = {};\n\n this.share.forEach((value, key) => {\n doc[key] = value.toJSON();\n });\n\n return doc\n }\n\n /**\n * Emit `destroy` event and unregister all event handlers.\n */\n destroy () {\n array.from(this.subdocs).forEach(subdoc => subdoc.destroy());\n const item = this._item;\n if (item !== null) {\n this._item = null;\n const content = /** @type {ContentDoc} */ (item.content);\n content.doc = new Doc({ guid: this.guid, ...content.opts, shouldLoad: false });\n content.doc._item = item;\n transact(/** @type {any} */ (item).parent.doc, transaction => {\n const doc = content.doc;\n if (!item.deleted) {\n transaction.subdocsAdded.add(doc);\n }\n transaction.subdocsRemoved.add(this);\n }, null, true);\n }\n // @ts-ignore\n this.emit('destroyed', [true]); // DEPRECATED!\n this.emit('destroy', [this]);\n super.destroy();\n }\n}\n\nclass DSDecoderV1 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n this.restDecoder = decoder;\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n}\n\nclass UpdateDecoderV1 extends DSDecoderV1 {\n /**\n * @return {ID}\n */\n readLeftID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return createID(decoding.readVarUint(this.restDecoder), decoding.readVarUint(this.restDecoder))\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return decoding.readUint8(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readString () {\n return decoding.readVarString(this.restDecoder)\n }\n\n /**\n * @return {boolean} isKey\n */\n readParentInfo () {\n return decoding.readVarUint(this.restDecoder) === 1\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readTypeRef () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number} len\n */\n readLen () {\n return decoding.readVarUint(this.restDecoder)\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return buffer.copyUint8Array(decoding.readVarUint8Array(this.restDecoder))\n }\n\n /**\n * Legacy implementation uses JSON parse. We use any-decoding in v2.\n *\n * @return {any}\n */\n readJSON () {\n return JSON.parse(decoding.readVarString(this.restDecoder))\n }\n\n /**\n * @return {string}\n */\n readKey () {\n return decoding.readVarString(this.restDecoder)\n }\n}\n\nclass DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n /**\n * @private\n */\n this.dsCurrVal = 0;\n this.restDecoder = decoder;\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0;\n }\n\n /**\n * @return {number}\n */\n readDsClock () {\n this.dsCurrVal += decoding.readVarUint(this.restDecoder);\n return this.dsCurrVal\n }\n\n /**\n * @return {number}\n */\n readDsLen () {\n const diff = decoding.readVarUint(this.restDecoder) + 1;\n this.dsCurrVal += diff;\n return diff\n }\n}\n\nclass UpdateDecoderV2 extends DSDecoderV2 {\n /**\n * @param {decoding.Decoder} decoder\n */\n constructor (decoder) {\n super(decoder);\n /**\n * List of cached keys. If the keys[id] does not exist, we read a new key\n * from stringEncoder and push it to keys.\n *\n * @type {Array}\n */\n this.keys = [];\n decoding.readVarUint(decoder); // read feature flag - currently unused\n this.keyClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder));\n this.clientDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder));\n this.leftClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder));\n this.rightClockDecoder = new decoding.IntDiffOptRleDecoder(decoding.readVarUint8Array(decoder));\n this.infoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8);\n this.stringDecoder = new decoding.StringDecoder(decoding.readVarUint8Array(decoder));\n this.parentInfoDecoder = new decoding.RleDecoder(decoding.readVarUint8Array(decoder), decoding.readUint8);\n this.typeRefDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder));\n this.lenDecoder = new decoding.UintOptRleDecoder(decoding.readVarUint8Array(decoder));\n }\n\n /**\n * @return {ID}\n */\n readLeftID () {\n return new ID(this.clientDecoder.read(), this.leftClockDecoder.read())\n }\n\n /**\n * @return {ID}\n */\n readRightID () {\n return new ID(this.clientDecoder.read(), this.rightClockDecoder.read())\n }\n\n /**\n * Read the next client id.\n * Use this in favor of readID whenever possible to reduce the number of objects created.\n */\n readClient () {\n return this.clientDecoder.read()\n }\n\n /**\n * @return {number} info An unsigned 8-bit integer\n */\n readInfo () {\n return /** @type {number} */ (this.infoDecoder.read())\n }\n\n /**\n * @return {string}\n */\n readString () {\n return this.stringDecoder.read()\n }\n\n /**\n * @return {boolean}\n */\n readParentInfo () {\n return this.parentInfoDecoder.read() === 1\n }\n\n /**\n * @return {number} An unsigned 8-bit integer\n */\n readTypeRef () {\n return this.typeRefDecoder.read()\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @return {number}\n */\n readLen () {\n return this.lenDecoder.read()\n }\n\n /**\n * @return {any}\n */\n readAny () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {Uint8Array}\n */\n readBuf () {\n return decoding.readVarUint8Array(this.restDecoder)\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @return {any}\n */\n readJSON () {\n return decoding.readAny(this.restDecoder)\n }\n\n /**\n * @return {string}\n */\n readKey () {\n const keyClock = this.keyClockDecoder.read();\n if (keyClock < this.keys.length) {\n return this.keys[keyClock]\n } else {\n const key = this.stringDecoder.read();\n this.keys.push(key);\n return key\n }\n }\n}\n\nclass DSEncoderV1 {\n constructor () {\n this.restEncoder = encoding.createEncoder();\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n // nop\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n encoding.writeVarUint(this.restEncoder, clock);\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n encoding.writeVarUint(this.restEncoder, len);\n }\n}\n\nclass UpdateEncoderV1 extends DSEncoderV1 {\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n encoding.writeVarUint(this.restEncoder, id.client);\n encoding.writeVarUint(this.restEncoder, id.clock);\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n encoding.writeVarUint(this.restEncoder, id.client);\n encoding.writeVarUint(this.restEncoder, id.clock);\n }\n\n /**\n * Use writeClient and writeClock instead of writeID if possible.\n * @param {number} client\n */\n writeClient (client) {\n encoding.writeVarUint(this.restEncoder, client);\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n encoding.writeUint8(this.restEncoder, info);\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n encoding.writeVarString(this.restEncoder, s);\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n encoding.writeVarUint(this.restEncoder, isYKey ? 1 : 0);\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n encoding.writeVarUint(this.restEncoder, info);\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n encoding.writeVarUint(this.restEncoder, len);\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any);\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf);\n }\n\n /**\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeVarString(this.restEncoder, JSON.stringify(embed));\n }\n\n /**\n * @param {string} key\n */\n writeKey (key) {\n encoding.writeVarString(this.restEncoder, key);\n }\n}\n\nclass DSEncoderV2 {\n constructor () {\n this.restEncoder = encoding.createEncoder(); // encodes all the rest / non-optimized\n this.dsCurrVal = 0;\n }\n\n toUint8Array () {\n return encoding.toUint8Array(this.restEncoder)\n }\n\n resetDsCurVal () {\n this.dsCurrVal = 0;\n }\n\n /**\n * @param {number} clock\n */\n writeDsClock (clock) {\n const diff = clock - this.dsCurrVal;\n this.dsCurrVal = clock;\n encoding.writeVarUint(this.restEncoder, diff);\n }\n\n /**\n * @param {number} len\n */\n writeDsLen (len) {\n if (len === 0) {\n error.unexpectedCase();\n }\n encoding.writeVarUint(this.restEncoder, len - 1);\n this.dsCurrVal += len;\n }\n}\n\nclass UpdateEncoderV2 extends DSEncoderV2 {\n constructor () {\n super();\n /**\n * @type {Map}\n */\n this.keyMap = new Map();\n /**\n * Refers to the next uniqe key-identifier to me used.\n * See writeKey method for more information.\n *\n * @type {number}\n */\n this.keyClock = 0;\n this.keyClockEncoder = new encoding.IntDiffOptRleEncoder();\n this.clientEncoder = new encoding.UintOptRleEncoder();\n this.leftClockEncoder = new encoding.IntDiffOptRleEncoder();\n this.rightClockEncoder = new encoding.IntDiffOptRleEncoder();\n this.infoEncoder = new encoding.RleEncoder(encoding.writeUint8);\n this.stringEncoder = new encoding.StringEncoder();\n this.parentInfoEncoder = new encoding.RleEncoder(encoding.writeUint8);\n this.typeRefEncoder = new encoding.UintOptRleEncoder();\n this.lenEncoder = new encoding.UintOptRleEncoder();\n }\n\n toUint8Array () {\n const encoder = encoding.createEncoder();\n encoding.writeVarUint(encoder, 0); // this is a feature flag that we might use in the future\n encoding.writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array());\n encoding.writeVarUint8Array(encoder, this.clientEncoder.toUint8Array());\n encoding.writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array());\n encoding.writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array());\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.infoEncoder));\n encoding.writeVarUint8Array(encoder, this.stringEncoder.toUint8Array());\n encoding.writeVarUint8Array(encoder, encoding.toUint8Array(this.parentInfoEncoder));\n encoding.writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array());\n encoding.writeVarUint8Array(encoder, this.lenEncoder.toUint8Array());\n // @note The rest encoder is appended! (note the missing var)\n encoding.writeUint8Array(encoder, encoding.toUint8Array(this.restEncoder));\n return encoding.toUint8Array(encoder)\n }\n\n /**\n * @param {ID} id\n */\n writeLeftID (id) {\n this.clientEncoder.write(id.client);\n this.leftClockEncoder.write(id.clock);\n }\n\n /**\n * @param {ID} id\n */\n writeRightID (id) {\n this.clientEncoder.write(id.client);\n this.rightClockEncoder.write(id.clock);\n }\n\n /**\n * @param {number} client\n */\n writeClient (client) {\n this.clientEncoder.write(client);\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeInfo (info) {\n this.infoEncoder.write(info);\n }\n\n /**\n * @param {string} s\n */\n writeString (s) {\n this.stringEncoder.write(s);\n }\n\n /**\n * @param {boolean} isYKey\n */\n writeParentInfo (isYKey) {\n this.parentInfoEncoder.write(isYKey ? 1 : 0);\n }\n\n /**\n * @param {number} info An unsigned 8-bit integer\n */\n writeTypeRef (info) {\n this.typeRefEncoder.write(info);\n }\n\n /**\n * Write len of a struct - well suited for Opt RLE encoder.\n *\n * @param {number} len\n */\n writeLen (len) {\n this.lenEncoder.write(len);\n }\n\n /**\n * @param {any} any\n */\n writeAny (any) {\n encoding.writeAny(this.restEncoder, any);\n }\n\n /**\n * @param {Uint8Array} buf\n */\n writeBuf (buf) {\n encoding.writeVarUint8Array(this.restEncoder, buf);\n }\n\n /**\n * This is mainly here for legacy purposes.\n *\n * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.\n *\n * @param {any} embed\n */\n writeJSON (embed) {\n encoding.writeAny(this.restEncoder, embed);\n }\n\n /**\n * Property keys are often reused. For example, in y-prosemirror the key `bold` might\n * occur very often. For a 3d application, the key `position` might occur very often.\n *\n * We cache these keys in a Map and refer to them via a unique number.\n *\n * @param {string} key\n */\n writeKey (key) {\n const clock = this.keyMap.get(key);\n if (clock === undefined) {\n /**\n * @todo uncomment to introduce this feature finally\n *\n * Background. The ContentFormat object was always encoded using writeKey, but the decoder used to use readString.\n * Furthermore, I forgot to set the keyclock. So everything was working fine.\n *\n * However, this feature here is basically useless as it is not being used (it actually only consumes extra memory).\n *\n * I don't know yet how to reintroduce this feature..\n *\n * Older clients won't be able to read updates when we reintroduce this feature. So this should probably be done using a flag.\n *\n */\n // this.keyMap.set(key, this.keyClock)\n this.keyClockEncoder.write(this.keyClock++);\n this.stringEncoder.write(key);\n } else {\n this.keyClockEncoder.write(clock);\n }\n }\n}\n\n/**\n * @module encoding\n */\n/*\n * We use the first five bits in the info flag for determining the type of the struct.\n *\n * 0: GC\n * 1: Item with Deleted content\n * 2: Item with JSON content\n * 3: Item with Binary content\n * 4: Item with String content\n * 5: Item with Embed content (for richtext content)\n * 6: Item with Format content (a formatting marker for richtext content)\n * 7: Item with Type\n */\n\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Array} structs All structs by `client`\n * @param {number} client\n * @param {number} clock write structs starting with `ID(client,clock)`\n *\n * @function\n */\nconst writeStructs = (encoder, structs, client, clock) => {\n // write first id\n clock = math.max(clock, structs[0].id.clock); // make sure the first id exists\n const startNewStructs = findIndexSS(structs, clock);\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, structs.length - startNewStructs);\n encoder.writeClient(client);\n encoding.writeVarUint(encoder.restEncoder, clock);\n const firstStruct = structs[startNewStructs];\n // write first struct with an offset\n firstStruct.write(encoder, clock - firstStruct.id.clock);\n for (let i = startNewStructs + 1; i < structs.length; i++) {\n structs[i].write(encoder, 0);\n }\n};\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {StructStore} store\n * @param {Map} _sm\n *\n * @private\n * @function\n */\nconst writeClientsStructs = (encoder, store, _sm) => {\n // we filter all valid _sm entries into sm\n const sm = new Map();\n _sm.forEach((clock, client) => {\n // only write if new structs are available\n if (getState(store, client) > clock) {\n sm.set(client, clock);\n }\n });\n getStateVector(store).forEach((_clock, client) => {\n if (!_sm.has(client)) {\n sm.set(client, 0);\n }\n });\n // write # states that were updated\n encoding.writeVarUint(encoder.restEncoder, sm.size);\n // Write items with higher client ids first\n // This heavily improves the conflict algorithm.\n array.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n writeStructs(encoder, /** @type {Array} */ (store.clients.get(client)), client, clock);\n });\n};\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder The decoder object to read data from.\n * @param {Doc} doc\n * @return {Map }>}\n *\n * @private\n * @function\n */\nconst readClientsStructRefs = (decoder, doc) => {\n /**\n * @type {Map }>}\n */\n const clientRefs = map.create();\n const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder);\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = decoding.readVarUint(decoder.restDecoder);\n /**\n * @type {Array}\n */\n const refs = new Array(numberOfStructs);\n const client = decoder.readClient();\n let clock = decoding.readVarUint(decoder.restDecoder);\n // const start = performance.now()\n clientRefs.set(client, { i: 0, refs });\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo();\n switch (binary.BITS5 & info) {\n case 0: { // GC\n const len = decoder.readLen();\n refs[i] = new GC(createID(client, clock), len);\n clock += len;\n break\n }\n case 10: { // Skip Struct (nothing to apply)\n // @todo we could reduce the amount of checks by adding Skip struct to clientRefs so we know that something is missing.\n const len = decoding.readVarUint(decoder.restDecoder);\n refs[i] = new Skip(createID(client, clock), len);\n clock += len;\n break\n }\n default: { // Item with content\n /**\n * The optimized implementation doesn't use any variables because inlining variables is faster.\n * Below a non-optimized version is shown that implements the basic algorithm with\n * a few comments\n */\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0;\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // left\n (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin\n cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n );\n /* A non-optimized implementation of the above algorithm:\n\n // The item that was originally to the left of this item.\n const origin = (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null\n // The item that was originally to the right of this item.\n const rightOrigin = (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0\n const hasParentYKey = cantCopyParentInfo ? decoder.readParentInfo() : false\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const parentYKey = cantCopyParentInfo && hasParentYKey ? decoder.readString() : null\n\n const struct = new Item(\n createID(client, clock),\n null, // left\n origin, // origin\n null, // right\n rightOrigin, // right origin\n cantCopyParentInfo && !hasParentYKey ? decoder.readLeftID() : (parentYKey !== null ? doc.get(parentYKey) : null), // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n )\n */\n refs[i] = struct;\n clock += struct.length;\n }\n }\n }\n // console.log('time to read: ', performance.now() - start) // @todo remove\n }\n return clientRefs\n};\n\n/**\n * Resume computing structs generated by struct readers.\n *\n * While there is something to do, we integrate structs in this order\n * 1. top element on stack, if stack is not empty\n * 2. next element from current struct reader (if empty, use next struct reader)\n *\n * If struct causally depends on another struct (ref.missing), we put next reader of\n * `ref.id.client` on top of stack.\n *\n * At some point we find a struct that has no causal dependencies,\n * then we start emptying the stack.\n *\n * It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2)\n * depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`.\n *\n * This method is implemented in a way so that we can resume computation if this update\n * causally depends on another update.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {Map} clientsStructRefs\n * @return { null | { update: Uint8Array, missing: Map } }\n *\n * @private\n * @function\n */\nconst integrateStructs = (transaction, store, clientsStructRefs) => {\n /**\n * @type {Array}\n */\n const stack = [];\n // sort them so that we take the higher id first, in case of conflicts the lower id will probably not conflict with the id from the higher user.\n let clientsStructRefsIds = array.from(clientsStructRefs.keys()).sort((a, b) => a - b);\n if (clientsStructRefsIds.length === 0) {\n return null\n }\n const getNextStructTarget = () => {\n if (clientsStructRefsIds.length === 0) {\n return null\n }\n let nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]));\n while (nextStructsTarget.refs.length === nextStructsTarget.i) {\n clientsStructRefsIds.pop();\n if (clientsStructRefsIds.length > 0) {\n nextStructsTarget = /** @type {{i:number,refs:Array}} */ (clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]));\n } else {\n return null\n }\n }\n return nextStructsTarget\n };\n let curStructsTarget = getNextStructTarget();\n if (curStructsTarget === null) {\n return null\n }\n\n /**\n * @type {StructStore}\n */\n const restStructs = new StructStore();\n const missingSV = new Map();\n /**\n * @param {number} client\n * @param {number} clock\n */\n const updateMissingSv = (client, clock) => {\n const mclock = missingSV.get(client);\n if (mclock == null || mclock > clock) {\n missingSV.set(client, clock);\n }\n };\n /**\n * @type {GC|Item}\n */\n let stackHead = /** @type {any} */ (curStructsTarget).refs[/** @type {any} */ (curStructsTarget).i++];\n // caching the state because it is used very often\n const state = new Map();\n\n const addStackToRestSS = () => {\n for (const item of stack) {\n const client = item.id.client;\n const unapplicableItems = clientsStructRefs.get(client);\n if (unapplicableItems) {\n // decrement because we weren't able to apply previous operation\n unapplicableItems.i--;\n restStructs.clients.set(client, unapplicableItems.refs.slice(unapplicableItems.i));\n clientsStructRefs.delete(client);\n unapplicableItems.i = 0;\n unapplicableItems.refs = [];\n } else {\n // item was the last item on clientsStructRefs and the field was already cleared. Add item to restStructs and continue\n restStructs.clients.set(client, [item]);\n }\n // remove client from clientsStructRefsIds to prevent users from applying the same update again\n clientsStructRefsIds = clientsStructRefsIds.filter(c => c !== client);\n }\n stack.length = 0;\n };\n\n // iterate over all struct readers until we are done\n while (true) {\n if (stackHead.constructor !== Skip) {\n const localClock = map.setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client));\n const offset = localClock - stackHead.id.clock;\n if (offset < 0) {\n // update from the same client is missing\n stack.push(stackHead);\n updateMissingSv(stackHead.id.client, stackHead.id.clock - 1);\n // hid a dead wall, add all items from stack to restSS\n addStackToRestSS();\n } else {\n const missing = stackHead.getMissing(transaction, store);\n if (missing !== null) {\n stack.push(stackHead);\n // get the struct reader that has the missing struct\n /**\n * @type {{ refs: Array, i: number }}\n */\n const structRefs = clientsStructRefs.get(/** @type {number} */ (missing)) || { refs: [], i: 0 };\n if (structRefs.refs.length === structRefs.i) {\n // This update message causally depends on another update message that doesn't exist yet\n updateMissingSv(/** @type {number} */ (missing), getState(store, missing));\n addStackToRestSS();\n } else {\n stackHead = structRefs.refs[structRefs.i++];\n continue\n }\n } else if (offset === 0 || offset < stackHead.length) {\n // all fine, apply the stackhead\n stackHead.integrate(transaction, offset);\n state.set(stackHead.id.client, stackHead.id.clock + stackHead.length);\n }\n }\n }\n // iterate to next stackHead\n if (stack.length > 0) {\n stackHead = /** @type {GC|Item} */ (stack.pop());\n } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]);\n } else {\n curStructsTarget = getNextStructTarget();\n if (curStructsTarget === null) {\n // we are done!\n break\n } else {\n stackHead = /** @type {GC|Item} */ (curStructsTarget.refs[curStructsTarget.i++]);\n }\n }\n }\n if (restStructs.clients.size > 0) {\n const encoder = new UpdateEncoderV2();\n writeClientsStructs(encoder, restStructs, new Map());\n // write empty deleteset\n // writeDeleteSet(encoder, new DeleteSet())\n encoding.writeVarUint(encoder.restEncoder, 0); // => no need for an extra function call, just write 0 deletes\n return { missing: missingSV, update: encoder.toUint8Array() }\n }\n return null\n};\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Transaction} transaction\n *\n * @private\n * @function\n */\nconst writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState);\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts a decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {UpdateDecoderV1 | UpdateDecoderV2} [structDecoder]\n *\n * @function\n */\nconst readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) =>\n transact(ydoc, transaction => {\n // force that transaction.local is set to non-local\n transaction.local = false;\n let retry = false;\n const doc = transaction.doc;\n const store = doc.store;\n // let start = performance.now()\n const ss = readClientsStructRefs(structDecoder, doc);\n // console.log('time to read structs: ', performance.now() - start) // @todo remove\n // start = performance.now()\n // console.log('time to merge: ', performance.now() - start) // @todo remove\n // start = performance.now()\n const restStructs = integrateStructs(transaction, store, ss);\n const pending = store.pendingStructs;\n if (pending) {\n // check if we can apply something\n for (const [client, clock] of pending.missing) {\n if (clock < getState(store, client)) {\n retry = true;\n break\n }\n }\n if (restStructs) {\n // merge restStructs into store.pending\n for (const [client, clock] of restStructs.missing) {\n const mclock = pending.missing.get(client);\n if (mclock == null || mclock > clock) {\n pending.missing.set(client, clock);\n }\n }\n pending.update = mergeUpdatesV2([pending.update, restStructs.update]);\n }\n } else {\n store.pendingStructs = restStructs;\n }\n // console.log('time to integrate: ', performance.now() - start) // @todo remove\n // start = performance.now()\n const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store);\n if (store.pendingDs) {\n // @todo we could make a lower-bound state-vector check as we do above\n const pendingDSUpdate = new UpdateDecoderV2(decoding.createDecoder(store.pendingDs));\n decoding.readVarUint(pendingDSUpdate.restDecoder); // read 0 structs, because we only encode deletes in pendingdsupdate\n const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store);\n if (dsRest && dsRest2) {\n // case 1: ds1 != null && ds2 != null\n store.pendingDs = mergeUpdatesV2([dsRest, dsRest2]);\n } else {\n // case 2: ds1 != null\n // case 3: ds2 != null\n // case 4: ds1 == null && ds2 == null\n store.pendingDs = dsRest || dsRest2;\n }\n } else {\n // Either dsRest == null && pendingDs == null OR dsRest != null\n store.pendingDs = dsRest;\n }\n // console.log('time to cleanup: ', performance.now() - start) // @todo remove\n // start = performance.now()\n\n // console.log('time to resume delete readers: ', performance.now() - start) // @todo remove\n // start = performance.now()\n if (retry) {\n const update = /** @type {{update: Uint8Array}} */ (store.pendingStructs).update;\n store.pendingStructs = null;\n applyUpdateV2(transaction.doc, update);\n }\n }, transactionOrigin, false);\n\n/**\n * Read and apply a document update.\n *\n * This function has the same effect as `applyUpdate` but accepts a decoder.\n *\n * @param {decoding.Decoder} decoder\n * @param {Doc} ydoc\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nconst readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new UpdateDecoderV1(decoder));\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n *\n * @function\n */\nconst applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {\n const decoder = decoding.createDecoder(update);\n readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder));\n};\n\n/**\n * Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.\n *\n * This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.\n *\n * @param {Doc} ydoc\n * @param {Uint8Array} update\n * @param {any} [transactionOrigin] This will be stored on `transaction.origin` and `.on('update', (update, origin))`\n *\n * @function\n */\nconst applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1);\n\n/**\n * Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will\n * only write the operations that are missing.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Doc} doc\n * @param {Map} [targetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n *\n * @function\n */\nconst writeStateAsUpdate = (encoder, doc, targetStateVector = new Map()) => {\n writeClientsStructs(encoder, doc.store, targetStateVector);\n writeDeleteSet(encoder, createDeleteSetFromStructStore(doc.store));\n};\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @param {UpdateEncoderV1 | UpdateEncoderV2} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nconst encodeStateAsUpdateV2 = (doc, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => {\n const targetStateVector = decodeStateVector(encodedTargetStateVector);\n writeStateAsUpdate(encoder, doc, targetStateVector);\n const updates = [encoder.toUint8Array()];\n // also add the pending updates (if there are any)\n if (doc.store.pendingDs) {\n updates.push(doc.store.pendingDs);\n }\n if (doc.store.pendingStructs) {\n updates.push(diffUpdateV2(doc.store.pendingStructs.update, encodedTargetStateVector));\n }\n if (updates.length > 1) {\n if (encoder.constructor === UpdateEncoderV1) {\n return mergeUpdates(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update)))\n } else if (encoder.constructor === UpdateEncoderV2) {\n return mergeUpdatesV2(updates)\n }\n }\n return updates[0]\n};\n\n/**\n * Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will\n * only write the operations that are missing.\n *\n * Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder\n *\n * @param {Doc} doc\n * @param {Uint8Array} [encodedTargetStateVector] The state of the target that receives the update. Leave empty to write all known structs\n * @return {Uint8Array}\n *\n * @function\n */\nconst encodeStateAsUpdate = (doc, encodedTargetStateVector) => encodeStateAsUpdateV2(doc, encodedTargetStateVector, new UpdateEncoderV1());\n\n/**\n * Read state vector from Decoder and return as Map\n *\n * @param {DSDecoderV1 | DSDecoderV2} decoder\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nconst readStateVector = decoder => {\n const ss = new Map();\n const ssLength = decoding.readVarUint(decoder.restDecoder);\n for (let i = 0; i < ssLength; i++) {\n const client = decoding.readVarUint(decoder.restDecoder);\n const clock = decoding.readVarUint(decoder.restDecoder);\n ss.set(client, clock);\n }\n return ss\n};\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\n// export const decodeStateVectorV2 = decodedState => readStateVector(new DSDecoderV2(decoding.createDecoder(decodedState)))\n\n/**\n * Read decodedState and return State as Map.\n *\n * @param {Uint8Array} decodedState\n * @return {Map} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nconst decodeStateVector = decodedState => readStateVector(new DSDecoderV1(decoding.createDecoder(decodedState)));\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {Map} sv\n * @function\n */\nconst writeStateVector = (encoder, sv) => {\n encoding.writeVarUint(encoder.restEncoder, sv.size);\n array.from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n encoding.writeVarUint(encoder.restEncoder, client); // @todo use a special client decoder that is based on mapping\n encoding.writeVarUint(encoder.restEncoder, clock);\n });\n return encoder\n};\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {Doc} doc\n *\n * @function\n */\nconst writeDocumentStateVector = (encoder, doc) => writeStateVector(encoder, getStateVector(doc.store));\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc|Map} doc\n * @param {DSEncoderV1 | DSEncoderV2} [encoder]\n * @return {Uint8Array}\n *\n * @function\n */\nconst encodeStateVectorV2 = (doc, encoder = new DSEncoderV2()) => {\n if (doc instanceof Map) {\n writeStateVector(encoder, doc);\n } else {\n writeDocumentStateVector(encoder, doc);\n }\n return encoder.toUint8Array()\n};\n\n/**\n * Encode State as Uint8Array.\n *\n * @param {Doc|Map} doc\n * @return {Uint8Array}\n *\n * @function\n */\nconst encodeStateVector = doc => encodeStateVectorV2(doc, new DSEncoderV1());\n\n/**\n * General event handler implementation.\n *\n * @template ARG0, ARG1\n *\n * @private\n */\nclass EventHandler {\n constructor () {\n /**\n * @type {Array}\n */\n this.l = [];\n }\n}\n\n/**\n * @template ARG0,ARG1\n * @returns {EventHandler}\n *\n * @private\n * @function\n */\nconst createEventHandler = () => new EventHandler();\n\n/**\n * Adds an event listener that is called when\n * {@link EventHandler#callEventListeners} is called.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler.\n *\n * @private\n * @function\n */\nconst addEventHandlerListener = (eventHandler, f) =>\n eventHandler.l.push(f);\n\n/**\n * Removes an event listener.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {function(ARG0,ARG1):void} f The event handler that was added with\n * {@link EventHandler#addEventListener}\n *\n * @private\n * @function\n */\nconst removeEventHandlerListener = (eventHandler, f) => {\n const l = eventHandler.l;\n const len = l.length;\n eventHandler.l = l.filter(g => f !== g);\n if (len === eventHandler.l.length) {\n console.error('[yjs] Tried to remove event handler that doesn\\'t exist.');\n }\n};\n\n/**\n * Call all event listeners that were added via\n * {@link EventHandler#addEventListener}.\n *\n * @template ARG0,ARG1\n * @param {EventHandler} eventHandler\n * @param {ARG0} arg0\n * @param {ARG1} arg1\n *\n * @private\n * @function\n */\nconst callEventHandlerListeners = (eventHandler, arg0, arg1) =>\n f.callAll(eventHandler.l, [arg0, arg1]);\n\nclass ID {\n /**\n * @param {number} client client id\n * @param {number} clock unique per client id, continuous number\n */\n constructor (client, clock) {\n /**\n * Client id\n * @type {number}\n */\n this.client = client;\n /**\n * unique per client id, continuous number\n * @type {number}\n */\n this.clock = clock;\n }\n}\n\n/**\n * @param {ID | null} a\n * @param {ID | null} b\n * @return {boolean}\n *\n * @function\n */\nconst compareIDs = (a, b) => a === b || (a !== null && b !== null && a.client === b.client && a.clock === b.clock);\n\n/**\n * @param {number} client\n * @param {number} clock\n *\n * @private\n * @function\n */\nconst createID = (client, clock) => new ID(client, clock);\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {ID} id\n *\n * @private\n * @function\n */\nconst writeID = (encoder, id) => {\n encoding.writeVarUint(encoder, id.client);\n encoding.writeVarUint(encoder, id.clock);\n};\n\n/**\n * Read ID.\n * * If first varUint read is 0xFFFFFF a RootID is returned.\n * * Otherwise an ID is returned\n *\n * @param {decoding.Decoder} decoder\n * @return {ID}\n *\n * @private\n * @function\n */\nconst readID = decoder =>\n createID(decoding.readVarUint(decoder), decoding.readVarUint(decoder));\n\n/**\n * The top types are mapped from y.share.get(keyname) => type.\n * `type` does not store any information about the `keyname`.\n * This function finds the correct `keyname` for `type` and throws otherwise.\n *\n * @param {AbstractType} type\n * @return {string}\n *\n * @private\n * @function\n */\nconst findRootTypeKey = type => {\n // @ts-ignore _y must be defined, otherwise unexpected case\n for (const [key, value] of type.doc.share.entries()) {\n if (value === type) {\n return key\n }\n }\n throw error.unexpectedCase()\n};\n\n/**\n * Check if `parent` is a parent of `child`.\n *\n * @param {AbstractType} parent\n * @param {Item|null} child\n * @return {Boolean} Whether `parent` is a parent of `child`.\n *\n * @private\n * @function\n */\nconst isParentOf = (parent, child) => {\n while (child !== null) {\n if (child.parent === parent) {\n return true\n }\n child = /** @type {AbstractType} */ (child.parent)._item;\n }\n return false\n};\n\n/**\n * Convenient helper to log type information.\n *\n * Do not use in productive systems as the output can be immense!\n *\n * @param {AbstractType} type\n */\nconst logType = type => {\n const res = [];\n let n = type._start;\n while (n) {\n res.push(n);\n n = n.right;\n }\n console.log('Children: ', res);\n console.log('Children content: ', res.filter(m => !m.deleted).map(m => m.content));\n};\n\nclass PermanentUserData {\n /**\n * @param {Doc} doc\n * @param {YMap} [storeType]\n */\n constructor (doc, storeType = doc.getMap('users')) {\n /**\n * @type {Map}\n */\n const dss = new Map();\n this.yusers = storeType;\n this.doc = doc;\n /**\n * Maps from clientid to userDescription\n *\n * @type {Map}\n */\n this.clients = new Map();\n this.dss = dss;\n /**\n * @param {YMap} user\n * @param {string} userDescription\n */\n const initUser = (user, userDescription) => {\n /**\n * @type {YArray}\n */\n const ds = user.get('ds');\n const ids = user.get('ids');\n const addClientId = /** @param {number} clientid */ clientid => this.clients.set(clientid, userDescription);\n ds.observe(/** @param {YArrayEvent} event */ event => {\n event.changes.added.forEach(item => {\n item.content.getContent().forEach(encodedDs => {\n if (encodedDs instanceof Uint8Array) {\n this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs)))]));\n }\n });\n });\n });\n this.dss.set(userDescription, mergeDeleteSets(ds.map(encodedDs => readDeleteSet(new DSDecoderV1(decoding.createDecoder(encodedDs))))));\n ids.observe(/** @param {YArrayEvent} event */ event =>\n event.changes.added.forEach(item => item.content.getContent().forEach(addClientId))\n );\n ids.forEach(addClientId);\n };\n // observe users\n storeType.observe(event => {\n event.keysChanged.forEach(userDescription =>\n initUser(storeType.get(userDescription), userDescription)\n );\n });\n // add intial data\n storeType.forEach(initUser);\n }\n\n /**\n * @param {Doc} doc\n * @param {number} clientid\n * @param {string} userDescription\n * @param {Object} conf\n * @param {function(Transaction, DeleteSet):boolean} [conf.filter]\n */\n setUserMapping (doc, clientid, userDescription, { filter = () => true } = {}) {\n const users = this.yusers;\n let user = users.get(userDescription);\n if (!user) {\n user = new YMap();\n user.set('ids', new YArray());\n user.set('ds', new YArray());\n users.set(userDescription, user);\n }\n user.get('ids').push([clientid]);\n users.observe(_event => {\n setTimeout(() => {\n const userOverwrite = users.get(userDescription);\n if (userOverwrite !== user) {\n // user was overwritten, port all data over to the next user object\n // @todo Experiment with Y.Sets here\n user = userOverwrite;\n // @todo iterate over old type\n this.clients.forEach((_userDescription, clientid) => {\n if (userDescription === _userDescription) {\n user.get('ids').push([clientid]);\n }\n });\n const encoder = new DSEncoderV1();\n const ds = this.dss.get(userDescription);\n if (ds) {\n writeDeleteSet(encoder, ds);\n user.get('ds').push([encoder.toUint8Array()]);\n }\n }\n }, 0);\n });\n doc.on('afterTransaction', /** @param {Transaction} transaction */ transaction => {\n setTimeout(() => {\n const yds = user.get('ds');\n const ds = transaction.deleteSet;\n if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {\n const encoder = new DSEncoderV1();\n writeDeleteSet(encoder, ds);\n yds.push([encoder.toUint8Array()]);\n }\n });\n });\n }\n\n /**\n * @param {number} clientid\n * @return {any}\n */\n getUserByClientId (clientid) {\n return this.clients.get(clientid) || null\n }\n\n /**\n * @param {ID} id\n * @return {string | null}\n */\n getUserByDeletedId (id) {\n for (const [userDescription, ds] of this.dss.entries()) {\n if (isDeleted(ds, id)) {\n return userDescription\n }\n }\n return null\n }\n}\n\n/**\n * A relative position is based on the Yjs model and is not affected by document changes.\n * E.g. If you place a relative position before a certain character, it will always point to this character.\n * If you place a relative position at the end of a type, it will always point to the end of the type.\n *\n * A numeric position is often unsuited for user selections, because it does not change when content is inserted\n * before or after.\n *\n * ```Insert(0, 'x')('a|bc') = 'xa|bc'``` Where | is the relative position.\n *\n * One of the properties must be defined.\n *\n * @example\n * // Current cursor position is at position 10\n * const relativePosition = createRelativePositionFromIndex(yText, 10)\n * // modify yText\n * yText.insert(0, 'abc')\n * yText.delete(3, 10)\n * // Compute the cursor position\n * const absolutePosition = createAbsolutePositionFromRelativePosition(y, relativePosition)\n * absolutePosition.type === yText // => true\n * console.log('cursor location is ' + absolutePosition.index) // => cursor location is 3\n *\n */\nclass RelativePosition {\n /**\n * @param {ID|null} type\n * @param {string|null} tname\n * @param {ID|null} item\n * @param {number} assoc\n */\n constructor (type, tname, item, assoc = 0) {\n /**\n * @type {ID|null}\n */\n this.type = type;\n /**\n * @type {string|null}\n */\n this.tname = tname;\n /**\n * @type {ID | null}\n */\n this.item = item;\n /**\n * A relative position is associated to a specific character. By default\n * assoc >= 0, the relative position is associated to the character\n * after the meant position.\n * I.e. position 1 in 'ab' is associated to character 'b'.\n *\n * If assoc < 0, then the relative position is associated to the caharacter\n * before the meant position.\n *\n * @type {number}\n */\n this.assoc = assoc;\n }\n}\n\n/**\n * @param {RelativePosition} rpos\n * @return {any}\n */\nconst relativePositionToJSON = rpos => {\n const json = {};\n if (rpos.type) {\n json.type = rpos.type;\n }\n if (rpos.tname) {\n json.tname = rpos.tname;\n }\n if (rpos.item) {\n json.item = rpos.item;\n }\n if (rpos.assoc != null) {\n json.assoc = rpos.assoc;\n }\n return json\n};\n\n/**\n * @param {any} json\n * @return {RelativePosition}\n *\n * @function\n */\nconst createRelativePositionFromJSON = json => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname ?? null, json.item == null ? null : createID(json.item.client, json.item.clock), json.assoc == null ? 0 : json.assoc);\n\nclass AbsolutePosition {\n /**\n * @param {AbstractType} type\n * @param {number} index\n * @param {number} [assoc]\n */\n constructor (type, index, assoc = 0) {\n /**\n * @type {AbstractType}\n */\n this.type = type;\n /**\n * @type {number}\n */\n this.index = index;\n this.assoc = assoc;\n }\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n * @param {number} [assoc]\n *\n * @function\n */\nconst createAbsolutePosition = (type, index, assoc = 0) => new AbsolutePosition(type, index, assoc);\n\n/**\n * @param {AbstractType} type\n * @param {ID|null} item\n * @param {number} [assoc]\n *\n * @function\n */\nconst createRelativePosition = (type, item, assoc) => {\n let typeid = null;\n let tname = null;\n if (type._item === null) {\n tname = findRootTypeKey(type);\n } else {\n typeid = createID(type._item.id.client, type._item.id.clock);\n }\n return new RelativePosition(typeid, tname, item, assoc)\n};\n\n/**\n * Create a relativePosition based on a absolute position.\n *\n * @param {AbstractType} type The base type (e.g. YText or YArray).\n * @param {number} index The absolute position.\n * @param {number} [assoc]\n * @return {RelativePosition}\n *\n * @function\n */\nconst createRelativePositionFromTypeIndex = (type, index, assoc = 0) => {\n let t = type._start;\n if (assoc < 0) {\n // associated to the left character or the beginning of a type, increment index if possible.\n if (index === 0) {\n return createRelativePosition(type, null, assoc)\n }\n index--;\n }\n while (t !== null) {\n if (!t.deleted && t.countable) {\n if (t.length > index) {\n // case 1: found position somewhere in the linked list\n return createRelativePosition(type, createID(t.id.client, t.id.clock + index), assoc)\n }\n index -= t.length;\n }\n if (t.right === null && assoc < 0) {\n // left-associated position, return last available id\n return createRelativePosition(type, t.lastId, assoc)\n }\n t = t.right;\n }\n return createRelativePosition(type, null, assoc)\n};\n\n/**\n * @param {encoding.Encoder} encoder\n * @param {RelativePosition} rpos\n *\n * @function\n */\nconst writeRelativePosition = (encoder, rpos) => {\n const { type, tname, item, assoc } = rpos;\n if (item !== null) {\n encoding.writeVarUint(encoder, 0);\n writeID(encoder, item);\n } else if (tname !== null) {\n // case 2: found position at the end of the list and type is stored in y.share\n encoding.writeUint8(encoder, 1);\n encoding.writeVarString(encoder, tname);\n } else if (type !== null) {\n // case 3: found position at the end of the list and type is attached to an item\n encoding.writeUint8(encoder, 2);\n writeID(encoder, type);\n } else {\n throw error.unexpectedCase()\n }\n encoding.writeVarInt(encoder, assoc);\n return encoder\n};\n\n/**\n * @param {RelativePosition} rpos\n * @return {Uint8Array}\n */\nconst encodeRelativePosition = rpos => {\n const encoder = encoding.createEncoder();\n writeRelativePosition(encoder, rpos);\n return encoding.toUint8Array(encoder)\n};\n\n/**\n * @param {decoding.Decoder} decoder\n * @return {RelativePosition}\n *\n * @function\n */\nconst readRelativePosition = decoder => {\n let type = null;\n let tname = null;\n let itemID = null;\n switch (decoding.readVarUint(decoder)) {\n case 0:\n // case 1: found position somewhere in the linked list\n itemID = readID(decoder);\n break\n case 1:\n // case 2: found position at the end of the list and type is stored in y.share\n tname = decoding.readVarString(decoder);\n break\n case 2: {\n // case 3: found position at the end of the list and type is attached to an item\n type = readID(decoder);\n }\n }\n const assoc = decoding.hasContent(decoder) ? decoding.readVarInt(decoder) : 0;\n return new RelativePosition(type, tname, itemID, assoc)\n};\n\n/**\n * @param {Uint8Array} uint8Array\n * @return {RelativePosition}\n */\nconst decodeRelativePosition = uint8Array => readRelativePosition(decoding.createDecoder(uint8Array));\n\n/**\n * Transform a relative position to an absolute position.\n *\n * If you want to share the relative position with other users, you should set\n * `followUndoneDeletions` to false to get consistent results across all clients.\n *\n * When calculating the absolute position, we try to follow the \"undone deletions\". This yields\n * better results for the user who performed undo. However, only the user who performed the undo\n * will get the better results, the other users don't know which operations recreated a deleted\n * range of content. There is more information in this ticket: https://github.com/yjs/yjs/issues/638\n *\n * @param {RelativePosition} rpos\n * @param {Doc} doc\n * @param {boolean} followUndoneDeletions - whether to follow undone deletions - see https://github.com/yjs/yjs/issues/638\n * @return {AbsolutePosition|null}\n *\n * @function\n */\nconst createAbsolutePositionFromRelativePosition = (rpos, doc, followUndoneDeletions = true) => {\n const store = doc.store;\n const rightID = rpos.item;\n const typeID = rpos.type;\n const tname = rpos.tname;\n const assoc = rpos.assoc;\n let type = null;\n let index = 0;\n if (rightID !== null) {\n if (getState(store, rightID.client) <= rightID.clock) {\n return null\n }\n const res = followUndoneDeletions ? followRedone(store, rightID) : { item: getItem(store, rightID), diff: 0 };\n const right = res.item;\n if (!(right instanceof Item)) {\n return null\n }\n type = /** @type {AbstractType} */ (right.parent);\n if (type._item === null || !type._item.deleted) {\n index = (right.deleted || !right.countable) ? 0 : (res.diff + (assoc >= 0 ? 0 : 1)); // adjust position based on left association if necessary\n let n = right.left;\n while (n !== null) {\n if (!n.deleted && n.countable) {\n index += n.length;\n }\n n = n.left;\n }\n }\n } else {\n if (tname !== null) {\n type = doc.get(tname);\n } else if (typeID !== null) {\n if (getState(store, typeID.client) <= typeID.clock) {\n // type does not exist yet\n return null\n }\n const { item } = followUndoneDeletions ? followRedone(store, typeID) : { item: getItem(store, typeID) };\n if (item instanceof Item && item.content instanceof ContentType) {\n type = item.content.type;\n } else {\n // struct is garbage collected\n return null\n }\n } else {\n throw error.unexpectedCase()\n }\n if (assoc >= 0) {\n index = type._length;\n } else {\n index = 0;\n }\n }\n return createAbsolutePosition(type, index, rpos.assoc)\n};\n\n/**\n * @param {RelativePosition|null} a\n * @param {RelativePosition|null} b\n * @return {boolean}\n *\n * @function\n */\nconst compareRelativePositions = (a, b) => a === b || (\n a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type) && a.assoc === b.assoc\n);\n\nclass Snapshot {\n /**\n * @param {DeleteSet} ds\n * @param {Map} sv state map\n */\n constructor (ds, sv) {\n /**\n * @type {DeleteSet}\n */\n this.ds = ds;\n /**\n * State Map\n * @type {Map}\n */\n this.sv = sv;\n }\n}\n\n/**\n * @param {Snapshot} snap1\n * @param {Snapshot} snap2\n * @return {boolean}\n */\nconst equalSnapshots = (snap1, snap2) => {\n const ds1 = snap1.ds.clients;\n const ds2 = snap2.ds.clients;\n const sv1 = snap1.sv;\n const sv2 = snap2.sv;\n if (sv1.size !== sv2.size || ds1.size !== ds2.size) {\n return false\n }\n for (const [key, value] of sv1.entries()) {\n if (sv2.get(key) !== value) {\n return false\n }\n }\n for (const [client, dsitems1] of ds1.entries()) {\n const dsitems2 = ds2.get(client) || [];\n if (dsitems1.length !== dsitems2.length) {\n return false\n }\n for (let i = 0; i < dsitems1.length; i++) {\n const dsitem1 = dsitems1[i];\n const dsitem2 = dsitems2[i];\n if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) {\n return false\n }\n }\n }\n return true\n};\n\n/**\n * @param {Snapshot} snapshot\n * @param {DSEncoderV1 | DSEncoderV2} [encoder]\n * @return {Uint8Array}\n */\nconst encodeSnapshotV2 = (snapshot, encoder = new DSEncoderV2()) => {\n writeDeleteSet(encoder, snapshot.ds);\n writeStateVector(encoder, snapshot.sv);\n return encoder.toUint8Array()\n};\n\n/**\n * @param {Snapshot} snapshot\n * @return {Uint8Array}\n */\nconst encodeSnapshot = snapshot => encodeSnapshotV2(snapshot, new DSEncoderV1());\n\n/**\n * @param {Uint8Array} buf\n * @param {DSDecoderV1 | DSDecoderV2} [decoder]\n * @return {Snapshot}\n */\nconst decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(decoding.createDecoder(buf))) => {\n return new Snapshot(readDeleteSet(decoder), readStateVector(decoder))\n};\n\n/**\n * @param {Uint8Array} buf\n * @return {Snapshot}\n */\nconst decodeSnapshot = buf => decodeSnapshotV2(buf, new DSDecoderV1(decoding.createDecoder(buf)));\n\n/**\n * @param {DeleteSet} ds\n * @param {Map} sm\n * @return {Snapshot}\n */\nconst createSnapshot = (ds, sm) => new Snapshot(ds, sm);\n\nconst emptySnapshot = createSnapshot(createDeleteSet(), new Map());\n\n/**\n * @param {Doc} doc\n * @return {Snapshot}\n */\nconst snapshot = doc => createSnapshot(createDeleteSetFromStructStore(doc.store), getStateVector(doc.store));\n\n/**\n * @param {Item} item\n * @param {Snapshot|undefined} snapshot\n *\n * @protected\n * @function\n */\nconst isVisible = (item, snapshot) => snapshot === undefined\n ? !item.deleted\n : snapshot.sv.has(item.id.client) && (snapshot.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot.ds, item.id);\n\n/**\n * @param {Transaction} transaction\n * @param {Snapshot} snapshot\n */\nconst splitSnapshotAffectedStructs = (transaction, snapshot) => {\n const meta = map.setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, set.create);\n const store = transaction.doc.store;\n // check if we already split for this snapshot\n if (!meta.has(snapshot)) {\n snapshot.sv.forEach((clock, client) => {\n if (clock < getState(store, client)) {\n getItemCleanStart(transaction, createID(client, clock));\n }\n });\n iterateDeletedStructs(transaction, snapshot.ds, _item => {});\n meta.add(snapshot);\n }\n};\n\n/**\n * @example\n * const ydoc = new Y.Doc({ gc: false })\n * ydoc.getText().insert(0, 'world!')\n * const snapshot = Y.snapshot(ydoc)\n * ydoc.getText().insert(0, 'hello ')\n * const restored = Y.createDocFromSnapshot(ydoc, snapshot)\n * assert(restored.getText().toString() === 'world!')\n *\n * @param {Doc} originDoc\n * @param {Snapshot} snapshot\n * @param {Doc} [newDoc] Optionally, you may define the Yjs document that receives the data from originDoc\n * @return {Doc}\n */\nconst createDocFromSnapshot = (originDoc, snapshot, newDoc = new Doc()) => {\n if (originDoc.gc) {\n // we should not try to restore a GC-ed document, because some of the restored items might have their content deleted\n throw new Error('Garbage-collection must be disabled in `originDoc`!')\n }\n const { sv, ds } = snapshot;\n\n const encoder = new UpdateEncoderV2();\n originDoc.transact(transaction => {\n let size = 0;\n sv.forEach(clock => {\n if (clock > 0) {\n size++;\n }\n });\n encoding.writeVarUint(encoder.restEncoder, size);\n // splitting the structs before writing them to the encoder\n for (const [client, clock] of sv) {\n if (clock === 0) {\n continue\n }\n if (clock < getState(originDoc.store, client)) {\n getItemCleanStart(transaction, createID(client, clock));\n }\n const structs = originDoc.store.clients.get(client) || [];\n const lastStructIndex = findIndexSS(structs, clock - 1);\n // write # encoded structs\n encoding.writeVarUint(encoder.restEncoder, lastStructIndex + 1);\n encoder.writeClient(client);\n // first clock written is 0\n encoding.writeVarUint(encoder.restEncoder, 0);\n for (let i = 0; i <= lastStructIndex; i++) {\n structs[i].write(encoder, 0);\n }\n }\n writeDeleteSet(encoder, ds);\n });\n\n applyUpdateV2(newDoc, encoder.toUint8Array(), 'snapshot');\n return newDoc\n};\n\n/**\n * @param {Snapshot} snapshot\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n */\nconst snapshotContainsUpdateV2 = (snapshot, update, YDecoder = UpdateDecoderV2) => {\n const updateDecoder = new YDecoder(decoding.createDecoder(update));\n const lazyDecoder = new LazyStructReader(updateDecoder, false);\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n if ((snapshot.sv.get(curr.id.client) || 0) < curr.id.clock + curr.length) {\n return false\n }\n }\n const mergedDS = mergeDeleteSets([snapshot.ds, readDeleteSet(updateDecoder)]);\n return equalDeleteSets(snapshot.ds, mergedDS)\n};\n\n/**\n * @param {Snapshot} snapshot\n * @param {Uint8Array} update\n */\nconst snapshotContainsUpdate = (snapshot, update) => snapshotContainsUpdateV2(snapshot, update, UpdateDecoderV1);\n\nclass StructStore {\n constructor () {\n /**\n * @type {Map>}\n */\n this.clients = new Map();\n /**\n * @type {null | { missing: Map, update: Uint8Array }}\n */\n this.pendingStructs = null;\n /**\n * @type {null | Uint8Array}\n */\n this.pendingDs = null;\n }\n}\n\n/**\n * Return the states as a Map.\n * Note that clock refers to the next expected clock id.\n *\n * @param {StructStore} store\n * @return {Map}\n *\n * @public\n * @function\n */\nconst getStateVector = store => {\n const sm = new Map();\n store.clients.forEach((structs, client) => {\n const struct = structs[structs.length - 1];\n sm.set(client, struct.id.clock + struct.length);\n });\n return sm\n};\n\n/**\n * @param {StructStore} store\n * @param {number} client\n * @return {number}\n *\n * @public\n * @function\n */\nconst getState = (store, client) => {\n const structs = store.clients.get(client);\n if (structs === undefined) {\n return 0\n }\n const lastStruct = structs[structs.length - 1];\n return lastStruct.id.clock + lastStruct.length\n};\n\n/**\n * @param {StructStore} store\n * @param {GC|Item} struct\n *\n * @private\n * @function\n */\nconst addStruct = (store, struct) => {\n let structs = store.clients.get(struct.id.client);\n if (structs === undefined) {\n structs = [];\n store.clients.set(struct.id.client, structs);\n } else {\n const lastStruct = structs[structs.length - 1];\n if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {\n throw error.unexpectedCase()\n }\n }\n structs.push(struct);\n};\n\n/**\n * Perform a binary search on a sorted array\n * @param {Array} structs\n * @param {number} clock\n * @return {number}\n *\n * @private\n * @function\n */\nconst findIndexSS = (structs, clock) => {\n let left = 0;\n let right = structs.length - 1;\n let mid = structs[right];\n let midclock = mid.id.clock;\n if (midclock === clock) {\n return right\n }\n // @todo does it even make sense to pivot the search?\n // If a good split misses, it might actually increase the time to find the correct item.\n // Currently, the only advantage is that search with pivoting might find the item on the first try.\n let midindex = math.floor((clock / (midclock + mid.length - 1)) * right); // pivoting the search\n while (left <= right) {\n mid = structs[midindex];\n midclock = mid.id.clock;\n if (midclock <= clock) {\n if (clock < midclock + mid.length) {\n return midindex\n }\n left = midindex + 1;\n } else {\n right = midindex - 1;\n }\n midindex = math.floor((left + right) / 2);\n }\n // Always check state before looking for a struct in StructStore\n // Therefore the case of not finding a struct is unexpected\n throw error.unexpectedCase()\n};\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {GC|Item}\n *\n * @private\n * @function\n */\nconst find = (store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client);\n return structs[findIndexSS(structs, id.clock)]\n};\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n * @private\n * @function\n */\nconst getItem = /** @type {function(StructStore,ID):Item} */ (find);\n\n/**\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clock\n */\nconst findIndexCleanStart = (transaction, structs, clock) => {\n const index = findIndexSS(structs, clock);\n const struct = structs[index];\n if (struct.id.clock < clock && struct instanceof Item) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));\n return index + 1\n }\n return index\n};\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nconst getItemCleanStart = (transaction, id) => {\n const structs = /** @type {Array} */ (transaction.doc.store.clients.get(id.client));\n return structs[findIndexCleanStart(transaction, structs, id.clock)]\n};\n\n/**\n * Expects that id is actually in store. This function throws or is an infinite loop otherwise.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @param {ID} id\n * @return {Item}\n *\n * @private\n * @function\n */\nconst getItemCleanEnd = (transaction, store, id) => {\n /**\n * @type {Array}\n */\n // @ts-ignore\n const structs = store.clients.get(id.client);\n const index = findIndexSS(structs, id.clock);\n const struct = structs[index];\n if (id.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {\n structs.splice(index + 1, 0, splitItem(transaction, struct, id.clock - struct.id.clock + 1));\n }\n return struct\n};\n\n/**\n * Replace `item` with `newitem` in store\n * @param {StructStore} store\n * @param {GC|Item} struct\n * @param {GC|Item} newStruct\n *\n * @private\n * @function\n */\nconst replaceStruct = (store, struct, newStruct) => {\n const structs = /** @type {Array} */ (store.clients.get(struct.id.client));\n structs[findIndexSS(structs, struct.id.clock)] = newStruct;\n};\n\n/**\n * Iterate over a range of structs\n *\n * @param {Transaction} transaction\n * @param {Array} structs\n * @param {number} clockStart Inclusive start\n * @param {number} len\n * @param {function(GC|Item):void} f\n *\n * @function\n */\nconst iterateStructs = (transaction, structs, clockStart, len, f) => {\n if (len === 0) {\n return\n }\n const clockEnd = clockStart + len;\n let index = findIndexCleanStart(transaction, structs, clockStart);\n let struct;\n do {\n struct = structs[index++];\n if (clockEnd < struct.id.clock + struct.length) {\n findIndexCleanStart(transaction, structs, clockEnd);\n }\n f(struct);\n } while (index < structs.length && structs[index].id.clock < clockEnd)\n};\n\n/**\n * A transaction is created for every change on the Yjs model. It is possible\n * to bundle changes on the Yjs model in a single transaction to\n * minimize the number on messages sent and the number of observer calls.\n * If possible the user of this library should bundle as many changes as\n * possible. Here is an example to illustrate the advantages of bundling:\n *\n * @example\n * const ydoc = new Y.Doc()\n * const map = ydoc.getMap('map')\n * // Log content when change is triggered\n * map.observe(() => {\n * console.log('change triggered')\n * })\n * // Each change on the map type triggers a log message:\n * map.set('a', 0) // => \"change triggered\"\n * map.set('b', 0) // => \"change triggered\"\n * // When put in a transaction, it will trigger the log after the transaction:\n * ydoc.transact(() => {\n * map.set('a', 1)\n * map.set('b', 1)\n * }) // => \"change triggered\"\n *\n * @public\n */\nclass Transaction {\n /**\n * @param {Doc} doc\n * @param {any} origin\n * @param {boolean} local\n */\n constructor (doc, origin, local) {\n /**\n * The Yjs instance.\n * @type {Doc}\n */\n this.doc = doc;\n /**\n * Describes the set of deleted items by ids\n * @type {DeleteSet}\n */\n this.deleteSet = new DeleteSet();\n /**\n * Holds the state before the transaction started.\n * @type {Map}\n */\n this.beforeState = getStateVector(doc.store);\n /**\n * Holds the state after the transaction.\n * @type {Map}\n */\n this.afterState = new Map();\n /**\n * All types that were directly modified (property added or child\n * inserted/deleted). New types are not included in this Set.\n * Maps from type to parentSubs (`item.parentSub = null` for YArray)\n * @type {Map>,Set>}\n */\n this.changed = new Map();\n /**\n * Stores the events for the types that observe also child elements.\n * It is mainly used by `observeDeep`.\n * @type {Map>,Array>>}\n */\n this.changedParentTypes = new Map();\n /**\n * @type {Array}\n */\n this._mergeStructs = [];\n /**\n * @type {any}\n */\n this.origin = origin;\n /**\n * Stores meta information on the transaction\n * @type {Map}\n */\n this.meta = new Map();\n /**\n * Whether this change originates from this doc.\n * @type {boolean}\n */\n this.local = local;\n /**\n * @type {Set}\n */\n this.subdocsAdded = new Set();\n /**\n * @type {Set}\n */\n this.subdocsRemoved = new Set();\n /**\n * @type {Set}\n */\n this.subdocsLoaded = new Set();\n /**\n * @type {boolean}\n */\n this._needFormattingCleanup = false;\n }\n}\n\n/**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Transaction} transaction\n * @return {boolean} Whether data was written.\n */\nconst writeUpdateMessageFromTransaction = (encoder, transaction) => {\n if (transaction.deleteSet.clients.size === 0 && !map.any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {\n return false\n }\n sortAndMergeDeleteSet(transaction.deleteSet);\n writeStructsFromTransaction(encoder, transaction);\n writeDeleteSet(encoder, transaction.deleteSet);\n return true\n};\n\n/**\n * If `type.parent` was added in current transaction, `type` technically\n * did not change, it was just added and we should not fire events for `type`.\n *\n * @param {Transaction} transaction\n * @param {AbstractType>} type\n * @param {string|null} parentSub\n */\nconst addChangedTypeToTransaction = (transaction, type, parentSub) => {\n const item = type._item;\n if (item === null || (item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted)) {\n map.setIfUndefined(transaction.changed, type, set.create).add(parentSub);\n }\n};\n\n/**\n * @param {Array} structs\n * @param {number} pos\n * @return {number} # of merged structs\n */\nconst tryToMergeWithLefts = (structs, pos) => {\n let right = structs[pos];\n let left = structs[pos - 1];\n let i = pos;\n for (; i > 0; right = left, left = structs[--i - 1]) {\n if (left.deleted === right.deleted && left.constructor === right.constructor) {\n if (left.mergeWith(right)) {\n if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType} */ (right.parent)._map.get(right.parentSub) === right) {\n /** @type {AbstractType} */ (right.parent)._map.set(right.parentSub, /** @type {Item} */ (left));\n }\n continue\n }\n }\n break\n }\n const merged = pos - i;\n if (merged) {\n // remove all merged structs from the array\n structs.splice(pos + 1 - merged, merged);\n }\n return merged\n};\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nconst tryGcDeleteSet = (ds, store, gcFilter) => {\n for (const [client, deleteItems] of ds.clients.entries()) {\n const structs = /** @type {Array} */ (store.clients.get(client));\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di];\n const endDeleteItemClock = deleteItem.clock + deleteItem.len;\n for (\n let si = findIndexSS(structs, deleteItem.clock), struct = structs[si];\n si < structs.length && struct.id.clock < endDeleteItemClock;\n struct = structs[++si]\n ) {\n const struct = structs[si];\n if (deleteItem.clock + deleteItem.len <= struct.id.clock) {\n break\n }\n if (struct instanceof Item && struct.deleted && !struct.keep && gcFilter(struct)) {\n struct.gc(store, false);\n }\n }\n }\n }\n};\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n */\nconst tryMergeDeleteSet = (ds, store) => {\n // try to merge deleted / gc'd items\n // merge from right to left for better efficiency and so we don't miss any merge targets\n ds.clients.forEach((deleteItems, client) => {\n const structs = /** @type {Array} */ (store.clients.get(client));\n for (let di = deleteItems.length - 1; di >= 0; di--) {\n const deleteItem = deleteItems[di];\n // start with merging the item next to the last deleted item\n const mostRightIndexToCheck = math.min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1));\n for (\n let si = mostRightIndexToCheck, struct = structs[si];\n si > 0 && struct.id.clock >= deleteItem.clock;\n struct = structs[si]\n ) {\n si -= 1 + tryToMergeWithLefts(structs, si);\n }\n }\n });\n};\n\n/**\n * @param {DeleteSet} ds\n * @param {StructStore} store\n * @param {function(Item):boolean} gcFilter\n */\nconst tryGc = (ds, store, gcFilter) => {\n tryGcDeleteSet(ds, store, gcFilter);\n tryMergeDeleteSet(ds, store);\n};\n\n/**\n * @param {Array} transactionCleanups\n * @param {number} i\n */\nconst cleanupTransactions = (transactionCleanups, i) => {\n if (i < transactionCleanups.length) {\n const transaction = transactionCleanups[i];\n const doc = transaction.doc;\n const store = doc.store;\n const ds = transaction.deleteSet;\n const mergeStructs = transaction._mergeStructs;\n try {\n sortAndMergeDeleteSet(ds);\n transaction.afterState = getStateVector(transaction.doc.store);\n doc.emit('beforeObserverCalls', [transaction, doc]);\n /**\n * An array of event callbacks.\n *\n * Each callback is called even if the other ones throw errors.\n *\n * @type {Array}\n */\n const fs = [];\n // observe events on changed types\n transaction.changed.forEach((subs, itemtype) =>\n fs.push(() => {\n if (itemtype._item === null || !itemtype._item.deleted) {\n itemtype._callObserver(transaction, subs);\n }\n })\n );\n fs.push(() => {\n // deep observe events\n transaction.changedParentTypes.forEach((events, type) => {\n // We need to think about the possibility that the user transforms the\n // Y.Doc in the event.\n if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) {\n events = events\n .filter(event =>\n event.target._item === null || !event.target._item.deleted\n );\n events\n .forEach(event => {\n event.currentTarget = type;\n // path is relative to the current target\n event._path = null;\n });\n // sort events by path length so that top-level events are fired first.\n events\n .sort((event1, event2) => event1.path.length - event2.path.length);\n // We don't need to check for events.length\n // because we know it has at least one element\n callEventHandlerListeners(type._dEH, events, transaction);\n }\n });\n });\n fs.push(() => doc.emit('afterTransaction', [transaction, doc]));\n callAll(fs, []);\n if (transaction._needFormattingCleanup) {\n cleanupYTextAfterTransaction(transaction);\n }\n } finally {\n // Replace deleted items with ItemDeleted / GC.\n // This is where content is actually remove from the Yjs Doc.\n if (doc.gc) {\n tryGcDeleteSet(ds, store, doc.gcFilter);\n }\n tryMergeDeleteSet(ds, store);\n\n // on all affected store.clients props, try to merge\n transaction.afterState.forEach((clock, client) => {\n const beforeClock = transaction.beforeState.get(client) || 0;\n if (beforeClock !== clock) {\n const structs = /** @type {Array} */ (store.clients.get(client));\n // we iterate from right to left so we can safely remove entries\n const firstChangePos = math.max(findIndexSS(structs, beforeClock), 1);\n for (let i = structs.length - 1; i >= firstChangePos;) {\n i -= 1 + tryToMergeWithLefts(structs, i);\n }\n }\n });\n // try to merge mergeStructs\n // @todo: it makes more sense to transform mergeStructs to a DS, sort it, and merge from right to left\n // but at the moment DS does not handle duplicates\n for (let i = mergeStructs.length - 1; i >= 0; i--) {\n const { client, clock } = mergeStructs[i].id;\n const structs = /** @type {Array} */ (store.clients.get(client));\n const replacedStructPos = findIndexSS(structs, clock);\n if (replacedStructPos + 1 < structs.length) {\n if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) {\n continue // no need to perform next check, both are already merged\n }\n }\n if (replacedStructPos > 0) {\n tryToMergeWithLefts(structs, replacedStructPos);\n }\n }\n if (!transaction.local && transaction.afterState.get(doc.clientID) !== transaction.beforeState.get(doc.clientID)) {\n logging.print(logging.ORANGE, logging.BOLD, '[yjs] ', logging.UNBOLD, logging.RED, 'Changed the client-id because another client seems to be using it.');\n doc.clientID = generateNewClientId();\n }\n // @todo Merge all the transactions into one and provide send the data as a single update message\n doc.emit('afterTransactionCleanup', [transaction, doc]);\n if (doc._observers.has('update')) {\n const encoder = new UpdateEncoderV1();\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction);\n if (hasContent) {\n doc.emit('update', [encoder.toUint8Array(), transaction.origin, doc, transaction]);\n }\n }\n if (doc._observers.has('updateV2')) {\n const encoder = new UpdateEncoderV2();\n const hasContent = writeUpdateMessageFromTransaction(encoder, transaction);\n if (hasContent) {\n doc.emit('updateV2', [encoder.toUint8Array(), transaction.origin, doc, transaction]);\n }\n }\n const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction;\n if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) {\n subdocsAdded.forEach(subdoc => {\n subdoc.clientID = doc.clientID;\n if (subdoc.collectionid == null) {\n subdoc.collectionid = doc.collectionid;\n }\n doc.subdocs.add(subdoc);\n });\n subdocsRemoved.forEach(subdoc => doc.subdocs.delete(subdoc));\n doc.emit('subdocs', [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc, transaction]);\n subdocsRemoved.forEach(subdoc => subdoc.destroy());\n }\n\n if (transactionCleanups.length <= i + 1) {\n doc._transactionCleanups = [];\n doc.emit('afterAllTransactions', [doc, transactionCleanups]);\n } else {\n cleanupTransactions(transactionCleanups, i + 1);\n }\n }\n }\n};\n\n/**\n * Implements the functionality of `y.transact(()=>{..})`\n *\n * @template T\n * @param {Doc} doc\n * @param {function(Transaction):T} f\n * @param {any} [origin=true]\n * @return {T}\n *\n * @function\n */\nconst transact = (doc, f, origin = null, local = true) => {\n const transactionCleanups = doc._transactionCleanups;\n let initialCall = false;\n /**\n * @type {any}\n */\n let result = null;\n if (doc._transaction === null) {\n initialCall = true;\n doc._transaction = new Transaction(doc, origin, local);\n transactionCleanups.push(doc._transaction);\n if (transactionCleanups.length === 1) {\n doc.emit('beforeAllTransactions', [doc]);\n }\n doc.emit('beforeTransaction', [doc._transaction, doc]);\n }\n try {\n result = f(doc._transaction);\n } finally {\n if (initialCall) {\n const finishCleanup = doc._transaction === transactionCleanups[0];\n doc._transaction = null;\n if (finishCleanup) {\n // The first transaction ended, now process observer calls.\n // Observer call may create new transactions for which we need to call the observers and do cleanup.\n // We don't want to nest these calls, so we execute these calls one after\n // another.\n // Also we need to ensure that all cleanups are called, even if the\n // observes throw errors.\n // This file is full of hacky try {} finally {} blocks to ensure that an\n // event can throw errors and also that the cleanup is called.\n cleanupTransactions(transactionCleanups, 0);\n }\n }\n }\n return result\n};\n\nclass StackItem {\n /**\n * @param {DeleteSet} deletions\n * @param {DeleteSet} insertions\n */\n constructor (deletions, insertions) {\n this.insertions = insertions;\n this.deletions = deletions;\n /**\n * Use this to save and restore metadata like selection range\n */\n this.meta = new Map();\n }\n}\n/**\n * @param {Transaction} tr\n * @param {UndoManager} um\n * @param {StackItem} stackItem\n */\nconst clearUndoManagerStackItem = (tr, um, stackItem) => {\n iterateDeletedStructs(tr, stackItem.deletions, item => {\n if (item instanceof Item && um.scope.some(type => isParentOf(type, item))) {\n keepItem(item, false);\n }\n });\n};\n\n/**\n * @param {UndoManager} undoManager\n * @param {Array} stack\n * @param {'undo'|'redo'} eventType\n * @return {StackItem?}\n */\nconst popStackItem = (undoManager, stack, eventType) => {\n /**\n * Keep a reference to the transaction so we can fire the event with the changedParentTypes\n * @type {any}\n */\n let _tr = null;\n const doc = undoManager.doc;\n const scope = undoManager.scope;\n transact(doc, transaction => {\n while (stack.length > 0 && undoManager.currStackItem === null) {\n const store = doc.store;\n const stackItem = /** @type {StackItem} */ (stack.pop());\n /**\n * @type {Set}\n */\n const itemsToRedo = new Set();\n /**\n * @type {Array}\n */\n const itemsToDelete = [];\n let performedChange = false;\n iterateDeletedStructs(transaction, stackItem.insertions, struct => {\n if (struct instanceof Item) {\n if (struct.redone !== null) {\n let { item, diff } = followRedone(store, struct.id);\n if (diff > 0) {\n item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff));\n }\n struct = item;\n }\n if (!struct.deleted && scope.some(type => isParentOf(type, /** @type {Item} */ (struct)))) {\n itemsToDelete.push(struct);\n }\n }\n });\n iterateDeletedStructs(transaction, stackItem.deletions, struct => {\n if (\n struct instanceof Item &&\n scope.some(type => isParentOf(type, struct)) &&\n // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.\n !isDeleted(stackItem.insertions, struct.id)\n ) {\n itemsToRedo.add(struct);\n }\n });\n itemsToRedo.forEach(struct => {\n performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager.ignoreRemoteMapChanges, undoManager) !== null || performedChange;\n });\n // We want to delete in reverse order so that children are deleted before\n // parents, so we have more information available when items are filtered.\n for (let i = itemsToDelete.length - 1; i >= 0; i--) {\n const item = itemsToDelete[i];\n if (undoManager.deleteFilter(item)) {\n item.delete(transaction);\n performedChange = true;\n }\n }\n undoManager.currStackItem = performedChange ? stackItem : null;\n }\n transaction.changed.forEach((subProps, type) => {\n // destroy search marker if necessary\n if (subProps.has(null) && type._searchMarker) {\n type._searchMarker.length = 0;\n }\n });\n _tr = transaction;\n }, undoManager);\n const res = undoManager.currStackItem;\n if (res != null) {\n const changedParentTypes = _tr.changedParentTypes;\n undoManager.emit('stack-item-popped', [{ stackItem: res, type: eventType, changedParentTypes, origin: undoManager }, undoManager]);\n undoManager.currStackItem = null;\n }\n return res\n};\n\n/**\n * @typedef {Object} UndoManagerOptions\n * @property {number} [UndoManagerOptions.captureTimeout=500]\n * @property {function(Transaction):boolean} [UndoManagerOptions.captureTransaction] Do not capture changes of a Transaction if result false.\n * @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes\n * it is necessary to filter what an Undo/Redo operation can delete. If this\n * filter returns false, the type/item won't be deleted even it is in the\n * undo/redo scope.\n * @property {Set} [UndoManagerOptions.trackedOrigins=new Set([null])]\n * @property {boolean} [ignoreRemoteMapChanges] Experimental. By default, the UndoManager will never overwrite remote changes. Enable this property to enable overwriting remote changes on key-value changes (Y.Map, properties on Y.Xml, etc..).\n * @property {Doc} [doc] The document that this UndoManager operates on. Only needed if typeScope is empty.\n */\n\n/**\n * @typedef {Object} StackItemEvent\n * @property {StackItem} StackItemEvent.stackItem\n * @property {any} StackItemEvent.origin\n * @property {'undo'|'redo'} StackItemEvent.type\n * @property {Map>,Array>>} StackItemEvent.changedParentTypes\n */\n\n/**\n * Fires 'stack-item-added' event when a stack item was added to either the undo- or\n * the redo-stack. You may store additional stack information via the\n * metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties).\n * Fires 'stack-item-popped' event when a stack item was popped from either the\n * undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`.\n *\n * @extends {ObservableV2<{'stack-item-added':function(StackItemEvent, UndoManager):void, 'stack-item-popped': function(StackItemEvent, UndoManager):void, 'stack-cleared': function({ undoStackCleared: boolean, redoStackCleared: boolean }):void, 'stack-item-updated': function(StackItemEvent, UndoManager):void }>}\n */\nclass UndoManager extends ObservableV2 {\n /**\n * @param {AbstractType|Array>} typeScope Accepts either a single type, or an array of types\n * @param {UndoManagerOptions} options\n */\n constructor (typeScope, {\n captureTimeout = 500,\n captureTransaction = _tr => true,\n deleteFilter = () => true,\n trackedOrigins = new Set([null]),\n ignoreRemoteMapChanges = false,\n doc = /** @type {Doc} */ (array.isArray(typeScope) ? typeScope[0].doc : typeScope.doc)\n } = {}) {\n super();\n /**\n * @type {Array>}\n */\n this.scope = [];\n this.doc = doc;\n this.addToScope(typeScope);\n this.deleteFilter = deleteFilter;\n trackedOrigins.add(this);\n this.trackedOrigins = trackedOrigins;\n this.captureTransaction = captureTransaction;\n /**\n * @type {Array}\n */\n this.undoStack = [];\n /**\n * @type {Array}\n */\n this.redoStack = [];\n /**\n * Whether the client is currently undoing (calling UndoManager.undo)\n *\n * @type {boolean}\n */\n this.undoing = false;\n this.redoing = false;\n /**\n * The currently popped stack item if UndoManager.undoing or UndoManager.redoing\n *\n * @type {StackItem|null}\n */\n this.currStackItem = null;\n this.lastChange = 0;\n this.ignoreRemoteMapChanges = ignoreRemoteMapChanges;\n this.captureTimeout = captureTimeout;\n /**\n * @param {Transaction} transaction\n */\n this.afterTransactionHandler = transaction => {\n // Only track certain transactions\n if (\n !this.captureTransaction(transaction) ||\n !this.scope.some(type => transaction.changedParentTypes.has(type)) ||\n (!this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor)))\n ) {\n return\n }\n const undoing = this.undoing;\n const redoing = this.redoing;\n const stack = undoing ? this.redoStack : this.undoStack;\n if (undoing) {\n this.stopCapturing(); // next undo should not be appended to last stack item\n } else if (!redoing) {\n // neither undoing nor redoing: delete redoStack\n this.clear(false, true);\n }\n const insertions = new DeleteSet();\n transaction.afterState.forEach((endClock, client) => {\n const startClock = transaction.beforeState.get(client) || 0;\n const len = endClock - startClock;\n if (len > 0) {\n addToDeleteSet(insertions, client, startClock, len);\n }\n });\n const now = time.getUnixTime();\n let didAdd = false;\n if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) {\n // append change to last stack op\n const lastOp = stack[stack.length - 1];\n lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet]);\n lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions]);\n } else {\n // create a new stack op\n stack.push(new StackItem(transaction.deleteSet, insertions));\n didAdd = true;\n }\n if (!undoing && !redoing) {\n this.lastChange = now;\n }\n // make sure that deleted structs are not gc'd\n iterateDeletedStructs(transaction, transaction.deleteSet, /** @param {Item|GC} item */ item => {\n if (item instanceof Item && this.scope.some(type => isParentOf(type, item))) {\n keepItem(item, true);\n }\n });\n /**\n * @type {[StackItemEvent, UndoManager]}\n */\n const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? 'redo' : 'undo', changedParentTypes: transaction.changedParentTypes }, this];\n if (didAdd) {\n this.emit('stack-item-added', changeEvent);\n } else {\n this.emit('stack-item-updated', changeEvent);\n }\n };\n this.doc.on('afterTransaction', this.afterTransactionHandler);\n this.doc.on('destroy', () => {\n this.destroy();\n });\n }\n\n /**\n * @param {Array> | AbstractType} ytypes\n */\n addToScope (ytypes) {\n ytypes = array.isArray(ytypes) ? ytypes : [ytypes];\n ytypes.forEach(ytype => {\n if (this.scope.every(yt => yt !== ytype)) {\n if (ytype.doc !== this.doc) logging.warn('[yjs#509] Not same Y.Doc'); // use MultiDocUndoManager instead. also see https://github.com/yjs/yjs/issues/509\n this.scope.push(ytype);\n }\n });\n }\n\n /**\n * @param {any} origin\n */\n addTrackedOrigin (origin) {\n this.trackedOrigins.add(origin);\n }\n\n /**\n * @param {any} origin\n */\n removeTrackedOrigin (origin) {\n this.trackedOrigins.delete(origin);\n }\n\n clear (clearUndoStack = true, clearRedoStack = true) {\n if ((clearUndoStack && this.canUndo()) || (clearRedoStack && this.canRedo())) {\n this.doc.transact(tr => {\n if (clearUndoStack) {\n this.undoStack.forEach(item => clearUndoManagerStackItem(tr, this, item));\n this.undoStack = [];\n }\n if (clearRedoStack) {\n this.redoStack.forEach(item => clearUndoManagerStackItem(tr, this, item));\n this.redoStack = [];\n }\n this.emit('stack-cleared', [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }]);\n });\n }\n }\n\n /**\n * UndoManager merges Undo-StackItem if they are created within time-gap\n * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next\n * StackItem won't be merged.\n *\n *\n * @example\n * // without stopCapturing\n * ytext.insert(0, 'a')\n * ytext.insert(1, 'b')\n * um.undo()\n * ytext.toString() // => '' (note that 'ab' was removed)\n * // with stopCapturing\n * ytext.insert(0, 'a')\n * um.stopCapturing()\n * ytext.insert(0, 'b')\n * um.undo()\n * ytext.toString() // => 'a' (note that only 'b' was removed)\n *\n */\n stopCapturing () {\n this.lastChange = 0;\n }\n\n /**\n * Undo last changes on type.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n undo () {\n this.undoing = true;\n let res;\n try {\n res = popStackItem(this, this.undoStack, 'undo');\n } finally {\n this.undoing = false;\n }\n return res\n }\n\n /**\n * Redo last undo operation.\n *\n * @return {StackItem?} Returns StackItem if a change was applied\n */\n redo () {\n this.redoing = true;\n let res;\n try {\n res = popStackItem(this, this.redoStack, 'redo');\n } finally {\n this.redoing = false;\n }\n return res\n }\n\n /**\n * Are undo steps available?\n *\n * @return {boolean} `true` if undo is possible\n */\n canUndo () {\n return this.undoStack.length > 0\n }\n\n /**\n * Are redo steps available?\n *\n * @return {boolean} `true` if redo is possible\n */\n canRedo () {\n return this.redoStack.length > 0\n }\n\n destroy () {\n this.trackedOrigins.delete(this);\n this.doc.off('afterTransaction', this.afterTransactionHandler);\n super.destroy();\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n */\nfunction * lazyStructReaderGenerator (decoder) {\n const numOfStateUpdates = decoding.readVarUint(decoder.restDecoder);\n for (let i = 0; i < numOfStateUpdates; i++) {\n const numberOfStructs = decoding.readVarUint(decoder.restDecoder);\n const client = decoder.readClient();\n let clock = decoding.readVarUint(decoder.restDecoder);\n for (let i = 0; i < numberOfStructs; i++) {\n const info = decoder.readInfo();\n // @todo use switch instead of ifs\n if (info === 10) {\n const len = decoding.readVarUint(decoder.restDecoder);\n yield new Skip(createID(client, clock), len);\n clock += len;\n } else if ((binary.BITS5 & info) !== 0) {\n const cantCopyParentInfo = (info & (binary.BIT7 | binary.BIT8)) === 0;\n // If parent = null and neither left nor right are defined, then we know that `parent` is child of `y`\n // and we read the next string as parentYKey.\n // It indicates how we store/retrieve parent from `y.share`\n // @type {string|null}\n const struct = new Item(\n createID(client, clock),\n null, // left\n (info & binary.BIT8) === binary.BIT8 ? decoder.readLeftID() : null, // origin\n null, // right\n (info & binary.BIT7) === binary.BIT7 ? decoder.readRightID() : null, // right origin\n // @ts-ignore Force writing a string here.\n cantCopyParentInfo ? (decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID()) : null, // parent\n cantCopyParentInfo && (info & binary.BIT6) === binary.BIT6 ? decoder.readString() : null, // parentSub\n readItemContent(decoder, info) // item content\n );\n yield struct;\n clock += struct.length;\n } else {\n const len = decoder.readLen();\n yield new GC(createID(client, clock), len);\n clock += len;\n }\n }\n }\n}\n\nclass LazyStructReader {\n /**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @param {boolean} filterSkips\n */\n constructor (decoder, filterSkips) {\n this.gen = lazyStructReaderGenerator(decoder);\n /**\n * @type {null | Item | Skip | GC}\n */\n this.curr = null;\n this.done = false;\n this.filterSkips = filterSkips;\n this.next();\n }\n\n /**\n * @return {Item | GC | Skip |null}\n */\n next () {\n // ignore \"Skip\" structs\n do {\n this.curr = this.gen.next().value || null;\n } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip)\n return this.curr\n }\n}\n\n/**\n * @param {Uint8Array} update\n *\n */\nconst logUpdate = update => logUpdateV2(update, UpdateDecoderV1);\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n *\n */\nconst logUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {\n const structs = [];\n const updateDecoder = new YDecoder(decoding.createDecoder(update));\n const lazyDecoder = new LazyStructReader(updateDecoder, false);\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n structs.push(curr);\n }\n logging.print('Structs: ', structs);\n const ds = readDeleteSet(updateDecoder);\n logging.print('DeleteSet: ', ds);\n};\n\n/**\n * @param {Uint8Array} update\n *\n */\nconst decodeUpdate = (update) => decodeUpdateV2(update, UpdateDecoderV1);\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} [YDecoder]\n *\n */\nconst decodeUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {\n const structs = [];\n const updateDecoder = new YDecoder(decoding.createDecoder(update));\n const lazyDecoder = new LazyStructReader(updateDecoder, false);\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n structs.push(curr);\n }\n return {\n structs,\n ds: readDeleteSet(updateDecoder)\n }\n};\n\nclass LazyStructWriter {\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n constructor (encoder) {\n this.currClient = 0;\n this.startClock = 0;\n this.written = 0;\n this.encoder = encoder;\n /**\n * We want to write operations lazily, but also we need to know beforehand how many operations we want to write for each client.\n *\n * This kind of meta-information (#clients, #structs-per-client-written) is written to the restEncoder.\n *\n * We fragment the restEncoder and store a slice of it per-client until we know how many clients there are.\n * When we flush (toUint8Array) we write the restEncoder using the fragments and the meta-information.\n *\n * @type {Array<{ written: number, restEncoder: Uint8Array }>}\n */\n this.clientStructs = [];\n }\n}\n\n/**\n * @param {Array} updates\n * @return {Uint8Array}\n */\nconst mergeUpdates = updates => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1);\n\n/**\n * @param {Uint8Array} update\n * @param {typeof DSEncoderV1 | typeof DSEncoderV2} YEncoder\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} YDecoder\n * @return {Uint8Array}\n */\nconst encodeStateVectorFromUpdateV2 = (update, YEncoder = DSEncoderV2, YDecoder = UpdateDecoderV2) => {\n const encoder = new YEncoder();\n const updateDecoder = new LazyStructReader(new YDecoder(decoding.createDecoder(update)), false);\n let curr = updateDecoder.curr;\n if (curr !== null) {\n let size = 0;\n let currClient = curr.id.client;\n let stopCounting = curr.id.clock !== 0; // must start at 0\n let currClock = stopCounting ? 0 : curr.id.clock + curr.length;\n for (; curr !== null; curr = updateDecoder.next()) {\n if (currClient !== curr.id.client) {\n if (currClock !== 0) {\n size++;\n // We found a new client\n // write what we have to the encoder\n encoding.writeVarUint(encoder.restEncoder, currClient);\n encoding.writeVarUint(encoder.restEncoder, currClock);\n }\n currClient = curr.id.client;\n currClock = 0;\n stopCounting = curr.id.clock !== 0;\n }\n // we ignore skips\n if (curr.constructor === Skip) {\n stopCounting = true;\n }\n if (!stopCounting) {\n currClock = curr.id.clock + curr.length;\n }\n }\n // write what we have\n if (currClock !== 0) {\n size++;\n encoding.writeVarUint(encoder.restEncoder, currClient);\n encoding.writeVarUint(encoder.restEncoder, currClock);\n }\n // prepend the size of the state vector\n const enc = encoding.createEncoder();\n encoding.writeVarUint(enc, size);\n encoding.writeBinaryEncoder(enc, encoder.restEncoder);\n encoder.restEncoder = enc;\n return encoder.toUint8Array()\n } else {\n encoding.writeVarUint(encoder.restEncoder, 0);\n return encoder.toUint8Array()\n }\n};\n\n/**\n * @param {Uint8Array} update\n * @return {Uint8Array}\n */\nconst encodeStateVectorFromUpdate = update => encodeStateVectorFromUpdateV2(update, DSEncoderV1, UpdateDecoderV1);\n\n/**\n * @param {Uint8Array} update\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} YDecoder\n * @return {{ from: Map, to: Map }}\n */\nconst parseUpdateMetaV2 = (update, YDecoder = UpdateDecoderV2) => {\n /**\n * @type {Map}\n */\n const from = new Map();\n /**\n * @type {Map}\n */\n const to = new Map();\n const updateDecoder = new LazyStructReader(new YDecoder(decoding.createDecoder(update)), false);\n let curr = updateDecoder.curr;\n if (curr !== null) {\n let currClient = curr.id.client;\n let currClock = curr.id.clock;\n // write the beginning to `from`\n from.set(currClient, currClock);\n for (; curr !== null; curr = updateDecoder.next()) {\n if (currClient !== curr.id.client) {\n // We found a new client\n // write the end to `to`\n to.set(currClient, currClock);\n // write the beginning to `from`\n from.set(curr.id.client, curr.id.clock);\n // update currClient\n currClient = curr.id.client;\n }\n currClock = curr.id.clock + curr.length;\n }\n // write the end to `to`\n to.set(currClient, currClock);\n }\n return { from, to }\n};\n\n/**\n * @param {Uint8Array} update\n * @return {{ from: Map, to: Map }}\n */\nconst parseUpdateMeta = update => parseUpdateMetaV2(update, UpdateDecoderV1);\n\n/**\n * This method is intended to slice any kind of struct and retrieve the right part.\n * It does not handle side-effects, so it should only be used by the lazy-encoder.\n *\n * @param {Item | GC | Skip} left\n * @param {number} diff\n * @return {Item | GC}\n */\nconst sliceStruct = (left, diff) => {\n if (left.constructor === GC) {\n const { client, clock } = left.id;\n return new GC(createID(client, clock + diff), left.length - diff)\n } else if (left.constructor === Skip) {\n const { client, clock } = left.id;\n return new Skip(createID(client, clock + diff), left.length - diff)\n } else {\n const leftItem = /** @type {Item} */ (left);\n const { client, clock } = leftItem.id;\n return new Item(\n createID(client, clock + diff),\n null,\n createID(client, clock + diff - 1),\n null,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n )\n }\n};\n\n/**\n *\n * This function works similarly to `readUpdateV2`.\n *\n * @param {Array} updates\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n * @param {typeof UpdateEncoderV1 | typeof UpdateEncoderV2} [YEncoder]\n * @return {Uint8Array}\n */\nconst mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {\n if (updates.length === 1) {\n return updates[0]\n }\n const updateDecoders = updates.map(update => new YDecoder(decoding.createDecoder(update)));\n let lazyStructDecoders = updateDecoders.map(decoder => new LazyStructReader(decoder, true));\n\n /**\n * @todo we don't need offset because we always slice before\n * @type {null | { struct: Item | GC | Skip, offset: number }}\n */\n let currWrite = null;\n\n const updateEncoder = new YEncoder();\n // write structs lazily\n const lazyStructEncoder = new LazyStructWriter(updateEncoder);\n\n // Note: We need to ensure that all lazyStructDecoders are fully consumed\n // Note: Should merge document updates whenever possible - even from different updates\n // Note: Should handle that some operations cannot be applied yet ()\n\n while (true) {\n // Write higher clients first ⇒ sort by clientID & clock and remove decoders without content\n lazyStructDecoders = lazyStructDecoders.filter(dec => dec.curr !== null);\n lazyStructDecoders.sort(\n /** @type {function(any,any):number} */ (dec1, dec2) => {\n if (dec1.curr.id.client === dec2.curr.id.client) {\n const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock;\n if (clockDiff === 0) {\n // @todo remove references to skip since the structDecoders must filter Skips.\n return dec1.curr.constructor === dec2.curr.constructor\n ? 0\n : dec1.curr.constructor === Skip ? 1 : -1 // we are filtering skips anyway.\n } else {\n return clockDiff\n }\n } else {\n return dec2.curr.id.client - dec1.curr.id.client\n }\n }\n );\n if (lazyStructDecoders.length === 0) {\n break\n }\n const currDecoder = lazyStructDecoders[0];\n // write from currDecoder until the next operation is from another client or if filler-struct\n // then we need to reorder the decoders and find the next operation to write\n const firstClient = /** @type {Item | GC} */ (currDecoder.curr).id.client;\n\n if (currWrite !== null) {\n let curr = /** @type {Item | GC | null} */ (currDecoder.curr);\n let iterated = false;\n\n // iterate until we find something that we haven't written already\n // remember: first the high client-ids are written\n while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) {\n curr = currDecoder.next();\n iterated = true;\n }\n if (\n curr === null || // current decoder is empty\n curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient`\n (iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) // the above while loop was used and we are potentially missing updates\n ) {\n continue\n }\n\n if (firstClient !== currWrite.struct.id.client) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);\n currWrite = { struct: curr, offset: 0 };\n currDecoder.next();\n } else {\n if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) {\n // @todo write currStruct & set currStruct = Skip(clock = currStruct.id.clock + currStruct.length, length = curr.id.clock - self.clock)\n if (currWrite.struct.constructor === Skip) {\n // extend existing skip\n currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock;\n } else {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);\n const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length;\n /**\n * @type {Skip}\n */\n const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff);\n currWrite = { struct, offset: 0 };\n }\n } else { // if (currWrite.struct.id.clock + currWrite.struct.length >= curr.id.clock) {\n const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock;\n if (diff > 0) {\n if (currWrite.struct.constructor === Skip) {\n // prefer to slice Skip because the other struct might contain more information\n currWrite.struct.length -= diff;\n } else {\n curr = sliceStruct(curr, diff);\n }\n }\n if (!currWrite.struct.mergeWith(/** @type {any} */ (curr))) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);\n currWrite = { struct: curr, offset: 0 };\n currDecoder.next();\n }\n }\n }\n } else {\n currWrite = { struct: /** @type {Item | GC} */ (currDecoder.curr), offset: 0 };\n currDecoder.next();\n }\n for (\n let next = currDecoder.curr;\n next !== null && next.id.client === firstClient && next.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next.constructor !== Skip;\n next = currDecoder.next()\n ) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);\n currWrite = { struct: next, offset: 0 };\n }\n }\n if (currWrite !== null) {\n writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);\n currWrite = null;\n }\n finishLazyStructWriting(lazyStructEncoder);\n\n const dss = updateDecoders.map(decoder => readDeleteSet(decoder));\n const ds = mergeDeleteSets(dss);\n writeDeleteSet(updateEncoder, ds);\n return updateEncoder.toUint8Array()\n};\n\n/**\n * @param {Uint8Array} update\n * @param {Uint8Array} sv\n * @param {typeof UpdateDecoderV1 | typeof UpdateDecoderV2} [YDecoder]\n * @param {typeof UpdateEncoderV1 | typeof UpdateEncoderV2} [YEncoder]\n */\nconst diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {\n const state = decodeStateVector(sv);\n const encoder = new YEncoder();\n const lazyStructWriter = new LazyStructWriter(encoder);\n const decoder = new YDecoder(decoding.createDecoder(update));\n const reader = new LazyStructReader(decoder, false);\n while (reader.curr) {\n const curr = reader.curr;\n const currClient = curr.id.client;\n const svClock = state.get(currClient) || 0;\n if (reader.curr.constructor === Skip) {\n // the first written struct shouldn't be a skip\n reader.next();\n continue\n }\n if (curr.id.clock + curr.length > svClock) {\n writeStructToLazyStructWriter(lazyStructWriter, curr, math.max(svClock - curr.id.clock, 0));\n reader.next();\n while (reader.curr && reader.curr.id.client === currClient) {\n writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0);\n reader.next();\n }\n } else {\n // read until something new comes up\n while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) {\n reader.next();\n }\n }\n }\n finishLazyStructWriting(lazyStructWriter);\n // write ds\n const ds = readDeleteSet(decoder);\n writeDeleteSet(encoder, ds);\n return encoder.toUint8Array()\n};\n\n/**\n * @param {Uint8Array} update\n * @param {Uint8Array} sv\n */\nconst diffUpdate = (update, sv) => diffUpdateV2(update, sv, UpdateDecoderV1, UpdateEncoderV1);\n\n/**\n * @param {LazyStructWriter} lazyWriter\n */\nconst flushLazyStructWriter = lazyWriter => {\n if (lazyWriter.written > 0) {\n lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: encoding.toUint8Array(lazyWriter.encoder.restEncoder) });\n lazyWriter.encoder.restEncoder = encoding.createEncoder();\n lazyWriter.written = 0;\n }\n};\n\n/**\n * @param {LazyStructWriter} lazyWriter\n * @param {Item | GC} struct\n * @param {number} offset\n */\nconst writeStructToLazyStructWriter = (lazyWriter, struct, offset) => {\n // flush curr if we start another client\n if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) {\n flushLazyStructWriter(lazyWriter);\n }\n if (lazyWriter.written === 0) {\n lazyWriter.currClient = struct.id.client;\n // write next client\n lazyWriter.encoder.writeClient(struct.id.client);\n // write startClock\n encoding.writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset);\n }\n struct.write(lazyWriter.encoder, offset);\n lazyWriter.written++;\n};\n/**\n * Call this function when we collected all parts and want to\n * put all the parts together. After calling this method,\n * you can continue using the UpdateEncoder.\n *\n * @param {LazyStructWriter} lazyWriter\n */\nconst finishLazyStructWriting = (lazyWriter) => {\n flushLazyStructWriter(lazyWriter);\n\n // this is a fresh encoder because we called flushCurr\n const restEncoder = lazyWriter.encoder.restEncoder;\n\n /**\n * Now we put all the fragments together.\n * This works similarly to `writeClientsStructs`\n */\n\n // write # states that were updated - i.e. the clients\n encoding.writeVarUint(restEncoder, lazyWriter.clientStructs.length);\n\n for (let i = 0; i < lazyWriter.clientStructs.length; i++) {\n const partStructs = lazyWriter.clientStructs[i];\n /**\n * Works similarly to `writeStructs`\n */\n // write # encoded structs\n encoding.writeVarUint(restEncoder, partStructs.written);\n // write the rest of the fragment\n encoding.writeUint8Array(restEncoder, partStructs.restEncoder);\n }\n};\n\n/**\n * @param {Uint8Array} update\n * @param {function(Item|GC|Skip):Item|GC|Skip} blockTransformer\n * @param {typeof UpdateDecoderV2 | typeof UpdateDecoderV1} YDecoder\n * @param {typeof UpdateEncoderV2 | typeof UpdateEncoderV1 } YEncoder\n */\nconst convertUpdateFormat = (update, blockTransformer, YDecoder, YEncoder) => {\n const updateDecoder = new YDecoder(decoding.createDecoder(update));\n const lazyDecoder = new LazyStructReader(updateDecoder, false);\n const updateEncoder = new YEncoder();\n const lazyWriter = new LazyStructWriter(updateEncoder);\n for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {\n writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0);\n }\n finishLazyStructWriting(lazyWriter);\n const ds = readDeleteSet(updateDecoder);\n writeDeleteSet(updateEncoder, ds);\n return updateEncoder.toUint8Array()\n};\n\n/**\n * @typedef {Object} ObfuscatorOptions\n * @property {boolean} [ObfuscatorOptions.formatting=true]\n * @property {boolean} [ObfuscatorOptions.subdocs=true]\n * @property {boolean} [ObfuscatorOptions.yxml=true] Whether to obfuscate nodeName / hookName\n */\n\n/**\n * @param {ObfuscatorOptions} obfuscator\n */\nconst createObfuscator = ({ formatting = true, subdocs = true, yxml = true } = {}) => {\n let i = 0;\n const mapKeyCache = map.create();\n const nodeNameCache = map.create();\n const formattingKeyCache = map.create();\n const formattingValueCache = map.create();\n formattingValueCache.set(null, null); // end of a formatting range should always be the end of a formatting range\n /**\n * @param {Item|GC|Skip} block\n * @return {Item|GC|Skip}\n */\n return block => {\n switch (block.constructor) {\n case GC:\n case Skip:\n return block\n case Item: {\n const item = /** @type {Item} */ (block);\n const content = item.content;\n switch (content.constructor) {\n case ContentDeleted:\n break\n case ContentType: {\n if (yxml) {\n const type = /** @type {ContentType} */ (content).type;\n if (type instanceof YXmlElement) {\n type.nodeName = map.setIfUndefined(nodeNameCache, type.nodeName, () => 'node-' + i);\n }\n if (type instanceof YXmlHook) {\n type.hookName = map.setIfUndefined(nodeNameCache, type.hookName, () => 'hook-' + i);\n }\n }\n break\n }\n case ContentAny: {\n const c = /** @type {ContentAny} */ (content);\n c.arr = c.arr.map(() => i);\n break\n }\n case ContentBinary: {\n const c = /** @type {ContentBinary} */ (content);\n c.content = new Uint8Array([i]);\n break\n }\n case ContentDoc: {\n const c = /** @type {ContentDoc} */ (content);\n if (subdocs) {\n c.opts = {};\n c.doc.guid = i + '';\n }\n break\n }\n case ContentEmbed: {\n const c = /** @type {ContentEmbed} */ (content);\n c.embed = {};\n break\n }\n case ContentFormat: {\n const c = /** @type {ContentFormat} */ (content);\n if (formatting) {\n c.key = map.setIfUndefined(formattingKeyCache, c.key, () => i + '');\n c.value = map.setIfUndefined(formattingValueCache, c.value, () => ({ i }));\n }\n break\n }\n case ContentJSON: {\n const c = /** @type {ContentJSON} */ (content);\n c.arr = c.arr.map(() => i);\n break\n }\n case ContentString: {\n const c = /** @type {ContentString} */ (content);\n c.str = string.repeat((i % 10) + '', c.str.length);\n break\n }\n default:\n // unknown content type\n error.unexpectedCase();\n }\n if (item.parentSub) {\n item.parentSub = map.setIfUndefined(mapKeyCache, item.parentSub, () => i + '');\n }\n i++;\n return block\n }\n default:\n // unknown block-type\n error.unexpectedCase();\n }\n }\n};\n\n/**\n * This function obfuscates the content of a Yjs update. This is useful to share\n * buggy Yjs documents while significantly limiting the possibility that a\n * developer can on the user. Note that it might still be possible to deduce\n * some information by analyzing the \"structure\" of the document or by analyzing\n * the typing behavior using the CRDT-related metadata that is still kept fully\n * intact.\n *\n * @param {Uint8Array} update\n * @param {ObfuscatorOptions} [opts]\n */\nconst obfuscateUpdate = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV1, UpdateEncoderV1);\n\n/**\n * @param {Uint8Array} update\n * @param {ObfuscatorOptions} [opts]\n */\nconst obfuscateUpdateV2 = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV2, UpdateEncoderV2);\n\n/**\n * @param {Uint8Array} update\n */\nconst convertUpdateFormatV1ToV2 = update => convertUpdateFormat(update, f.id, UpdateDecoderV1, UpdateEncoderV2);\n\n/**\n * @param {Uint8Array} update\n */\nconst convertUpdateFormatV2ToV1 = update => convertUpdateFormat(update, f.id, UpdateDecoderV2, UpdateEncoderV1);\n\nconst errorComputeChanges = 'You must not compute changes after the event-handler fired.';\n\n/**\n * @template {AbstractType} T\n * YEvent describes the changes on a YType.\n */\nclass YEvent {\n /**\n * @param {T} target The changed type.\n * @param {Transaction} transaction\n */\n constructor (target, transaction) {\n /**\n * The type on which this event was created on.\n * @type {T}\n */\n this.target = target;\n /**\n * The current target on which the observe callback is called.\n * @type {AbstractType}\n */\n this.currentTarget = target;\n /**\n * The transaction that triggered this event.\n * @type {Transaction}\n */\n this.transaction = transaction;\n /**\n * @type {Object|null}\n */\n this._changes = null;\n /**\n * @type {null | Map}\n */\n this._keys = null;\n /**\n * @type {null | Array<{ insert?: string | Array | object | AbstractType, retain?: number, delete?: number, attributes?: Object }>}\n */\n this._delta = null;\n /**\n * @type {Array|null}\n */\n this._path = null;\n }\n\n /**\n * Computes the path from `y` to the changed type.\n *\n * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with.\n *\n * The following property holds:\n * @example\n * let type = y\n * event.path.forEach(dir => {\n * type = type.get(dir)\n * })\n * type === event.target // => true\n */\n get path () {\n return this._path || (this._path = getPathTo(this.currentTarget, this.target))\n }\n\n /**\n * Check if a struct is deleted by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n deletes (struct) {\n return isDeleted(this.transaction.deleteSet, struct.id)\n }\n\n /**\n * @type {Map}\n */\n get keys () {\n if (this._keys === null) {\n if (this.transaction.doc._transactionCleanups.length === 0) {\n throw error.create(errorComputeChanges)\n }\n const keys = new Map();\n const target = this.target;\n const changed = /** @type Set */ (this.transaction.changed.get(target));\n changed.forEach(key => {\n if (key !== null) {\n const item = /** @type {Item} */ (target._map.get(key));\n /**\n * @type {'delete' | 'add' | 'update'}\n */\n let action;\n let oldValue;\n if (this.adds(item)) {\n let prev = item.left;\n while (prev !== null && this.adds(prev)) {\n prev = prev.left;\n }\n if (this.deletes(item)) {\n if (prev !== null && this.deletes(prev)) {\n action = 'delete';\n oldValue = array.last(prev.content.getContent());\n } else {\n return\n }\n } else {\n if (prev !== null && this.deletes(prev)) {\n action = 'update';\n oldValue = array.last(prev.content.getContent());\n } else {\n action = 'add';\n oldValue = undefined;\n }\n }\n } else {\n if (this.deletes(item)) {\n action = 'delete';\n oldValue = array.last(/** @type {Item} */ item.content.getContent());\n } else {\n return // nop\n }\n }\n keys.set(key, { action, oldValue });\n }\n });\n this._keys = keys;\n }\n return this._keys\n }\n\n /**\n * This is a computed property. Note that this can only be safely computed during the\n * event call. Computing this property after other changes happened might result in\n * unexpected behavior (incorrect computation of deltas). A safe way to collect changes\n * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.\n *\n * @type {Array<{insert?: string | Array | object | AbstractType, retain?: number, delete?: number, attributes?: Object}>}\n */\n get delta () {\n return this.changes.delta\n }\n\n /**\n * Check if a struct is added by this event.\n *\n * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.\n *\n * @param {AbstractStruct} struct\n * @return {boolean}\n */\n adds (struct) {\n return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0)\n }\n\n /**\n * This is a computed property. Note that this can only be safely computed during the\n * event call. Computing this property after other changes happened might result in\n * unexpected behavior (incorrect computation of deltas). A safe way to collect changes\n * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.\n *\n * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string, delete?:number, retain?:number}>}}\n */\n get changes () {\n let changes = this._changes;\n if (changes === null) {\n if (this.transaction.doc._transactionCleanups.length === 0) {\n throw error.create(errorComputeChanges)\n }\n const target = this.target;\n const added = set.create();\n const deleted = set.create();\n /**\n * @type {Array<{insert:Array}|{delete:number}|{retain:number}>}\n */\n const delta = [];\n changes = {\n added,\n deleted,\n delta,\n keys: this.keys\n };\n const changed = /** @type Set */ (this.transaction.changed.get(target));\n if (changed.has(null)) {\n /**\n * @type {any}\n */\n let lastOp = null;\n const packOp = () => {\n if (lastOp) {\n delta.push(lastOp);\n }\n };\n for (let item = target._start; item !== null; item = item.right) {\n if (item.deleted) {\n if (this.deletes(item) && !this.adds(item)) {\n if (lastOp === null || lastOp.delete === undefined) {\n packOp();\n lastOp = { delete: 0 };\n }\n lastOp.delete += item.length;\n deleted.add(item);\n } // else nop\n } else {\n if (this.adds(item)) {\n if (lastOp === null || lastOp.insert === undefined) {\n packOp();\n lastOp = { insert: [] };\n }\n lastOp.insert = lastOp.insert.concat(item.content.getContent());\n added.add(item);\n } else {\n if (lastOp === null || lastOp.retain === undefined) {\n packOp();\n lastOp = { retain: 0 };\n }\n lastOp.retain += item.length;\n }\n }\n }\n if (lastOp !== null && lastOp.retain === undefined) {\n packOp();\n }\n }\n this._changes = changes;\n }\n return /** @type {any} */ (changes)\n }\n}\n\n/**\n * Compute the path from this type to the specified target.\n *\n * @example\n * // `child` should be accessible via `type.get(path[0]).get(path[1])..`\n * const path = type.getPathTo(child)\n * // assuming `type instanceof YArray`\n * console.log(path) // might look like => [2, 'key1']\n * child === type.get(path[0]).get(path[1])\n *\n * @param {AbstractType} parent\n * @param {AbstractType} child target\n * @return {Array} Path to the target\n *\n * @private\n * @function\n */\nconst getPathTo = (parent, child) => {\n const path = [];\n while (child._item !== null && child !== parent) {\n if (child._item.parentSub !== null) {\n // parent is map-ish\n path.unshift(child._item.parentSub);\n } else {\n // parent is array-ish\n let i = 0;\n let c = /** @type {AbstractType} */ (child._item.parent)._start;\n while (c !== child._item && c !== null) {\n if (!c.deleted && c.countable) {\n i += c.length;\n }\n c = c.right;\n }\n path.unshift(i);\n }\n child = /** @type {AbstractType} */ (child._item.parent);\n }\n return path\n};\n\nconst maxSearchMarker = 80;\n\n/**\n * A unique timestamp that identifies each marker.\n *\n * Time is relative,.. this is more like an ever-increasing clock.\n *\n * @type {number}\n */\nlet globalSearchMarkerTimestamp = 0;\n\nclass ArraySearchMarker {\n /**\n * @param {Item} p\n * @param {number} index\n */\n constructor (p, index) {\n p.marker = true;\n this.p = p;\n this.index = index;\n this.timestamp = globalSearchMarkerTimestamp++;\n }\n}\n\n/**\n * @param {ArraySearchMarker} marker\n */\nconst refreshMarkerTimestamp = marker => { marker.timestamp = globalSearchMarkerTimestamp++; };\n\n/**\n * This is rather complex so this function is the only thing that should overwrite a marker\n *\n * @param {ArraySearchMarker} marker\n * @param {Item} p\n * @param {number} index\n */\nconst overwriteMarker = (marker, p, index) => {\n marker.p.marker = false;\n marker.p = p;\n p.marker = true;\n marker.index = index;\n marker.timestamp = globalSearchMarkerTimestamp++;\n};\n\n/**\n * @param {Array} searchMarker\n * @param {Item} p\n * @param {number} index\n */\nconst markPosition = (searchMarker, p, index) => {\n if (searchMarker.length >= maxSearchMarker) {\n // override oldest marker (we don't want to create more objects)\n const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b);\n overwriteMarker(marker, p, index);\n return marker\n } else {\n // create new marker\n const pm = new ArraySearchMarker(p, index);\n searchMarker.push(pm);\n return pm\n }\n};\n\n/**\n * Search marker help us to find positions in the associative array faster.\n *\n * They speed up the process of finding a position without much bookkeeping.\n *\n * A maximum of `maxSearchMarker` objects are created.\n *\n * This function always returns a refreshed marker (updated timestamp)\n *\n * @param {AbstractType} yarray\n * @param {number} index\n */\nconst findMarker = (yarray, index) => {\n if (yarray._start === null || index === 0 || yarray._searchMarker === null) {\n return null\n }\n const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => math.abs(index - a.index) < math.abs(index - b.index) ? a : b);\n let p = yarray._start;\n let pindex = 0;\n if (marker !== null) {\n p = marker.p;\n pindex = marker.index;\n refreshMarkerTimestamp(marker); // we used it, we might need to use it again\n }\n // iterate to right if possible\n while (p.right !== null && pindex < index) {\n if (!p.deleted && p.countable) {\n if (index < pindex + p.length) {\n break\n }\n pindex += p.length;\n }\n p = p.right;\n }\n // iterate to left if necessary (might be that pindex > index)\n while (p.left !== null && pindex > index) {\n p = p.left;\n if (!p.deleted && p.countable) {\n pindex -= p.length;\n }\n }\n // we want to make sure that p can't be merged with left, because that would screw up everything\n // in that cas just return what we have (it is most likely the best marker anyway)\n // iterate to left until p can't be merged with left\n while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) {\n p = p.left;\n if (!p.deleted && p.countable) {\n pindex -= p.length;\n }\n }\n\n // @todo remove!\n // assure position\n // {\n // let start = yarray._start\n // let pos = 0\n // while (start !== p) {\n // if (!start.deleted && start.countable) {\n // pos += start.length\n // }\n // start = /** @type {Item} */ (start.right)\n // }\n // if (pos !== pindex) {\n // debugger\n // throw new Error('Gotcha position fail!')\n // }\n // }\n // if (marker) {\n // if (window.lengthes == null) {\n // window.lengthes = []\n // window.getLengthes = () => window.lengthes.sort((a, b) => a - b)\n // }\n // window.lengthes.push(marker.index - pindex)\n // console.log('distance', marker.index - pindex, 'len', p && p.parent.length)\n // }\n if (marker !== null && math.abs(marker.index - pindex) < /** @type {YText|YArray} */ (p.parent).length / maxSearchMarker) {\n // adjust existing marker\n overwriteMarker(marker, p, pindex);\n return marker\n } else {\n // create new marker\n return markPosition(yarray._searchMarker, p, pindex)\n }\n};\n\n/**\n * Update markers when a change happened.\n *\n * This should be called before doing a deletion!\n *\n * @param {Array} searchMarker\n * @param {number} index\n * @param {number} len If insertion, len is positive. If deletion, len is negative.\n */\nconst updateMarkerChanges = (searchMarker, index, len) => {\n for (let i = searchMarker.length - 1; i >= 0; i--) {\n const m = searchMarker[i];\n if (len > 0) {\n /**\n * @type {Item|null}\n */\n let p = m.p;\n p.marker = false;\n // Ideally we just want to do a simple position comparison, but this will only work if\n // search markers don't point to deleted items for formats.\n // Iterate marker to prev undeleted countable position so we know what to do when updating a position\n while (p && (p.deleted || !p.countable)) {\n p = p.left;\n if (p && !p.deleted && p.countable) {\n // adjust position. the loop should break now\n m.index -= p.length;\n }\n }\n if (p === null || p.marker === true) {\n // remove search marker if updated position is null or if position is already marked\n searchMarker.splice(i, 1);\n continue\n }\n m.p = p;\n p.marker = true;\n }\n if (index < m.index || (len > 0 && index === m.index)) { // a simple index <= m.index check would actually suffice\n m.index = math.max(index, m.index + len);\n }\n }\n};\n\n/**\n * Accumulate all (list) children of a type and return them as an Array.\n *\n * @param {AbstractType} t\n * @return {Array}\n */\nconst getTypeChildren = t => {\n let s = t._start;\n const arr = [];\n while (s) {\n arr.push(s);\n s = s.right;\n }\n return arr\n};\n\n/**\n * Call event listeners with an event. This will also add an event to all\n * parents (for `.observeDeep` handlers).\n *\n * @template EventType\n * @param {AbstractType} type\n * @param {Transaction} transaction\n * @param {EventType} event\n */\nconst callTypeObservers = (type, transaction, event) => {\n const changedType = type;\n const changedParentTypes = transaction.changedParentTypes;\n while (true) {\n // @ts-ignore\n map.setIfUndefined(changedParentTypes, type, () => []).push(event);\n if (type._item === null) {\n break\n }\n type = /** @type {AbstractType} */ (type._item.parent);\n }\n callEventHandlerListeners(changedType._eH, event, transaction);\n};\n\n/**\n * @template EventType\n * Abstract Yjs Type class\n */\nclass AbstractType {\n constructor () {\n /**\n * @type {Item|null}\n */\n this._item = null;\n /**\n * @type {Map}\n */\n this._map = new Map();\n /**\n * @type {Item|null}\n */\n this._start = null;\n /**\n * @type {Doc|null}\n */\n this.doc = null;\n this._length = 0;\n /**\n * Event handlers\n * @type {EventHandler}\n */\n this._eH = createEventHandler();\n /**\n * Deep event handlers\n * @type {EventHandler>,Transaction>}\n */\n this._dEH = createEventHandler();\n /**\n * @type {null | Array}\n */\n this._searchMarker = null;\n }\n\n /**\n * @return {AbstractType|null}\n */\n get parent () {\n return this._item ? /** @type {AbstractType} */ (this._item.parent) : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item|null} item\n */\n _integrate (y, item) {\n this.doc = y;\n this._item = item;\n }\n\n /**\n * @return {AbstractType}\n */\n _copy () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {AbstractType}\n */\n clone () {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder\n */\n _write (_encoder) { }\n\n /**\n * The first non-deleted item\n */\n get _first () {\n let n = this._start;\n while (n !== null && n.deleted) {\n n = n.right;\n }\n return n\n }\n\n /**\n * Creates YEvent and calls all type observers.\n * Must be implemented by each type.\n *\n * @param {Transaction} transaction\n * @param {Set} _parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, _parentSubs) {\n if (!transaction.local && this._searchMarker) {\n this._searchMarker.length = 0;\n }\n }\n\n /**\n * Observe all events that are created on this type.\n *\n * @param {function(EventType, Transaction):void} f Observer function\n */\n observe (f) {\n addEventHandlerListener(this._eH, f);\n }\n\n /**\n * Observe all events that are created by this type and its children.\n *\n * @param {function(Array>,Transaction):void} f Observer function\n */\n observeDeep (f) {\n addEventHandlerListener(this._dEH, f);\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(EventType,Transaction):void} f Observer function\n */\n unobserve (f) {\n removeEventHandlerListener(this._eH, f);\n }\n\n /**\n * Unregister an observer function.\n *\n * @param {function(Array>,Transaction):void} f Observer function\n */\n unobserveDeep (f) {\n removeEventHandlerListener(this._dEH, f);\n }\n\n /**\n * @abstract\n * @return {any}\n */\n toJSON () {}\n}\n\n/**\n * @param {AbstractType} type\n * @param {number} start\n * @param {number} end\n * @return {Array}\n *\n * @private\n * @function\n */\nconst typeListSlice = (type, start, end) => {\n if (start < 0) {\n start = type._length + start;\n }\n if (end < 0) {\n end = type._length + end;\n }\n let len = end - start;\n const cs = [];\n let n = type._start;\n while (n !== null && len > 0) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent();\n if (c.length <= start) {\n start -= c.length;\n } else {\n for (let i = start; i < c.length && len > 0; i++) {\n cs.push(c[i]);\n len--;\n }\n start = 0;\n }\n }\n n = n.right;\n }\n return cs\n};\n\n/**\n * @param {AbstractType} type\n * @return {Array}\n *\n * @private\n * @function\n */\nconst typeListToArray = type => {\n const cs = [];\n let n = type._start;\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent();\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i]);\n }\n }\n n = n.right;\n }\n return cs\n};\n\n/**\n * @param {AbstractType} type\n * @param {Snapshot} snapshot\n * @return {Array}\n *\n * @private\n * @function\n */\nconst typeListToArraySnapshot = (type, snapshot) => {\n const cs = [];\n let n = type._start;\n while (n !== null) {\n if (n.countable && isVisible(n, snapshot)) {\n const c = n.content.getContent();\n for (let i = 0; i < c.length; i++) {\n cs.push(c[i]);\n }\n }\n n = n.right;\n }\n return cs\n};\n\n/**\n * Executes a provided function on once on every element of this YArray.\n *\n * @param {AbstractType} type\n * @param {function(any,number,any):void} f A function to execute on every element of this YArray.\n *\n * @private\n * @function\n */\nconst typeListForEach = (type, f) => {\n let index = 0;\n let n = type._start;\n while (n !== null) {\n if (n.countable && !n.deleted) {\n const c = n.content.getContent();\n for (let i = 0; i < c.length; i++) {\n f(c[i], index++, type);\n }\n }\n n = n.right;\n }\n};\n\n/**\n * @template C,R\n * @param {AbstractType} type\n * @param {function(C,number,AbstractType):R} f\n * @return {Array}\n *\n * @private\n * @function\n */\nconst typeListMap = (type, f) => {\n /**\n * @type {Array}\n */\n const result = [];\n typeListForEach(type, (c, i) => {\n result.push(f(c, i, type));\n });\n return result\n};\n\n/**\n * @param {AbstractType} type\n * @return {IterableIterator}\n *\n * @private\n * @function\n */\nconst typeListCreateIterator = type => {\n let n = type._start;\n /**\n * @type {Array|null}\n */\n let currentContent = null;\n let currentContentIndex = 0;\n return {\n [Symbol.iterator] () {\n return this\n },\n next: () => {\n // find some content\n if (currentContent === null) {\n while (n !== null && n.deleted) {\n n = n.right;\n }\n // check if we reached the end, no need to check currentContent, because it does not exist\n if (n === null) {\n return {\n done: true,\n value: undefined\n }\n }\n // we found n, so we can set currentContent\n currentContent = n.content.getContent();\n currentContentIndex = 0;\n n = n.right; // we used the content of n, now iterate to next\n }\n const value = currentContent[currentContentIndex++];\n // check if we need to empty currentContent\n if (currentContent.length <= currentContentIndex) {\n currentContent = null;\n }\n return {\n done: false,\n value\n }\n }\n }\n};\n\n/**\n * @param {AbstractType} type\n * @param {number} index\n * @return {any}\n *\n * @private\n * @function\n */\nconst typeListGet = (type, index) => {\n const marker = findMarker(type, index);\n let n = type._start;\n if (marker !== null) {\n n = marker.p;\n index -= marker.index;\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n return n.content.getContent()[index]\n }\n index -= n.length;\n }\n }\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {Item?} referenceItem\n * @param {Array|Array|boolean|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nconst typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => {\n let left = referenceItem;\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n const store = doc.store;\n const right = referenceItem === null ? parent._start : referenceItem.right;\n /**\n * @type {Array|number|null>}\n */\n let jsonContent = [];\n const packJsonContent = () => {\n if (jsonContent.length > 0) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent));\n left.integrate(transaction, 0);\n jsonContent = [];\n }\n };\n content.forEach(c => {\n if (c === null) {\n jsonContent.push(c);\n } else {\n switch (c.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n jsonContent.push(c);\n break\n default:\n packJsonContent();\n switch (c.constructor) {\n case Uint8Array:\n case ArrayBuffer:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(/** @type {Uint8Array} */ (c))));\n left.integrate(transaction, 0);\n break\n case Doc:\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(/** @type {Doc} */ (c)));\n left.integrate(transaction, 0);\n break\n default:\n if (c instanceof AbstractType) {\n left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c));\n left.integrate(transaction, 0);\n } else {\n throw new Error('Unexpected content type in insert operation')\n }\n }\n }\n }\n });\n packJsonContent();\n};\n\nconst lengthExceeded = () => error.create('Length exceeded!');\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {Array|Array|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nconst typeListInsertGenerics = (transaction, parent, index, content) => {\n if (index > parent._length) {\n throw lengthExceeded()\n }\n if (index === 0) {\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, index, content.length);\n }\n return typeListInsertGenericsAfter(transaction, parent, null, content)\n }\n const startIndex = index;\n const marker = findMarker(parent, index);\n let n = parent._start;\n if (marker !== null) {\n n = marker.p;\n index -= marker.index;\n // we need to iterate one to the left so that the algorithm works\n if (index === 0) {\n // @todo refactor this as it actually doesn't consider formats\n n = n.prev; // important! get the left undeleted item so that we can actually decrease index\n index += (n && n.countable && !n.deleted) ? n.length : 0;\n }\n }\n for (; n !== null; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index <= n.length) {\n if (index < n.length) {\n // insert in-between\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));\n }\n break\n }\n index -= n.length;\n }\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, content.length);\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n};\n\n/**\n * Pushing content is special as we generally want to push after the last item. So we don't have to update\n * the serach marker.\n *\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {Array|Array|number|null|string|Uint8Array>} content\n *\n * @private\n * @function\n */\nconst typeListPushGenerics = (transaction, parent, content) => {\n // Use the marker with the highest index and iterate to the right.\n const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start });\n let n = marker.p;\n if (n) {\n while (n.right) {\n n = n.right;\n }\n }\n return typeListInsertGenericsAfter(transaction, parent, n, content)\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {number} length\n *\n * @private\n * @function\n */\nconst typeListDelete = (transaction, parent, index, length) => {\n if (length === 0) { return }\n const startIndex = index;\n const startLength = length;\n const marker = findMarker(parent, index);\n let n = parent._start;\n if (marker !== null) {\n n = marker.p;\n index -= marker.index;\n }\n // compute the first item to be deleted\n for (; n !== null && index > 0; n = n.right) {\n if (!n.deleted && n.countable) {\n if (index < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));\n }\n index -= n.length;\n }\n }\n // delete all items until done\n while (length > 0 && n !== null) {\n if (!n.deleted) {\n if (length < n.length) {\n getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length));\n }\n n.delete(transaction);\n length -= n.length;\n }\n n = n.right;\n }\n if (length > 0) {\n throw lengthExceeded()\n }\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, startIndex, -startLength + length /* in case we remove the above exception */);\n }\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n *\n * @private\n * @function\n */\nconst typeMapDelete = (transaction, parent, key) => {\n const c = parent._map.get(key);\n if (c !== undefined) {\n c.delete(transaction);\n }\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Object|number|null|Array|string|Uint8Array|AbstractType} value\n *\n * @private\n * @function\n */\nconst typeMapSet = (transaction, parent, key, value) => {\n const left = parent._map.get(key) || null;\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n let content;\n if (value == null) {\n content = new ContentAny([value]);\n } else {\n switch (value.constructor) {\n case Number:\n case Object:\n case Boolean:\n case Array:\n case String:\n content = new ContentAny([value]);\n break\n case Uint8Array:\n content = new ContentBinary(/** @type {Uint8Array} */ (value));\n break\n case Doc:\n content = new ContentDoc(/** @type {Doc} */ (value));\n break\n default:\n if (value instanceof AbstractType) {\n content = new ContentType(value);\n } else {\n throw new Error('Unexpected content type')\n }\n }\n }\n new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0);\n};\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nconst typeMapGet = (parent, key) => {\n const val = parent._map.get(key);\n return val !== undefined && !val.deleted ? val.content.getContent()[val.length - 1] : undefined\n};\n\n/**\n * @param {AbstractType} parent\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined>}\n *\n * @private\n * @function\n */\nconst typeMapGetAll = (parent) => {\n /**\n * @type {Object}\n */\n const res = {};\n parent._map.forEach((value, key) => {\n if (!value.deleted) {\n res[key] = value.content.getContent()[value.length - 1];\n }\n });\n return res\n};\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @return {boolean}\n *\n * @private\n * @function\n */\nconst typeMapHas = (parent, key) => {\n const val = parent._map.get(key);\n return val !== undefined && !val.deleted\n};\n\n/**\n * @param {AbstractType} parent\n * @param {string} key\n * @param {Snapshot} snapshot\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined}\n *\n * @private\n * @function\n */\nconst typeMapGetSnapshot = (parent, key, snapshot) => {\n let v = parent._map.get(key) || null;\n while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {\n v = v.left;\n }\n return v !== null && isVisible(v, snapshot) ? v.content.getContent()[v.length - 1] : undefined\n};\n\n/**\n * @param {AbstractType} parent\n * @param {Snapshot} snapshot\n * @return {Object|number|null|Array|string|Uint8Array|AbstractType|undefined>}\n *\n * @private\n * @function\n */\nconst typeMapGetAllSnapshot = (parent, snapshot) => {\n /**\n * @type {Object}\n */\n const res = {};\n parent._map.forEach((value, key) => {\n /**\n * @type {Item|null}\n */\n let v = value;\n while (v !== null && (!snapshot.sv.has(v.id.client) || v.id.clock >= (snapshot.sv.get(v.id.client) || 0))) {\n v = v.left;\n }\n if (v !== null && isVisible(v, snapshot)) {\n res[key] = v.content.getContent()[v.length - 1];\n }\n });\n return res\n};\n\n/**\n * @param {Map} map\n * @return {IterableIterator>}\n *\n * @private\n * @function\n */\nconst createMapIterator = map => iterator.iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted);\n\n/**\n * @module YArray\n */\n\n\n/**\n * Event that describes the changes on a YArray\n * @template T\n * @extends YEvent>\n */\nclass YArrayEvent extends YEvent {}\n\n/**\n * A shared Array implementation.\n * @template T\n * @extends AbstractType>\n * @implements {Iterable}\n */\nclass YArray extends AbstractType {\n constructor () {\n super();\n /**\n * @type {Array?}\n * @private\n */\n this._prelimContent = [];\n /**\n * @type {Array}\n */\n this._searchMarker = [];\n }\n\n /**\n * Construct a new YArray containing the specified items.\n * @template {Object|Array|number|null|string|Uint8Array} T\n * @param {Array} items\n * @return {YArray}\n */\n static from (items) {\n /**\n * @type {YArray}\n */\n const a = new YArray();\n a.push(items);\n return a\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item);\n this.insert(0, /** @type {Array} */ (this._prelimContent));\n this._prelimContent = null;\n }\n\n /**\n * @return {YArray}\n */\n _copy () {\n return new YArray()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YArray}\n */\n clone () {\n /**\n * @type {YArray}\n */\n const arr = new YArray();\n arr.insert(0, this.toArray().map(el =>\n el instanceof AbstractType ? /** @type {typeof el} */ (el.clone()) : el\n ));\n return arr\n }\n\n get length () {\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Creates YArrayEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs);\n callTypeObservers(this, transaction, new YArrayEvent(this, transaction));\n }\n\n /**\n * Inserts new content at an index.\n *\n * Important: This function expects an array of content. Not just a content\n * object. The reason for this \"weirdness\" is that inserting several elements\n * is very efficient when it is done as a single operation.\n *\n * @example\n * // Insert character 'a' at position 0\n * yarray.insert(0, ['a'])\n * // Insert numbers 1, 2 at position 1\n * yarray.insert(1, [1, 2])\n *\n * @param {number} index The index to insert content at.\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, /** @type {any} */ (content));\n });\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, 0, ...content);\n }\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array} content Array of content to append.\n *\n * @todo Use the following implementation in all types.\n */\n push (content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListPushGenerics(transaction, this, /** @type {any} */ (content));\n });\n } else {\n /** @type {Array} */ (this._prelimContent).push(...content);\n }\n }\n\n /**\n * Prepends content to this YArray.\n *\n * @param {Array} content Array of content to prepend.\n */\n unshift (content) {\n this.insert(0, content);\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} length The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length);\n });\n } else {\n /** @type {Array} */ (this._prelimContent).splice(index, length);\n }\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {T}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Returns a portion of this YArray into a JavaScript Array selected\n * from start to end (end not included).\n *\n * @param {number} [start]\n * @param {number} [end]\n * @return {Array}\n */\n slice (start = 0, end = this.length) {\n return typeListSlice(this, start, end)\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Array}\n */\n toJSON () {\n return this.map(c => c instanceof AbstractType ? c.toJSON() : c)\n }\n\n /**\n * Returns an Array with the result of calling a provided function on every\n * element of this YArray.\n *\n * @template M\n * @param {function(T,number,YArray):M} f Function that produces an element of the new Array\n * @return {Array} A new array with each element being the result of the\n * callback function\n */\n map (f) {\n return typeListMap(this, /** @type {any} */ (f))\n }\n\n /**\n * Executes a provided function once on every element of this YArray.\n *\n * @param {function(T,number,YArray):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n typeListForEach(this, f);\n }\n\n /**\n * @return {IterableIterator}\n */\n [Symbol.iterator] () {\n return typeListCreateIterator(this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YArrayRefID);\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n *\n * @private\n * @function\n */\nconst readYArray = _decoder => new YArray();\n\n/**\n * @module YMap\n */\n\n\n/**\n * @template T\n * @extends YEvent>\n * Event that describes the changes on a YMap.\n */\nclass YMapEvent extends YEvent {\n /**\n * @param {YMap} ymap The YArray that changed.\n * @param {Transaction} transaction\n * @param {Set} subs The keys that changed.\n */\n constructor (ymap, transaction, subs) {\n super(ymap, transaction);\n this.keysChanged = subs;\n }\n}\n\n/**\n * @template MapType\n * A shared Map implementation.\n *\n * @extends AbstractType>\n * @implements {Iterable<[string, MapType]>}\n */\nclass YMap extends AbstractType {\n /**\n *\n * @param {Iterable=} entries - an optional iterable to initialize the YMap\n */\n constructor (entries) {\n super();\n /**\n * @type {Map?}\n * @private\n */\n this._prelimContent = null;\n\n if (entries === undefined) {\n this._prelimContent = new Map();\n } else {\n this._prelimContent = new Map(entries);\n }\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;/** @type {Map} */ (this._prelimContent).forEach((value, key) => {\n this.set(key, value);\n });\n this._prelimContent = null;\n }\n\n /**\n * @return {YMap}\n */\n _copy () {\n return new YMap()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YMap}\n */\n clone () {\n /**\n * @type {YMap}\n */\n const map = new YMap();\n this.forEach((value, key) => {\n map.set(key, value instanceof AbstractType ? /** @type {typeof value} */ (value.clone()) : value);\n });\n return map\n }\n\n /**\n * Creates YMapEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs));\n }\n\n /**\n * Transforms this Shared Type to a JSON object.\n *\n * @return {Object}\n */\n toJSON () {\n /**\n * @type {Object}\n */\n const map = {};\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n const v = item.content.getContent()[item.length - 1];\n map[key] = v instanceof AbstractType ? v.toJSON() : v;\n }\n });\n return map\n }\n\n /**\n * Returns the size of the YMap (count of key/value pairs)\n *\n * @return {number}\n */\n get size () {\n return [...createMapIterator(this._map)].length\n }\n\n /**\n * Returns the keys for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n keys () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[0])\n }\n\n /**\n * Returns the values for each element in the YMap Type.\n *\n * @return {IterableIterator}\n */\n values () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => v[1].content.getContent()[v[1].length - 1])\n }\n\n /**\n * Returns an Iterator of [key, value] pairs\n *\n * @return {IterableIterator<[string, MapType]>}\n */\n entries () {\n return iterator.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => /** @type {any} */ ([v[0], v[1].content.getContent()[v[1].length - 1]]))\n }\n\n /**\n * Executes a provided function on once on every key-value pair.\n *\n * @param {function(MapType,string,YMap):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n this._map.forEach((item, key) => {\n if (!item.deleted) {\n f(item.content.getContent()[item.length - 1], key, this);\n }\n });\n }\n\n /**\n * Returns an Iterator of [key, value] pairs\n *\n * @return {IterableIterator<[string, MapType]>}\n */\n [Symbol.iterator] () {\n return this.entries()\n }\n\n /**\n * Remove a specified element from this YMap.\n *\n * @param {string} key The key of the element to remove.\n */\n delete (key) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, key);\n });\n } else {\n /** @type {Map} */ (this._prelimContent).delete(key);\n }\n }\n\n /**\n * Adds or updates an element with a specified key and value.\n * @template {MapType} VAL\n *\n * @param {string} key The key of the element to add to this YMap\n * @param {VAL} value The value of the element to add\n * @return {VAL}\n */\n set (key, value) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, key, /** @type {any} */ (value));\n });\n } else {\n /** @type {Map} */ (this._prelimContent).set(key, value);\n }\n return value\n }\n\n /**\n * Returns a specified element from this YMap.\n *\n * @param {string} key\n * @return {MapType|undefined}\n */\n get (key) {\n return /** @type {any} */ (typeMapGet(this, key))\n }\n\n /**\n * Returns a boolean indicating whether the specified key exists or not.\n *\n * @param {string} key The key to test.\n * @return {boolean}\n */\n has (key) {\n return typeMapHas(this, key)\n }\n\n /**\n * Removes all elements from this YMap.\n */\n clear () {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n this.forEach(function (_value, key, map) {\n typeMapDelete(transaction, map, key);\n });\n });\n } else {\n /** @type {Map} */ (this._prelimContent).clear();\n }\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YMapRefID);\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n *\n * @private\n * @function\n */\nconst readYMap = _decoder => new YMap();\n\n/**\n * @module YText\n */\n\n\n/**\n * @param {any} a\n * @param {any} b\n * @return {boolean}\n */\nconst equalAttrs = (a, b) => a === b || (typeof a === 'object' && typeof b === 'object' && a && b && object.equalFlat(a, b));\n\nclass ItemTextListPosition {\n /**\n * @param {Item|null} left\n * @param {Item|null} right\n * @param {number} index\n * @param {Map} currentAttributes\n */\n constructor (left, right, index, currentAttributes) {\n this.left = left;\n this.right = right;\n this.index = index;\n this.currentAttributes = currentAttributes;\n }\n\n /**\n * Only call this if you know that this.right is defined\n */\n forward () {\n if (this.right === null) {\n error.unexpectedCase();\n }\n switch (this.right.content.constructor) {\n case ContentFormat:\n if (!this.right.deleted) {\n updateCurrentAttributes(this.currentAttributes, /** @type {ContentFormat} */ (this.right.content));\n }\n break\n default:\n if (!this.right.deleted) {\n this.index += this.right.length;\n }\n break\n }\n this.left = this.right;\n this.right = this.right.right;\n }\n}\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} pos\n * @param {number} count steps to move forward\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findNextPosition = (transaction, pos, count) => {\n while (pos.right !== null && count > 0) {\n switch (pos.right.content.constructor) {\n case ContentFormat:\n if (!pos.right.deleted) {\n updateCurrentAttributes(pos.currentAttributes, /** @type {ContentFormat} */ (pos.right.content));\n }\n break\n default:\n if (!pos.right.deleted) {\n if (count < pos.right.length) {\n // split right\n getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count));\n }\n pos.index += pos.right.length;\n count -= pos.right.length;\n }\n break\n }\n pos.left = pos.right;\n pos.right = pos.right.right;\n // pos.forward() - we don't forward because that would halve the performance because we already do the checks above\n }\n return pos\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {number} index\n * @param {boolean} useSearchMarker\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findPosition = (transaction, parent, index, useSearchMarker) => {\n const currentAttributes = new Map();\n const marker = useSearchMarker ? findMarker(parent, index) : null;\n if (marker) {\n const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes);\n return findNextPosition(transaction, pos, index - marker.index)\n } else {\n const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes);\n return findNextPosition(transaction, pos, index)\n }\n};\n\n/**\n * Negate applied formats\n *\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Map} negatedAttributes\n *\n * @private\n * @function\n */\nconst insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {\n // check if we really need to remove attributes\n while (\n currPos.right !== null && (\n currPos.right.deleted === true || (\n currPos.right.content.constructor === ContentFormat &&\n equalAttrs(negatedAttributes.get(/** @type {ContentFormat} */ (currPos.right.content).key), /** @type {ContentFormat} */ (currPos.right.content).value)\n )\n )\n ) {\n if (!currPos.right.deleted) {\n negatedAttributes.delete(/** @type {ContentFormat} */ (currPos.right.content).key);\n }\n currPos.forward();\n }\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n negatedAttributes.forEach((val, key) => {\n const left = currPos.left;\n const right = currPos.right;\n const nextFormat = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val));\n nextFormat.integrate(transaction, 0);\n currPos.right = nextFormat;\n currPos.forward();\n });\n};\n\n/**\n * @param {Map} currentAttributes\n * @param {ContentFormat} format\n *\n * @private\n * @function\n */\nconst updateCurrentAttributes = (currentAttributes, format) => {\n const { key, value } = format;\n if (value === null) {\n currentAttributes.delete(key);\n } else {\n currentAttributes.set(key, value);\n }\n};\n\n/**\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst minimizeAttributeChanges = (currPos, attributes) => {\n // go right while attributes[right.key] === right.value (or right is deleted)\n while (true) {\n if (currPos.right === null) {\n break\n } else if (currPos.right.deleted || (currPos.right.content.constructor === ContentFormat && equalAttrs(attributes[(/** @type {ContentFormat} */ (currPos.right.content)).key] ?? null, /** @type {ContentFormat} */ (currPos.right.content).value))) ; else {\n break\n }\n currPos.forward();\n }\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {Object} attributes\n * @return {Map}\n *\n * @private\n * @function\n **/\nconst insertAttributes = (transaction, parent, currPos, attributes) => {\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n const negatedAttributes = new Map();\n // insert format-start items\n for (const key in attributes) {\n const val = attributes[key];\n const currentVal = currPos.currentAttributes.get(key) ?? null;\n if (!equalAttrs(currentVal, val)) {\n // save negated attribute (set null if currentVal undefined)\n negatedAttributes.set(key, currentVal);\n const { left, right } = currPos;\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val));\n currPos.right.integrate(transaction, 0);\n currPos.forward();\n }\n }\n return negatedAttributes\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {string|object|AbstractType} text\n * @param {Object} attributes\n *\n * @private\n * @function\n **/\nconst insertText = (transaction, parent, currPos, text, attributes) => {\n currPos.currentAttributes.forEach((_val, key) => {\n if (attributes[key] === undefined) {\n attributes[key] = null;\n }\n });\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n minimizeAttributeChanges(currPos, attributes);\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);\n // insert content\n const content = text.constructor === String ? new ContentString(/** @type {string} */ (text)) : (text instanceof AbstractType ? new ContentType(text) : new ContentEmbed(text));\n let { left, right, index } = currPos;\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength());\n }\n right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content);\n right.integrate(transaction, 0);\n currPos.right = right;\n currPos.index = index;\n currPos.forward();\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);\n};\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType} parent\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @param {Object} attributes\n *\n * @private\n * @function\n */\nconst formatText = (transaction, parent, currPos, length, attributes) => {\n const doc = transaction.doc;\n const ownClientId = doc.clientID;\n minimizeAttributeChanges(currPos, attributes);\n const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);\n // iterate until first non-format or null is found\n // delete all formats with attributes[format.key] != null\n // also check the attributes after the first non-format as we do not want to insert redundant negated attributes there\n // eslint-disable-next-line no-labels\n iterationLoop: while (\n currPos.right !== null &&\n (length > 0 ||\n (\n negatedAttributes.size > 0 &&\n (currPos.right.deleted || currPos.right.content.constructor === ContentFormat)\n )\n )\n ) {\n if (!currPos.right.deleted) {\n switch (currPos.right.content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (currPos.right.content);\n const attr = attributes[key];\n if (attr !== undefined) {\n if (equalAttrs(attr, value)) {\n negatedAttributes.delete(key);\n } else {\n if (length === 0) {\n // no need to further extend negatedAttributes\n // eslint-disable-next-line no-labels\n break iterationLoop\n }\n negatedAttributes.set(key, value);\n }\n currPos.right.delete(transaction);\n } else {\n currPos.currentAttributes.set(key, value);\n }\n break\n }\n default:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length));\n }\n length -= currPos.right.length;\n break\n }\n }\n currPos.forward();\n }\n // Quill just assumes that the editor starts with a newline and that it always\n // ends with a newline. We only insert that newline when a new newline is\n // inserted - i.e when length is bigger than type.length\n if (length > 0) {\n let newlines = '';\n for (; length > 0; length--) {\n newlines += '\\n';\n }\n currPos.right = new Item(createID(ownClientId, getState(doc.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines));\n currPos.right.integrate(transaction, 0);\n currPos.forward();\n }\n insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);\n};\n\n/**\n * Call this function after string content has been deleted in order to\n * clean up formatting Items.\n *\n * @param {Transaction} transaction\n * @param {Item} start\n * @param {Item|null} curr exclusive end, automatically iterates to the next Content Item\n * @param {Map} startAttributes\n * @param {Map} currAttributes\n * @return {number} The amount of formatting Items deleted.\n *\n * @function\n */\nconst cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => {\n /**\n * @type {Item|null}\n */\n let end = start;\n /**\n * @type {Map}\n */\n const endFormats = map.create();\n while (end && (!end.countable || end.deleted)) {\n if (!end.deleted && end.content.constructor === ContentFormat) {\n const cf = /** @type {ContentFormat} */ (end.content);\n endFormats.set(cf.key, cf);\n }\n end = end.right;\n }\n let cleanups = 0;\n let reachedCurr = false;\n while (start !== end) {\n if (curr === start) {\n reachedCurr = true;\n }\n if (!start.deleted) {\n const content = start.content;\n switch (content.constructor) {\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (content);\n const startAttrValue = startAttributes.get(key) ?? null;\n if (endFormats.get(key) !== content || startAttrValue === value) {\n // Either this format is overwritten or it is not necessary because the attribute already existed.\n start.delete(transaction);\n cleanups++;\n if (!reachedCurr && (currAttributes.get(key) ?? null) === value && startAttrValue !== value) {\n if (startAttrValue === null) {\n currAttributes.delete(key);\n } else {\n currAttributes.set(key, startAttrValue);\n }\n }\n }\n if (!reachedCurr && !start.deleted) {\n updateCurrentAttributes(currAttributes, /** @type {ContentFormat} */ (content));\n }\n break\n }\n }\n }\n start = /** @type {Item} */ (start.right);\n }\n return cleanups\n};\n\n/**\n * @param {Transaction} transaction\n * @param {Item | null} item\n */\nconst cleanupContextlessFormattingGap = (transaction, item) => {\n // iterate until item.right is null or content\n while (item && item.right && (item.right.deleted || !item.right.countable)) {\n item = item.right;\n }\n const attrs = new Set();\n // iterate back until a content item is found\n while (item && (item.deleted || !item.countable)) {\n if (!item.deleted && item.content.constructor === ContentFormat) {\n const key = /** @type {ContentFormat} */ (item.content).key;\n if (attrs.has(key)) {\n item.delete(transaction);\n } else {\n attrs.add(key);\n }\n }\n item = item.left;\n }\n};\n\n/**\n * This function is experimental and subject to change / be removed.\n *\n * Ideally, we don't need this function at all. Formatting attributes should be cleaned up\n * automatically after each change. This function iterates twice over the complete YText type\n * and removes unnecessary formatting attributes. This is also helpful for testing.\n *\n * This function won't be exported anymore as soon as there is confidence that the YText type works as intended.\n *\n * @param {YText} type\n * @return {number} How many formatting attributes have been cleaned up.\n */\nconst cleanupYTextFormatting = type => {\n let res = 0;\n transact(/** @type {Doc} */ (type.doc), transaction => {\n let start = /** @type {Item} */ (type._start);\n let end = type._start;\n let startAttributes = map.create();\n const currentAttributes = map.copy(startAttributes);\n while (end) {\n if (end.deleted === false) {\n switch (end.content.constructor) {\n case ContentFormat:\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (end.content));\n break\n default:\n res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes);\n startAttributes = map.copy(currentAttributes);\n start = end;\n break\n }\n }\n end = end.right;\n }\n });\n return res\n};\n\n/**\n * This will be called by the transction once the event handlers are called to potentially cleanup\n * formatting attributes.\n *\n * @param {Transaction} transaction\n */\nconst cleanupYTextAfterTransaction = transaction => {\n /**\n * @type {Set}\n */\n const needFullCleanup = new Set();\n // check if another formatting item was inserted\n const doc = transaction.doc;\n for (const [client, afterClock] of transaction.afterState.entries()) {\n const clock = transaction.beforeState.get(client) || 0;\n if (afterClock === clock) {\n continue\n }\n iterateStructs(transaction, /** @type {Array} */ (doc.store.clients.get(client)), clock, afterClock, item => {\n if (\n !item.deleted && /** @type {Item} */ (item).content.constructor === ContentFormat && item.constructor !== GC\n ) {\n needFullCleanup.add(/** @type {any} */ (item).parent);\n }\n });\n }\n // cleanup in a new transaction\n transact(doc, (t) => {\n iterateDeletedStructs(transaction, transaction.deleteSet, item => {\n if (item instanceof GC || !(/** @type {YText} */ (item.parent)._hasFormatting) || needFullCleanup.has(/** @type {YText} */ (item.parent))) {\n return\n }\n const parent = /** @type {YText} */ (item.parent);\n if (item.content.constructor === ContentFormat) {\n needFullCleanup.add(parent);\n } else {\n // If no formatting attribute was inserted or deleted, we can make due with contextless\n // formatting cleanups.\n // Contextless: it is not necessary to compute currentAttributes for the affected position.\n cleanupContextlessFormattingGap(t, item);\n }\n });\n // If a formatting item was inserted, we simply clean the whole type.\n // We need to compute currentAttributes for the current position anyway.\n for (const yText of needFullCleanup) {\n cleanupYTextFormatting(yText);\n }\n });\n};\n\n/**\n * @param {Transaction} transaction\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst deleteText = (transaction, currPos, length) => {\n const startLength = length;\n const startAttrs = map.copy(currPos.currentAttributes);\n const start = currPos.right;\n while (length > 0 && currPos.right !== null) {\n if (currPos.right.deleted === false) {\n switch (currPos.right.content.constructor) {\n case ContentType:\n case ContentEmbed:\n case ContentString:\n if (length < currPos.right.length) {\n getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length));\n }\n length -= currPos.right.length;\n currPos.right.delete(transaction);\n break\n }\n }\n currPos.forward();\n }\n if (start) {\n cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes);\n }\n const parent = /** @type {AbstractType} */ (/** @type {Item} */ (currPos.left || currPos.right).parent);\n if (parent._searchMarker) {\n updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length);\n }\n return currPos\n};\n\n/**\n * The Quill Delta format represents changes on a text document with\n * formatting information. For mor information visit {@link https://quilljs.com/docs/delta/|Quill Delta}\n *\n * @example\n * {\n * ops: [\n * { insert: 'Gandalf', attributes: { bold: true } },\n * { insert: ' the ' },\n * { insert: 'Grey', attributes: { color: '#cccccc' } }\n * ]\n * }\n *\n */\n\n/**\n * Attributes that can be assigned to a selection of text.\n *\n * @example\n * {\n * bold: true,\n * font-size: '40px'\n * }\n *\n * @typedef {Object} TextAttributes\n */\n\n/**\n * @extends YEvent\n * Event that describes the changes on a YText type.\n */\nclass YTextEvent extends YEvent {\n /**\n * @param {YText} ytext\n * @param {Transaction} transaction\n * @param {Set} subs The keys that changed\n */\n constructor (ytext, transaction, subs) {\n super(ytext, transaction);\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false;\n /**\n * Set of all changed attributes.\n * @type {Set}\n */\n this.keysChanged = new Set();\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true;\n } else {\n this.keysChanged.add(sub);\n }\n });\n }\n\n /**\n * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string, delete?:number, retain?:number}>}}\n */\n get changes () {\n if (this._changes === null) {\n /**\n * @type {{added:Set,deleted:Set,keys:Map,delta:Array<{insert?:Array|string|AbstractType|object, delete?:number, retain?:number}>}}\n */\n const changes = {\n keys: this.keys,\n delta: this.delta,\n added: new Set(),\n deleted: new Set()\n };\n this._changes = changes;\n }\n return /** @type {any} */ (this._changes)\n }\n\n /**\n * Compute the changes in the delta format.\n * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.\n *\n * @type {Array<{insert?:string|object|AbstractType, delete?:number, retain?:number, attributes?: Object}>}\n *\n * @public\n */\n get delta () {\n if (this._delta === null) {\n const y = /** @type {Doc} */ (this.target.doc);\n /**\n * @type {Array<{insert?:string|object|AbstractType, delete?:number, retain?:number, attributes?: Object}>}\n */\n const delta = [];\n transact(y, transaction => {\n const currentAttributes = new Map(); // saves all current attributes for insert\n const oldAttributes = new Map();\n let item = this.target._start;\n /**\n * @type {string?}\n */\n let action = null;\n /**\n * @type {Object}\n */\n const attributes = {}; // counts added or removed new attributes for retain\n /**\n * @type {string|object}\n */\n let insert = '';\n let retain = 0;\n let deleteLen = 0;\n const addOp = () => {\n if (action !== null) {\n /**\n * @type {any}\n */\n let op = null;\n switch (action) {\n case 'delete':\n if (deleteLen > 0) {\n op = { delete: deleteLen };\n }\n deleteLen = 0;\n break\n case 'insert':\n if (typeof insert === 'object' || insert.length > 0) {\n op = { insert };\n if (currentAttributes.size > 0) {\n op.attributes = {};\n currentAttributes.forEach((value, key) => {\n if (value !== null) {\n op.attributes[key] = value;\n }\n });\n }\n }\n insert = '';\n break\n case 'retain':\n if (retain > 0) {\n op = { retain };\n if (!object.isEmpty(attributes)) {\n op.attributes = object.assign({}, attributes);\n }\n }\n retain = 0;\n break\n }\n if (op) delta.push(op);\n action = null;\n }\n };\n while (item !== null) {\n switch (item.content.constructor) {\n case ContentType:\n case ContentEmbed:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n addOp();\n action = 'insert';\n insert = item.content.getContent()[0];\n addOp();\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp();\n action = 'delete';\n }\n deleteLen += 1;\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp();\n action = 'retain';\n }\n retain += 1;\n }\n break\n case ContentString:\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n if (action !== 'insert') {\n addOp();\n action = 'insert';\n }\n insert += /** @type {ContentString} */ (item.content).str;\n }\n } else if (this.deletes(item)) {\n if (action !== 'delete') {\n addOp();\n action = 'delete';\n }\n deleteLen += item.length;\n } else if (!item.deleted) {\n if (action !== 'retain') {\n addOp();\n action = 'retain';\n }\n retain += item.length;\n }\n break\n case ContentFormat: {\n const { key, value } = /** @type {ContentFormat} */ (item.content);\n if (this.adds(item)) {\n if (!this.deletes(item)) {\n const curVal = currentAttributes.get(key) ?? null;\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp();\n }\n if (equalAttrs(value, (oldAttributes.get(key) ?? null))) {\n delete attributes[key];\n } else {\n attributes[key] = value;\n }\n } else if (value !== null) {\n item.delete(transaction);\n }\n }\n } else if (this.deletes(item)) {\n oldAttributes.set(key, value);\n const curVal = currentAttributes.get(key) ?? null;\n if (!equalAttrs(curVal, value)) {\n if (action === 'retain') {\n addOp();\n }\n attributes[key] = curVal;\n }\n } else if (!item.deleted) {\n oldAttributes.set(key, value);\n const attr = attributes[key];\n if (attr !== undefined) {\n if (!equalAttrs(attr, value)) {\n if (action === 'retain') {\n addOp();\n }\n if (value === null) {\n delete attributes[key];\n } else {\n attributes[key] = value;\n }\n } else if (attr !== null) { // this will be cleaned up automatically by the contextless cleanup function\n item.delete(transaction);\n }\n }\n }\n if (!item.deleted) {\n if (action === 'insert') {\n addOp();\n }\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (item.content));\n }\n break\n }\n }\n item = item.right;\n }\n addOp();\n while (delta.length > 0) {\n const lastOp = delta[delta.length - 1];\n if (lastOp.retain !== undefined && lastOp.attributes === undefined) {\n // retain delta's if they don't assign attributes\n delta.pop();\n } else {\n break\n }\n }\n });\n this._delta = delta;\n }\n return /** @type {any} */ (this._delta)\n }\n}\n\n/**\n * Type that represents text with formatting information.\n *\n * This type replaces y-richtext as this implementation is able to handle\n * block formats (format information on a paragraph), embeds (complex elements\n * like pictures and videos), and text formats (**bold**, *italic*).\n *\n * @extends AbstractType\n */\nclass YText extends AbstractType {\n /**\n * @param {String} [string] The initial value of the YText.\n */\n constructor (string) {\n super();\n /**\n * Array of pending operations on this type\n * @type {Array?}\n */\n this._pending = string !== undefined ? [() => this.insert(0, string)] : [];\n /**\n * @type {Array|null}\n */\n this._searchMarker = [];\n /**\n * Whether this YText contains formatting attributes.\n * This flag is updated when a formatting item is integrated (see ContentFormat.integrate)\n */\n this._hasFormatting = false;\n }\n\n /**\n * Number of characters of this text type.\n *\n * @type {number}\n */\n get length () {\n return this._length\n }\n\n /**\n * @param {Doc} y\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item);\n try {\n /** @type {Array} */ (this._pending).forEach(f => f());\n } catch (e) {\n console.error(e);\n }\n this._pending = null;\n }\n\n _copy () {\n return new YText()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YText}\n */\n clone () {\n const text = new YText();\n text.applyDelta(this.toDelta());\n return text\n }\n\n /**\n * Creates YTextEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n super._callObserver(transaction, parentSubs);\n const event = new YTextEvent(this, transaction, parentSubs);\n callTypeObservers(this, transaction, event);\n // If a remote change happened, we try to cleanup potential formatting duplicates.\n if (!transaction.local && this._hasFormatting) {\n transaction._needFormattingCleanup = true;\n }\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @public\n */\n toString () {\n let str = '';\n /**\n * @type {Item|null}\n */\n let n = this._start;\n while (n !== null) {\n if (!n.deleted && n.countable && n.content.constructor === ContentString) {\n str += /** @type {ContentString} */ (n.content).str;\n }\n n = n.right;\n }\n return str\n }\n\n /**\n * Returns the unformatted string representation of this YText type.\n *\n * @return {string}\n * @public\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Apply a {@link Delta} on this shared YText type.\n *\n * @param {any} delta The changes to apply on this element.\n * @param {object} opts\n * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.\n *\n *\n * @public\n */\n applyDelta (delta, { sanitize = true } = {}) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const currPos = new ItemTextListPosition(null, this._start, 0, new Map());\n for (let i = 0; i < delta.length; i++) {\n const op = delta[i];\n if (op.insert !== undefined) {\n // Quill assumes that the content starts with an empty paragraph.\n // Yjs/Y.Text assumes that it starts empty. We always hide that\n // there is a newline at the end of the content.\n // If we omit this step, clients will see a different number of\n // paragraphs, but nothing bad will happen.\n const ins = (!sanitize && typeof op.insert === 'string' && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === '\\n') ? op.insert.slice(0, -1) : op.insert;\n if (typeof ins !== 'string' || ins.length > 0) {\n insertText(transaction, this, currPos, ins, op.attributes || {});\n }\n } else if (op.retain !== undefined) {\n formatText(transaction, this, currPos, op.retain, op.attributes || {});\n } else if (op.delete !== undefined) {\n deleteText(transaction, currPos, op.delete);\n }\n }\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.applyDelta(delta));\n }\n }\n\n /**\n * Returns the Delta representation of this YText type.\n *\n * @param {Snapshot} [snapshot]\n * @param {Snapshot} [prevSnapshot]\n * @param {function('removed' | 'added', ID):any} [computeYChange]\n * @return {any} The Delta representation of this type.\n *\n * @public\n */\n toDelta (snapshot, prevSnapshot, computeYChange) {\n /**\n * @type{Array}\n */\n const ops = [];\n const currentAttributes = new Map();\n const doc = /** @type {Doc} */ (this.doc);\n let str = '';\n let n = this._start;\n function packStr () {\n if (str.length > 0) {\n // pack str with attributes to ops\n /**\n * @type {Object}\n */\n const attributes = {};\n let addAttributes = false;\n currentAttributes.forEach((value, key) => {\n addAttributes = true;\n attributes[key] = value;\n });\n /**\n * @type {Object}\n */\n const op = { insert: str };\n if (addAttributes) {\n op.attributes = attributes;\n }\n ops.push(op);\n str = '';\n }\n }\n const computeDelta = () => {\n while (n !== null) {\n if (isVisible(n, snapshot) || (prevSnapshot !== undefined && isVisible(n, prevSnapshot))) {\n switch (n.content.constructor) {\n case ContentString: {\n const cur = currentAttributes.get('ychange');\n if (snapshot !== undefined && !isVisible(n, snapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.type !== 'removed') {\n packStr();\n currentAttributes.set('ychange', computeYChange ? computeYChange('removed', n.id) : { type: 'removed' });\n }\n } else if (prevSnapshot !== undefined && !isVisible(n, prevSnapshot)) {\n if (cur === undefined || cur.user !== n.id.client || cur.type !== 'added') {\n packStr();\n currentAttributes.set('ychange', computeYChange ? computeYChange('added', n.id) : { type: 'added' });\n }\n } else if (cur !== undefined) {\n packStr();\n currentAttributes.delete('ychange');\n }\n str += /** @type {ContentString} */ (n.content).str;\n break\n }\n case ContentType:\n case ContentEmbed: {\n packStr();\n /**\n * @type {Object}\n */\n const op = {\n insert: n.content.getContent()[0]\n };\n if (currentAttributes.size > 0) {\n const attrs = /** @type {Object} */ ({});\n op.attributes = attrs;\n currentAttributes.forEach((value, key) => {\n attrs[key] = value;\n });\n }\n ops.push(op);\n break\n }\n case ContentFormat:\n if (isVisible(n, snapshot)) {\n packStr();\n updateCurrentAttributes(currentAttributes, /** @type {ContentFormat} */ (n.content));\n }\n break\n }\n }\n n = n.right;\n }\n packStr();\n };\n if (snapshot || prevSnapshot) {\n // snapshots are merged again after the transaction, so we need to keep the\n // transaction alive until we are done\n transact(doc, transaction => {\n if (snapshot) {\n splitSnapshotAffectedStructs(transaction, snapshot);\n }\n if (prevSnapshot) {\n splitSnapshotAffectedStructs(transaction, prevSnapshot);\n }\n computeDelta();\n }, 'cleanup');\n } else {\n computeDelta();\n }\n return ops\n }\n\n /**\n * Insert text at a given index.\n *\n * @param {number} index The index at which to start inserting.\n * @param {String} text The text to insert at the specified position.\n * @param {TextAttributes} [attributes] Optionally define some formatting\n * information to apply on the inserted\n * Text.\n * @public\n */\n insert (index, text, attributes) {\n if (text.length <= 0) {\n return\n }\n const y = this.doc;\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index, !attributes);\n if (!attributes) {\n attributes = {};\n // @ts-ignore\n pos.currentAttributes.forEach((v, k) => { attributes[k] = v; });\n }\n insertText(transaction, this, pos, text, attributes);\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insert(index, text, attributes));\n }\n }\n\n /**\n * Inserts an embed at a index.\n *\n * @param {number} index The index to insert the embed at.\n * @param {Object | AbstractType} embed The Object that represents the embed.\n * @param {TextAttributes} [attributes] Attribute information to apply on the\n * embed\n *\n * @public\n */\n insertEmbed (index, embed, attributes) {\n const y = this.doc;\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index, !attributes);\n insertText(transaction, this, pos, embed, attributes || {});\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.insertEmbed(index, embed, attributes || {}));\n }\n }\n\n /**\n * Deletes text starting from an index.\n *\n * @param {number} index Index at which to start deleting.\n * @param {number} length The number of characters to remove. Defaults to 1.\n *\n * @public\n */\n delete (index, length) {\n if (length === 0) {\n return\n }\n const y = this.doc;\n if (y !== null) {\n transact(y, transaction => {\n deleteText(transaction, findPosition(transaction, this, index, true), length);\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.delete(index, length));\n }\n }\n\n /**\n * Assigns properties to a range of text.\n *\n * @param {number} index The position where to start formatting.\n * @param {number} length The amount of characters to assign properties to.\n * @param {TextAttributes} attributes Attribute information to apply on the\n * text.\n *\n * @public\n */\n format (index, length, attributes) {\n if (length === 0) {\n return\n }\n const y = this.doc;\n if (y !== null) {\n transact(y, transaction => {\n const pos = findPosition(transaction, this, index, false);\n if (pos.right === null) {\n return\n }\n formatText(transaction, this, pos, length, attributes);\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.format(index, length, attributes));\n }\n }\n\n /**\n * Removes an attribute.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName);\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.removeAttribute(attributeName));\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that is to be set.\n * @param {any} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue);\n });\n } else {\n /** @type {Array} */ (this._pending).push(() => this.setAttribute(attributeName, attributeValue));\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @param {String} attributeName The attribute name that identifies the\n * queried value.\n * @return {any} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.\n *\n * @return {Object} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes () {\n return typeMapGetAll(this)\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YTextRefID);\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n * @return {YText}\n *\n * @private\n * @function\n */\nconst readYText = _decoder => new YText();\n\n/**\n * @module YXml\n */\n\n\n/**\n * Define the elements to which a set of CSS queries apply.\n * {@link https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors|CSS_Selectors}\n *\n * @example\n * query = '.classSelector'\n * query = 'nodeSelector'\n * query = '#idSelector'\n *\n * @typedef {string} CSS_Selector\n */\n\n/**\n * Dom filter function.\n *\n * @callback domFilter\n * @param {string} nodeName The nodeName of the element\n * @param {Map} attributes The map of attributes.\n * @return {boolean} Whether to include the Dom node in the YXmlElement.\n */\n\n/**\n * Represents a subset of the nodes of a YXmlElement / YXmlFragment and a\n * position within them.\n *\n * Can be created with {@link YXmlFragment#createTreeWalker}\n *\n * @public\n * @implements {Iterable}\n */\nclass YXmlTreeWalker {\n /**\n * @param {YXmlFragment | YXmlElement} root\n * @param {function(AbstractType):boolean} [f]\n */\n constructor (root, f = () => true) {\n this._filter = f;\n this._root = root;\n /**\n * @type {Item}\n */\n this._currentNode = /** @type {Item} */ (root._start);\n this._firstCall = true;\n }\n\n [Symbol.iterator] () {\n return this\n }\n\n /**\n * Get the next node.\n *\n * @return {IteratorResult} The next node.\n *\n * @public\n */\n next () {\n /**\n * @type {Item|null}\n */\n let n = this._currentNode;\n let type = n && n.content && /** @type {any} */ (n.content).type;\n if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { // if first call, we check if we can use the first item\n do {\n type = /** @type {any} */ (n.content).type;\n if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {\n // walk down in the tree\n n = type._start;\n } else {\n // walk right or up in the tree\n while (n !== null) {\n if (n.right !== null) {\n n = n.right;\n break\n } else if (n.parent === this._root) {\n n = null;\n } else {\n n = /** @type {AbstractType} */ (n.parent)._item;\n }\n }\n }\n } while (n !== null && (n.deleted || !this._filter(/** @type {ContentType} */ (n.content).type)))\n }\n this._firstCall = false;\n if (n === null) {\n // @ts-ignore\n return { value: undefined, done: true }\n }\n this._currentNode = n;\n return { value: /** @type {any} */ (n.content).type, done: false }\n }\n}\n\n/**\n * Represents a list of {@link YXmlElement}.and {@link YXmlText} types.\n * A YxmlFragment is similar to a {@link YXmlElement}, but it does not have a\n * nodeName and it does not have attributes. Though it can be bound to a DOM\n * element - in this case the attributes and the nodeName are not shared.\n *\n * @public\n * @extends AbstractType\n */\nclass YXmlFragment extends AbstractType {\n constructor () {\n super();\n /**\n * @type {Array|null}\n */\n this._prelimContent = [];\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get firstChild () {\n const first = this._first;\n return first ? first.content.getContent()[0] : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item);\n this.insert(0, /** @type {Array} */ (this._prelimContent));\n this._prelimContent = null;\n }\n\n _copy () {\n return new YXmlFragment()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlFragment}\n */\n clone () {\n const el = new YXmlFragment();\n // @ts-ignore\n el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item));\n return el\n }\n\n get length () {\n return this._prelimContent === null ? this._length : this._prelimContent.length\n }\n\n /**\n * Create a subtree of childNodes.\n *\n * @example\n * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')\n * for (let node in walker) {\n * // `node` is a div node\n * nop(node)\n * }\n *\n * @param {function(AbstractType):boolean} filter Function that is called on each child element and\n * returns a Boolean indicating whether the child\n * is to be included in the subtree.\n * @return {YXmlTreeWalker} A subtree and a position within it.\n *\n * @public\n */\n createTreeWalker (filter) {\n return new YXmlTreeWalker(this, filter)\n }\n\n /**\n * Returns the first YXmlElement that matches the query.\n * Similar to DOM's {@link querySelector}.\n *\n * Query support:\n * - tagname\n * TODO:\n * - id\n * - attribute\n *\n * @param {CSS_Selector} query The query on the children.\n * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.\n *\n * @public\n */\n querySelector (query) {\n query = query.toUpperCase();\n // @ts-ignore\n const iterator = new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query);\n const next = iterator.next();\n if (next.done) {\n return null\n } else {\n return next.value\n }\n }\n\n /**\n * Returns all YXmlElements that match the query.\n * Similar to Dom's {@link querySelectorAll}.\n *\n * @todo Does not yet support all queries. Currently only query by tagName.\n *\n * @param {CSS_Selector} query The query on the children\n * @return {Array} The elements that match this query.\n *\n * @public\n */\n querySelectorAll (query) {\n query = query.toUpperCase();\n // @ts-ignore\n return array.from(new YXmlTreeWalker(this, element => element.nodeName && element.nodeName.toUpperCase() === query))\n }\n\n /**\n * Creates YXmlEvent and calls observers.\n *\n * @param {Transaction} transaction\n * @param {Set} parentSubs Keys changed on this type. `null` if list was modified.\n */\n _callObserver (transaction, parentSubs) {\n callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction));\n }\n\n /**\n * Get the string representation of all the children of this YXmlFragment.\n *\n * @return {string} The string representation of all children.\n */\n toString () {\n return typeListMap(this, xml => xml.toString()).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const fragment = _document.createDocumentFragment();\n if (binding !== undefined) {\n binding._createAssociation(fragment, this);\n }\n typeListForEach(this, xmlType => {\n fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null);\n });\n return fragment\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {number} index The index to insert content at\n * @param {Array} content The array of content\n */\n insert (index, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListInsertGenerics(transaction, this, index, content);\n });\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, 0, ...content);\n }\n }\n\n /**\n * Inserts new content at an index.\n *\n * @example\n * // Insert character 'a' at position 0\n * xml.insert(0, [new Y.XmlText('text')])\n *\n * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at\n * @param {Array} content The array of content\n */\n insertAfter (ref, content) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n const refItem = (ref && ref instanceof AbstractType) ? ref._item : ref;\n typeListInsertGenericsAfter(transaction, this, refItem, content);\n });\n } else {\n const pc = /** @type {Array} */ (this._prelimContent);\n const index = ref === null ? 0 : pc.findIndex(el => el === ref) + 1;\n if (index === 0 && ref !== null) {\n throw error.create('Reference item not found')\n }\n pc.splice(index, 0, ...content);\n }\n }\n\n /**\n * Deletes elements starting from an index.\n *\n * @param {number} index Index at which to start deleting elements\n * @param {number} [length=1] The number of elements to remove. Defaults to 1.\n */\n delete (index, length = 1) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeListDelete(transaction, this, index, length);\n });\n } else {\n // @ts-ignore _prelimContent is defined because this is not yet integrated\n this._prelimContent.splice(index, length);\n }\n }\n\n /**\n * Transforms this YArray to a JavaScript Array.\n *\n * @return {Array}\n */\n toArray () {\n return typeListToArray(this)\n }\n\n /**\n * Appends content to this YArray.\n *\n * @param {Array} content Array of content to append.\n */\n push (content) {\n this.insert(this.length, content);\n }\n\n /**\n * Prepends content to this YArray.\n *\n * @param {Array} content Array of content to prepend.\n */\n unshift (content) {\n this.insert(0, content);\n }\n\n /**\n * Returns the i-th element from a YArray.\n *\n * @param {number} index The index of the element to return from the YArray\n * @return {YXmlElement|YXmlText}\n */\n get (index) {\n return typeListGet(this, index)\n }\n\n /**\n * Returns a portion of this YXmlFragment into a JavaScript Array selected\n * from start to end (end not included).\n *\n * @param {number} [start]\n * @param {number} [end]\n * @return {Array}\n */\n slice (start = 0, end = this.length) {\n return typeListSlice(this, start, end)\n }\n\n /**\n * Executes a provided function on once on every child element.\n *\n * @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray.\n */\n forEach (f) {\n typeListForEach(this, f);\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlFragmentRefID);\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} _decoder\n * @return {YXmlFragment}\n *\n * @private\n * @function\n */\nconst readYXmlFragment = _decoder => new YXmlFragment();\n\n/**\n * @typedef {Object|number|null|Array|string|Uint8Array|AbstractType} ValueTypes\n */\n\n/**\n * An YXmlElement imitates the behavior of a\n * https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element\n *\n * * An YXmlElement has attributes (key value pairs)\n * * An YXmlElement has childElements that must inherit from YXmlElement\n *\n * @template {{ [key: string]: ValueTypes }} [KV={ [key: string]: string }]\n */\nclass YXmlElement extends YXmlFragment {\n constructor (nodeName = 'UNDEFINED') {\n super();\n this.nodeName = nodeName;\n /**\n * @type {Map|null}\n */\n this._prelimAttrs = new Map();\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get nextSibling () {\n const n = this._item ? this._item.next : null;\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get prevSibling () {\n const n = this._item ? this._item.prev : null;\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * Integrate this type into the Yjs instance.\n *\n * * Save this struct in the os\n * * This type is sent to other client\n * * Observer functions are fired\n *\n * @param {Doc} y The Yjs instance\n * @param {Item} item\n */\n _integrate (y, item) {\n super._integrate(y, item)\n ;(/** @type {Map} */ (this._prelimAttrs)).forEach((value, key) => {\n this.setAttribute(key, value);\n });\n this._prelimAttrs = null;\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n *\n * @return {YXmlElement}\n */\n _copy () {\n return new YXmlElement(this.nodeName)\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlElement}\n */\n clone () {\n /**\n * @type {YXmlElement}\n */\n const el = new YXmlElement(this.nodeName);\n const attrs = this.getAttributes();\n object.forEach(attrs, (value, key) => {\n if (typeof value === 'string') {\n el.setAttribute(key, value);\n }\n });\n // @ts-ignore\n el.insert(0, this.toArray().map(item => item instanceof AbstractType ? item.clone() : item));\n return el\n }\n\n /**\n * Returns the XML serialization of this YXmlElement.\n * The attributes are ordered by attribute-name, so you can easily use this\n * method to compare YXmlElements\n *\n * @return {string} The string representation of this type.\n *\n * @public\n */\n toString () {\n const attrs = this.getAttributes();\n const stringBuilder = [];\n const keys = [];\n for (const key in attrs) {\n keys.push(key);\n }\n keys.sort();\n const keysLen = keys.length;\n for (let i = 0; i < keysLen; i++) {\n const key = keys[i];\n stringBuilder.push(key + '=\"' + attrs[key] + '\"');\n }\n const nodeName = this.nodeName.toLocaleLowerCase();\n const attrsString = stringBuilder.length > 0 ? ' ' + stringBuilder.join(' ') : '';\n return `<${nodeName}${attrsString}>${super.toString()}`\n }\n\n /**\n * Removes an attribute from this YXmlElement.\n *\n * @param {string} attributeName The attribute name that is to be removed.\n *\n * @public\n */\n removeAttribute (attributeName) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapDelete(transaction, this, attributeName);\n });\n } else {\n /** @type {Map} */ (this._prelimAttrs).delete(attributeName);\n }\n }\n\n /**\n * Sets or updates an attribute.\n *\n * @template {keyof KV & string} KEY\n *\n * @param {KEY} attributeName The attribute name that is to be set.\n * @param {KV[KEY]} attributeValue The attribute value that is to be set.\n *\n * @public\n */\n setAttribute (attributeName, attributeValue) {\n if (this.doc !== null) {\n transact(this.doc, transaction => {\n typeMapSet(transaction, this, attributeName, attributeValue);\n });\n } else {\n /** @type {Map} */ (this._prelimAttrs).set(attributeName, attributeValue);\n }\n }\n\n /**\n * Returns an attribute value that belongs to the attribute name.\n *\n * @template {keyof KV & string} KEY\n *\n * @param {KEY} attributeName The attribute name that identifies the\n * queried value.\n * @return {KV[KEY]|undefined} The queried attribute value.\n *\n * @public\n */\n getAttribute (attributeName) {\n return /** @type {any} */ (typeMapGet(this, attributeName))\n }\n\n /**\n * Returns whether an attribute exists\n *\n * @param {string} attributeName The attribute name to check for existence.\n * @return {boolean} whether the attribute exists.\n *\n * @public\n */\n hasAttribute (attributeName) {\n return /** @type {any} */ (typeMapHas(this, attributeName))\n }\n\n /**\n * Returns all attribute name/value pairs in a JSON Object.\n *\n * @param {Snapshot} [snapshot]\n * @return {{ [Key in Extract]?: KV[Key]}} A JSON Object that describes the attributes.\n *\n * @public\n */\n getAttributes (snapshot) {\n return /** @type {any} */ (snapshot ? typeMapGetAllSnapshot(this, snapshot) : typeMapGetAll(this))\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks={}] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const dom = _document.createElement(this.nodeName);\n const attrs = this.getAttributes();\n for (const key in attrs) {\n const value = attrs[key];\n if (typeof value === 'string') {\n dom.setAttribute(key, value);\n }\n }\n typeListForEach(this, yxml => {\n dom.appendChild(yxml.toDOM(_document, hooks, binding));\n });\n if (binding !== undefined) {\n binding._createAssociation(dom, this);\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlElementRefID);\n encoder.writeKey(this.nodeName);\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlElement}\n *\n * @function\n */\nconst readYXmlElement = decoder => new YXmlElement(decoder.readKey());\n\n/**\n * @extends YEvent\n * An Event that describes changes on a YXml Element or Yxml Fragment\n */\nclass YXmlEvent extends YEvent {\n /**\n * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created.\n * @param {Set} subs The set of changed attributes. `null` is included if the\n * child list changed.\n * @param {Transaction} transaction The transaction instance with wich the\n * change was created.\n */\n constructor (target, subs, transaction) {\n super(target, transaction);\n /**\n * Whether the children changed.\n * @type {Boolean}\n * @private\n */\n this.childListChanged = false;\n /**\n * Set of all changed attributes.\n * @type {Set}\n */\n this.attributesChanged = new Set();\n subs.forEach((sub) => {\n if (sub === null) {\n this.childListChanged = true;\n } else {\n this.attributesChanged.add(sub);\n }\n });\n }\n}\n\n/**\n * You can manage binding to a custom type with YXmlHook.\n *\n * @extends {YMap}\n */\nclass YXmlHook extends YMap {\n /**\n * @param {string} hookName nodeName of the Dom Node.\n */\n constructor (hookName) {\n super();\n /**\n * @type {string}\n */\n this.hookName = hookName;\n }\n\n /**\n * Creates an Item with the same effect as this Item (without position effect)\n */\n _copy () {\n return new YXmlHook(this.hookName)\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlHook}\n */\n clone () {\n const el = new YXmlHook(this.hookName);\n this.forEach((value, key) => {\n el.set(key, value);\n });\n return el\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlElement.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object.} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type\n * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks = {}, binding) {\n const hook = hooks[this.hookName];\n let dom;\n if (hook !== undefined) {\n dom = hook.createDom(this);\n } else {\n dom = document.createElement(this.hookName);\n }\n dom.setAttribute('data-yjs-hook', this.hookName);\n if (binding !== undefined) {\n binding._createAssociation(dom, this);\n }\n return dom\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlHookRefID);\n encoder.writeKey(this.hookName);\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlHook}\n *\n * @private\n * @function\n */\nconst readYXmlHook = decoder =>\n new YXmlHook(decoder.readKey());\n\n/**\n * Represents text in a Dom Element. In the future this type will also handle\n * simple formatting information like bold and italic.\n */\nclass YXmlText extends YText {\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get nextSibling () {\n const n = this._item ? this._item.next : null;\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n /**\n * @type {YXmlElement|YXmlText|null}\n */\n get prevSibling () {\n const n = this._item ? this._item.prev : null;\n return n ? /** @type {YXmlElement|YXmlText} */ (/** @type {ContentType} */ (n.content).type) : null\n }\n\n _copy () {\n return new YXmlText()\n }\n\n /**\n * Makes a copy of this data type that can be included somewhere else.\n *\n * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.\n *\n * @return {YXmlText}\n */\n clone () {\n const text = new YXmlText();\n text.applyDelta(this.toDelta());\n return text\n }\n\n /**\n * Creates a Dom Element that mirrors this YXmlText.\n *\n * @param {Document} [_document=document] The document object (you must define\n * this when calling this method in\n * nodejs)\n * @param {Object} [hooks] Optional property to customize how hooks\n * are presented in the DOM\n * @param {any} [binding] You should not set this property. This is\n * used if DomBinding wants to create a\n * association to the created DOM type.\n * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}\n *\n * @public\n */\n toDOM (_document = document, hooks, binding) {\n const dom = _document.createTextNode(this.toString());\n if (binding !== undefined) {\n binding._createAssociation(dom, this);\n }\n return dom\n }\n\n toString () {\n // @ts-ignore\n return this.toDelta().map(delta => {\n const nestedNodes = [];\n for (const nodeName in delta.attributes) {\n const attrs = [];\n for (const key in delta.attributes[nodeName]) {\n attrs.push({ key, value: delta.attributes[nodeName][key] });\n }\n // sort attributes to get a unique order\n attrs.sort((a, b) => a.key < b.key ? -1 : 1);\n nestedNodes.push({ nodeName, attrs });\n }\n // sort node order to get a unique order\n nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1);\n // now convert to dom string\n let str = '';\n for (let i = 0; i < nestedNodes.length; i++) {\n const node = nestedNodes[i];\n str += `<${node.nodeName}`;\n for (let j = 0; j < node.attrs.length; j++) {\n const attr = node.attrs[j];\n str += ` ${attr.key}=\"${attr.value}\"`;\n }\n str += '>';\n }\n str += delta.insert;\n for (let i = nestedNodes.length - 1; i >= 0; i--) {\n str += ``;\n }\n return str\n }).join('')\n }\n\n /**\n * @return {string}\n */\n toJSON () {\n return this.toString()\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n */\n _write (encoder) {\n encoder.writeTypeRef(YXmlTextRefID);\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {YXmlText}\n *\n * @private\n * @function\n */\nconst readYXmlText = decoder => new YXmlText();\n\nclass AbstractStruct {\n /**\n * @param {ID} id\n * @param {number} length\n */\n constructor (id, length) {\n this.id = id;\n this.length = length;\n }\n\n /**\n * @type {boolean}\n */\n get deleted () {\n throw error.methodUnimplemented()\n }\n\n /**\n * Merge this struct with the item to the right.\n * This method is already assuming that `this.id.clock + this.length === this.id.clock`.\n * Also this method does *not* remove right from StructStore!\n * @param {AbstractStruct} right\n * @return {boolean} wether this merged with right\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n * @param {number} offset\n * @param {number} encodingRef\n */\n write (encoder, offset, encodingRef) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n throw error.methodUnimplemented()\n }\n}\n\nconst structGCRefNumber = 0;\n\n/**\n * @private\n */\nclass GC extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {GC} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (this.constructor !== right.constructor) {\n return false\n }\n this.length += right.length;\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset;\n this.length -= offset;\n }\n addStruct(transaction.doc.store, this);\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structGCRefNumber);\n encoder.writeLen(this.length - offset);\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n\nclass ContentBinary {\n /**\n * @param {Uint8Array} content\n */\n constructor (content) {\n this.content = content;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.content]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentBinary}\n */\n copy () {\n return new ContentBinary(this.content)\n }\n\n /**\n * @param {number} offset\n * @return {ContentBinary}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentBinary} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeBuf(this.content);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 3\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2 } decoder\n * @return {ContentBinary}\n */\nconst readContentBinary = decoder => new ContentBinary(decoder.readBuf());\n\nclass ContentDeleted {\n /**\n * @param {number} len\n */\n constructor (len) {\n this.len = len;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.len\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentDeleted}\n */\n copy () {\n return new ContentDeleted(this.len)\n }\n\n /**\n * @param {number} offset\n * @return {ContentDeleted}\n */\n splice (offset) {\n const right = new ContentDeleted(this.len - offset);\n this.len = offset;\n return right\n }\n\n /**\n * @param {ContentDeleted} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.len += right.len;\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len);\n item.markDeleted();\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeLen(this.len - offset);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 1\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2 } decoder\n * @return {ContentDeleted}\n */\nconst readContentDeleted = decoder => new ContentDeleted(decoder.readLen());\n\n/**\n * @param {string} guid\n * @param {Object} opts\n */\nconst createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false });\n\n/**\n * @private\n */\nclass ContentDoc {\n /**\n * @param {Doc} doc\n */\n constructor (doc) {\n if (doc._item) {\n console.error('This document was already integrated as a sub-document. You should create a second instance instead with the same guid.');\n }\n /**\n * @type {Doc}\n */\n this.doc = doc;\n /**\n * @type {any}\n */\n const opts = {};\n this.opts = opts;\n if (!doc.gc) {\n opts.gc = false;\n }\n if (doc.autoLoad) {\n opts.autoLoad = true;\n }\n if (doc.meta !== null) {\n opts.meta = doc.meta;\n }\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.doc]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentDoc}\n */\n copy () {\n return new ContentDoc(createDocFromOpts(this.doc.guid, this.opts))\n }\n\n /**\n * @param {number} offset\n * @return {ContentDoc}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentDoc} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n // this needs to be reflected in doc.destroy as well\n this.doc._item = item;\n transaction.subdocsAdded.add(this.doc);\n if (this.doc.shouldLoad) {\n transaction.subdocsLoaded.add(this.doc);\n }\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (transaction.subdocsAdded.has(this.doc)) {\n transaction.subdocsAdded.delete(this.doc);\n } else {\n transaction.subdocsRemoved.add(this.doc);\n }\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) { }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(this.doc.guid);\n encoder.writeAny(this.opts);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 9\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentDoc}\n */\nconst readContentDoc = decoder => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny()));\n\n/**\n * @private\n */\nclass ContentEmbed {\n /**\n * @param {Object} embed\n */\n constructor (embed) {\n this.embed = embed;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.embed]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentEmbed}\n */\n copy () {\n return new ContentEmbed(this.embed)\n }\n\n /**\n * @param {number} offset\n * @return {ContentEmbed}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentEmbed} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeJSON(this.embed);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 5\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentEmbed}\n */\nconst readContentEmbed = decoder => new ContentEmbed(decoder.readJSON());\n\n/**\n * @private\n */\nclass ContentFormat {\n /**\n * @param {string} key\n * @param {Object} value\n */\n constructor (key, value) {\n this.key = key;\n this.value = value;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return []\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return false\n }\n\n /**\n * @return {ContentFormat}\n */\n copy () {\n return new ContentFormat(this.key, this.value)\n }\n\n /**\n * @param {number} _offset\n * @return {ContentFormat}\n */\n splice (_offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentFormat} _right\n * @return {boolean}\n */\n mergeWith (_right) {\n return false\n }\n\n /**\n * @param {Transaction} _transaction\n * @param {Item} item\n */\n integrate (_transaction, item) {\n // @todo searchmarker are currently unsupported for rich text documents\n const p = /** @type {YText} */ (item.parent);\n p._searchMarker = null;\n p._hasFormatting = true;\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeKey(this.key);\n encoder.writeJSON(this.value);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 6\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentFormat}\n */\nconst readContentFormat = decoder => new ContentFormat(decoder.readKey(), decoder.readJSON());\n\n/**\n * @private\n */\nclass ContentJSON {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentJSON}\n */\n copy () {\n return new ContentJSON(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentJSON}\n */\n splice (offset) {\n const right = new ContentJSON(this.arr.slice(offset));\n this.arr = this.arr.slice(0, offset);\n return right\n }\n\n /**\n * @param {ContentJSON} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr);\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length;\n encoder.writeLen(len - offset);\n for (let i = offset; i < len; i++) {\n const c = this.arr[i];\n encoder.writeString(c === undefined ? 'undefined' : JSON.stringify(c));\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 2\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentJSON}\n */\nconst readContentJSON = decoder => {\n const len = decoder.readLen();\n const cs = [];\n for (let i = 0; i < len; i++) {\n const c = decoder.readString();\n if (c === 'undefined') {\n cs.push(undefined);\n } else {\n cs.push(JSON.parse(c));\n }\n }\n return new ContentJSON(cs)\n};\n\nclass ContentAny {\n /**\n * @param {Array} arr\n */\n constructor (arr) {\n /**\n * @type {Array}\n */\n this.arr = arr;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.arr.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.arr\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentAny}\n */\n copy () {\n return new ContentAny(this.arr)\n }\n\n /**\n * @param {number} offset\n * @return {ContentAny}\n */\n splice (offset) {\n const right = new ContentAny(this.arr.slice(offset));\n this.arr = this.arr.slice(0, offset);\n return right\n }\n\n /**\n * @param {ContentAny} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.arr = this.arr.concat(right.arr);\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n const len = this.arr.length;\n encoder.writeLen(len - offset);\n for (let i = offset; i < len; i++) {\n const c = this.arr[i];\n encoder.writeAny(c);\n }\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 8\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentAny}\n */\nconst readContentAny = decoder => {\n const len = decoder.readLen();\n const cs = [];\n for (let i = 0; i < len; i++) {\n cs.push(decoder.readAny());\n }\n return new ContentAny(cs)\n};\n\n/**\n * @private\n */\nclass ContentString {\n /**\n * @param {string} str\n */\n constructor (str) {\n /**\n * @type {string}\n */\n this.str = str;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return this.str.length\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return this.str.split('')\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentString}\n */\n copy () {\n return new ContentString(this.str)\n }\n\n /**\n * @param {number} offset\n * @return {ContentString}\n */\n splice (offset) {\n const right = new ContentString(this.str.slice(offset));\n this.str = this.str.slice(0, offset);\n\n // Prevent encoding invalid documents because of splitting of surrogate pairs: https://github.com/yjs/yjs/issues/248\n const firstCharCode = this.str.charCodeAt(offset - 1);\n if (firstCharCode >= 0xD800 && firstCharCode <= 0xDBFF) {\n // Last character of the left split is the start of a surrogate utf16/ucs2 pair.\n // We don't support splitting of surrogate pairs because this may lead to invalid documents.\n // Replace the invalid character with a unicode replacement character (� / U+FFFD)\n this.str = this.str.slice(0, offset - 1) + '�';\n // replace right as well\n right.str = '�' + right.str.slice(1);\n }\n return right\n }\n\n /**\n * @param {ContentString} right\n * @return {boolean}\n */\n mergeWith (right) {\n this.str += right.str;\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {}\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {}\n /**\n * @param {StructStore} store\n */\n gc (store) {}\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeString(offset === 0 ? this.str : this.str.slice(offset));\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 4\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentString}\n */\nconst readContentString = decoder => new ContentString(decoder.readString());\n\n/**\n * @type {Array>}\n * @private\n */\nconst typeRefs = [\n readYArray,\n readYMap,\n readYText,\n readYXmlElement,\n readYXmlFragment,\n readYXmlHook,\n readYXmlText\n];\n\nconst YArrayRefID = 0;\nconst YMapRefID = 1;\nconst YTextRefID = 2;\nconst YXmlElementRefID = 3;\nconst YXmlFragmentRefID = 4;\nconst YXmlHookRefID = 5;\nconst YXmlTextRefID = 6;\n\n/**\n * @private\n */\nclass ContentType {\n /**\n * @param {AbstractType} type\n */\n constructor (type) {\n /**\n * @type {AbstractType}\n */\n this.type = type;\n }\n\n /**\n * @return {number}\n */\n getLength () {\n return 1\n }\n\n /**\n * @return {Array}\n */\n getContent () {\n return [this.type]\n }\n\n /**\n * @return {boolean}\n */\n isCountable () {\n return true\n }\n\n /**\n * @return {ContentType}\n */\n copy () {\n return new ContentType(this.type._copy())\n }\n\n /**\n * @param {number} offset\n * @return {ContentType}\n */\n splice (offset) {\n throw error.methodUnimplemented()\n }\n\n /**\n * @param {ContentType} right\n * @return {boolean}\n */\n mergeWith (right) {\n return false\n }\n\n /**\n * @param {Transaction} transaction\n * @param {Item} item\n */\n integrate (transaction, item) {\n this.type._integrate(transaction.doc, item);\n }\n\n /**\n * @param {Transaction} transaction\n */\n delete (transaction) {\n let item = this.type._start;\n while (item !== null) {\n if (!item.deleted) {\n item.delete(transaction);\n } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {\n // This will be gc'd later and we want to merge it if possible\n // We try to merge all deleted items after each transaction,\n // but we have no knowledge about that this needs to be merged\n // since it is not in transaction.ds. Hence we add it to transaction._mergeStructs\n transaction._mergeStructs.push(item);\n }\n item = item.right;\n }\n this.type._map.forEach(item => {\n if (!item.deleted) {\n item.delete(transaction);\n } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {\n // same as above\n transaction._mergeStructs.push(item);\n }\n });\n transaction.changed.delete(this.type);\n }\n\n /**\n * @param {StructStore} store\n */\n gc (store) {\n let item = this.type._start;\n while (item !== null) {\n item.gc(store, true);\n item = item.right;\n }\n this.type._start = null;\n this.type._map.forEach(/** @param {Item | null} item */ (item) => {\n while (item !== null) {\n item.gc(store, true);\n item = item.left;\n }\n });\n this.type._map = new Map();\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n this.type._write(encoder);\n }\n\n /**\n * @return {number}\n */\n getRef () {\n return 7\n }\n}\n\n/**\n * @private\n *\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @return {ContentType}\n */\nconst readContentType = decoder => new ContentType(typeRefs[decoder.readTypeRef()](decoder));\n\n/**\n * @todo This should return several items\n *\n * @param {StructStore} store\n * @param {ID} id\n * @return {{item:Item, diff:number}}\n */\nconst followRedone = (store, id) => {\n /**\n * @type {ID|null}\n */\n let nextID = id;\n let diff = 0;\n let item;\n do {\n if (diff > 0) {\n nextID = createID(nextID.client, nextID.clock + diff);\n }\n item = getItem(store, nextID);\n diff = nextID.clock - item.id.clock;\n nextID = item.redone;\n } while (nextID !== null && item instanceof Item)\n return {\n item, diff\n }\n};\n\n/**\n * Make sure that neither item nor any of its parents is ever deleted.\n *\n * This property does not persist when storing it into a database or when\n * sending it to other peers\n *\n * @param {Item|null} item\n * @param {boolean} keep\n */\nconst keepItem = (item, keep) => {\n while (item !== null && item.keep !== keep) {\n item.keep = keep;\n item = /** @type {AbstractType} */ (item.parent)._item;\n }\n};\n\n/**\n * Split leftItem into two items\n * @param {Transaction} transaction\n * @param {Item} leftItem\n * @param {number} diff\n * @return {Item}\n *\n * @function\n * @private\n */\nconst splitItem = (transaction, leftItem, diff) => {\n // create rightItem\n const { client, clock } = leftItem.id;\n const rightItem = new Item(\n createID(client, clock + diff),\n leftItem,\n createID(client, clock + diff - 1),\n leftItem.right,\n leftItem.rightOrigin,\n leftItem.parent,\n leftItem.parentSub,\n leftItem.content.splice(diff)\n );\n if (leftItem.deleted) {\n rightItem.markDeleted();\n }\n if (leftItem.keep) {\n rightItem.keep = true;\n }\n if (leftItem.redone !== null) {\n rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff);\n }\n // update left (do not set leftItem.rightOrigin as it will lead to problems when syncing)\n leftItem.right = rightItem;\n // update right\n if (rightItem.right !== null) {\n rightItem.right.left = rightItem;\n }\n // right is more specific.\n transaction._mergeStructs.push(rightItem);\n // update parent._map\n if (rightItem.parentSub !== null && rightItem.right === null) {\n /** @type {AbstractType} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem);\n }\n leftItem.length = diff;\n return rightItem\n};\n\n/**\n * @param {Array} stack\n * @param {ID} id\n */\nconst isDeletedByUndoStack = (stack, id) => array.some(stack, /** @param {StackItem} s */ s => isDeleted(s.deletions, id));\n\n/**\n * Redoes the effect of this operation.\n *\n * @param {Transaction} transaction The Yjs instance.\n * @param {Item} item\n * @param {Set} redoitems\n * @param {DeleteSet} itemsToDelete\n * @param {boolean} ignoreRemoteMapChanges\n * @param {import('../utils/UndoManager.js').UndoManager} um\n *\n * @return {Item|null}\n *\n * @private\n */\nconst redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) => {\n const doc = transaction.doc;\n const store = doc.store;\n const ownClientID = doc.clientID;\n const redone = item.redone;\n if (redone !== null) {\n return getItemCleanStart(transaction, redone)\n }\n let parentItem = /** @type {AbstractType} */ (item.parent)._item;\n /**\n * @type {Item|null}\n */\n let left = null;\n /**\n * @type {Item|null}\n */\n let right;\n // make sure that parent is redone\n if (parentItem !== null && parentItem.deleted === true) {\n // try to undo parent if it will be undone anyway\n if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) === null)) {\n return null\n }\n while (parentItem.redone !== null) {\n parentItem = getItemCleanStart(transaction, parentItem.redone);\n }\n }\n const parentType = parentItem === null ? /** @type {AbstractType} */ (item.parent) : /** @type {ContentType} */ (parentItem.content).type;\n\n if (item.parentSub === null) {\n // Is an array item. Insert at the old position\n left = item.left;\n right = item;\n // find next cloned_redo items\n while (left !== null) {\n /**\n * @type {Item|null}\n */\n let leftTrace = left;\n // trace redone until parent matches\n while (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item !== parentItem) {\n leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone);\n }\n if (leftTrace !== null && /** @type {AbstractType} */ (leftTrace.parent)._item === parentItem) {\n left = leftTrace;\n break\n }\n left = left.left;\n }\n while (right !== null) {\n /**\n * @type {Item|null}\n */\n let rightTrace = right;\n // trace redone until parent matches\n while (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item !== parentItem) {\n rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone);\n }\n if (rightTrace !== null && /** @type {AbstractType} */ (rightTrace.parent)._item === parentItem) {\n right = rightTrace;\n break\n }\n right = right.right;\n }\n } else {\n right = null;\n if (item.right && !ignoreRemoteMapChanges) {\n left = item;\n // Iterate right while right is in itemsToDelete\n // If it is intended to delete right while item is redone, we can expect that item should replace right.\n while (left !== null && left.right !== null && (left.right.redone || isDeleted(itemsToDelete, left.right.id) || isDeletedByUndoStack(um.undoStack, left.right.id) || isDeletedByUndoStack(um.redoStack, left.right.id))) {\n left = left.right;\n // follow redone\n while (left.redone) left = getItemCleanStart(transaction, left.redone);\n }\n if (left && left.right !== null) {\n // It is not possible to redo this item because it conflicts with a\n // change from another client\n return null\n }\n } else {\n left = parentType._map.get(item.parentSub) || null;\n }\n }\n const nextClock = getState(store, ownClientID);\n const nextId = createID(ownClientID, nextClock);\n const redoneItem = new Item(\n nextId,\n left, left && left.lastId,\n right, right && right.id,\n parentType,\n item.parentSub,\n item.content.copy()\n );\n item.redone = nextId;\n keepItem(redoneItem, true);\n redoneItem.integrate(transaction, 0);\n return redoneItem\n};\n\n/**\n * Abstract class that represents any content.\n */\nclass Item extends AbstractStruct {\n /**\n * @param {ID} id\n * @param {Item | null} left\n * @param {ID | null} origin\n * @param {Item | null} right\n * @param {ID | null} rightOrigin\n * @param {AbstractType|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it.\n * @param {string | null} parentSub\n * @param {AbstractContent} content\n */\n constructor (id, left, origin, right, rightOrigin, parent, parentSub, content) {\n super(id, content.getLength());\n /**\n * The item that was originally to the left of this item.\n * @type {ID | null}\n */\n this.origin = origin;\n /**\n * The item that is currently to the left of this item.\n * @type {Item | null}\n */\n this.left = left;\n /**\n * The item that is currently to the right of this item.\n * @type {Item | null}\n */\n this.right = right;\n /**\n * The item that was originally to the right of this item.\n * @type {ID | null}\n */\n this.rightOrigin = rightOrigin;\n /**\n * @type {AbstractType|ID|null}\n */\n this.parent = parent;\n /**\n * If the parent refers to this item with some kind of key (e.g. YMap, the\n * key is specified here. The key is then used to refer to the list in which\n * to insert this item. If `parentSub = null` type._start is the list in\n * which to insert to. Otherwise it is `parent._map`.\n * @type {String | null}\n */\n this.parentSub = parentSub;\n /**\n * If this type's effect is redone this type refers to the type that undid\n * this operation.\n * @type {ID | null}\n */\n this.redone = null;\n /**\n * @type {AbstractContent}\n */\n this.content = content;\n /**\n * bit1: keep\n * bit2: countable\n * bit3: deleted\n * bit4: mark - mark node as fast-search-marker\n * @type {number} byte\n */\n this.info = this.content.isCountable() ? binary.BIT2 : 0;\n }\n\n /**\n * This is used to mark the item as an indexed fast-search marker\n *\n * @type {boolean}\n */\n set marker (isMarked) {\n if (((this.info & binary.BIT4) > 0) !== isMarked) {\n this.info ^= binary.BIT4;\n }\n }\n\n get marker () {\n return (this.info & binary.BIT4) > 0\n }\n\n /**\n * If true, do not garbage collect this Item.\n */\n get keep () {\n return (this.info & binary.BIT1) > 0\n }\n\n set keep (doKeep) {\n if (this.keep !== doKeep) {\n this.info ^= binary.BIT1;\n }\n }\n\n get countable () {\n return (this.info & binary.BIT2) > 0\n }\n\n /**\n * Whether this item was deleted or not.\n * @type {Boolean}\n */\n get deleted () {\n return (this.info & binary.BIT3) > 0\n }\n\n set deleted (doDelete) {\n if (this.deleted !== doDelete) {\n this.info ^= binary.BIT3;\n }\n }\n\n markDeleted () {\n this.info |= binary.BIT3;\n }\n\n /**\n * Return the creator clientID of the missing op or define missing items and return null.\n *\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) {\n return this.origin.client\n }\n if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) {\n return this.rightOrigin.client\n }\n if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) {\n return this.parent.client\n }\n\n // We have all missing ids, now find the items\n\n if (this.origin) {\n this.left = getItemCleanEnd(transaction, store, this.origin);\n this.origin = this.left.lastId;\n }\n if (this.rightOrigin) {\n this.right = getItemCleanStart(transaction, this.rightOrigin);\n this.rightOrigin = this.right.id;\n }\n if ((this.left && this.left.constructor === GC) || (this.right && this.right.constructor === GC)) {\n this.parent = null;\n } else if (!this.parent) {\n // only set parent if this shouldn't be garbage collected\n if (this.left && this.left.constructor === Item) {\n this.parent = this.left.parent;\n this.parentSub = this.left.parentSub;\n }\n if (this.right && this.right.constructor === Item) {\n this.parent = this.right.parent;\n this.parentSub = this.right.parentSub;\n }\n } else if (this.parent.constructor === ID) {\n const parentItem = getItem(store, this.parent);\n if (parentItem.constructor === GC) {\n this.parent = null;\n } else {\n this.parent = /** @type {ContentType} */ (parentItem.content).type;\n }\n }\n return null\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n if (offset > 0) {\n this.id.clock += offset;\n this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1));\n this.origin = this.left.lastId;\n this.content = this.content.splice(offset);\n this.length -= offset;\n }\n\n if (this.parent) {\n if ((!this.left && (!this.right || this.right.left !== null)) || (this.left && this.left.right !== this.right)) {\n /**\n * @type {Item|null}\n */\n let left = this.left;\n\n /**\n * @type {Item|null}\n */\n let o;\n // set o to the first conflicting item\n if (left !== null) {\n o = left.right;\n } else if (this.parentSub !== null) {\n o = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null;\n while (o !== null && o.left !== null) {\n o = o.left;\n }\n } else {\n o = /** @type {AbstractType} */ (this.parent)._start;\n }\n // TODO: use something like DeleteSet here (a tree implementation would be best)\n // @todo use global set definitions\n /**\n * @type {Set}\n */\n const conflictingItems = new Set();\n /**\n * @type {Set}\n */\n const itemsBeforeOrigin = new Set();\n // Let c in conflictingItems, b in itemsBeforeOrigin\n // ***{origin}bbbb{this}{c,b}{c,b}{o}***\n // Note that conflictingItems is a subset of itemsBeforeOrigin\n while (o !== null && o !== this.right) {\n itemsBeforeOrigin.add(o);\n conflictingItems.add(o);\n if (compareIDs(this.origin, o.origin)) {\n // case 1\n if (o.id.client < this.id.client) {\n left = o;\n conflictingItems.clear();\n } else if (compareIDs(this.rightOrigin, o.rightOrigin)) {\n // this and o are conflicting and point to the same integration points. The id decides which item comes first.\n // Since this is to the left of o, we can break here\n break\n } // else, o might be integrated before an item that this conflicts with. If so, we will find it in the next iterations\n } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { // use getItem instead of getItemCleanEnd because we don't want / need to split items.\n // case 2\n if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) {\n left = o;\n conflictingItems.clear();\n }\n } else {\n break\n }\n o = o.right;\n }\n this.left = left;\n }\n // reconnect left/right + update parent map/start if necessary\n if (this.left !== null) {\n const right = this.left.right;\n this.right = right;\n this.left.right = this;\n } else {\n let r;\n if (this.parentSub !== null) {\n r = /** @type {AbstractType} */ (this.parent)._map.get(this.parentSub) || null;\n while (r !== null && r.left !== null) {\n r = r.left;\n }\n } else {\n r = /** @type {AbstractType} */ (this.parent)._start\n ;/** @type {AbstractType} */ (this.parent)._start = this;\n }\n this.right = r;\n }\n if (this.right !== null) {\n this.right.left = this;\n } else if (this.parentSub !== null) {\n // set as current parent value if right === null and this is parentSub\n /** @type {AbstractType} */ (this.parent)._map.set(this.parentSub, this);\n if (this.left !== null) {\n // this is the current attribute value of parent. delete right\n this.left.delete(transaction);\n }\n }\n // adjust length of parent\n if (this.parentSub === null && this.countable && !this.deleted) {\n /** @type {AbstractType} */ (this.parent)._length += this.length;\n }\n addStruct(transaction.doc.store, this);\n this.content.integrate(transaction, this);\n // add parent to transaction.changed\n addChangedTypeToTransaction(transaction, /** @type {AbstractType} */ (this.parent), this.parentSub);\n if ((/** @type {AbstractType} */ (this.parent)._item !== null && /** @type {AbstractType} */ (this.parent)._item.deleted) || (this.parentSub !== null && this.right !== null)) {\n // delete if parent is deleted or if this is not the current attribute value of parent\n this.delete(transaction);\n }\n } else {\n // parent is not defined. Integrate GC struct instead\n new GC(this.id, this.length).integrate(transaction, 0);\n }\n }\n\n /**\n * Returns the next non-deleted item\n */\n get next () {\n let n = this.right;\n while (n !== null && n.deleted) {\n n = n.right;\n }\n return n\n }\n\n /**\n * Returns the previous non-deleted item\n */\n get prev () {\n let n = this.left;\n while (n !== null && n.deleted) {\n n = n.left;\n }\n return n\n }\n\n /**\n * Computes the last content address of this Item.\n */\n get lastId () {\n // allocating ids is pretty costly because of the amount of ids created, so we try to reuse whenever possible\n return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1)\n }\n\n /**\n * Try to merge two items\n *\n * @param {Item} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (\n this.constructor === right.constructor &&\n compareIDs(right.origin, this.lastId) &&\n this.right === right &&\n compareIDs(this.rightOrigin, right.rightOrigin) &&\n this.id.client === right.id.client &&\n this.id.clock + this.length === right.id.clock &&\n this.deleted === right.deleted &&\n this.redone === null &&\n right.redone === null &&\n this.content.constructor === right.content.constructor &&\n this.content.mergeWith(right.content)\n ) {\n const searchMarker = /** @type {AbstractType} */ (this.parent)._searchMarker;\n if (searchMarker) {\n searchMarker.forEach(marker => {\n if (marker.p === right) {\n // right is going to be \"forgotten\" so we need to update the marker\n marker.p = this;\n // adjust marker index\n if (!this.deleted && this.countable) {\n marker.index -= this.length;\n }\n }\n });\n }\n if (right.keep) {\n this.keep = true;\n }\n this.right = right.right;\n if (this.right !== null) {\n this.right.left = this;\n }\n this.length += right.length;\n return true\n }\n return false\n }\n\n /**\n * Mark this Item as deleted.\n *\n * @param {Transaction} transaction\n */\n delete (transaction) {\n if (!this.deleted) {\n const parent = /** @type {AbstractType} */ (this.parent);\n // adjust the length of parent\n if (this.countable && this.parentSub === null) {\n parent._length -= this.length;\n }\n this.markDeleted();\n addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length);\n addChangedTypeToTransaction(transaction, parent, this.parentSub);\n this.content.delete(transaction);\n }\n }\n\n /**\n * @param {StructStore} store\n * @param {boolean} parentGCd\n */\n gc (store, parentGCd) {\n if (!this.deleted) {\n throw error.unexpectedCase()\n }\n this.content.gc(store);\n if (parentGCd) {\n replaceStruct(store, this, new GC(this.id, this.length));\n } else {\n this.content = new ContentDeleted(this.length);\n }\n }\n\n /**\n * Transform the properties of this type to binary and write it to an\n * BinaryEncoder.\n *\n * This is called when this Item is sent to a remote peer.\n *\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.\n * @param {number} offset\n */\n write (encoder, offset) {\n const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin;\n const rightOrigin = this.rightOrigin;\n const parentSub = this.parentSub;\n const info = (this.content.getRef() & binary.BITS5) |\n (origin === null ? 0 : binary.BIT8) | // origin is defined\n (rightOrigin === null ? 0 : binary.BIT7) | // right origin is defined\n (parentSub === null ? 0 : binary.BIT6); // parentSub is non-null\n encoder.writeInfo(info);\n if (origin !== null) {\n encoder.writeLeftID(origin);\n }\n if (rightOrigin !== null) {\n encoder.writeRightID(rightOrigin);\n }\n if (origin === null && rightOrigin === null) {\n const parent = /** @type {AbstractType} */ (this.parent);\n if (parent._item !== undefined) {\n const parentItem = parent._item;\n if (parentItem === null) {\n // parent type on y._map\n // find the correct key\n const ykey = findRootTypeKey(parent);\n encoder.writeParentInfo(true); // write parentYKey\n encoder.writeString(ykey);\n } else {\n encoder.writeParentInfo(false); // write parent id\n encoder.writeLeftID(parentItem.id);\n }\n } else if (parent.constructor === String) { // this edge case was added by differential updates\n encoder.writeParentInfo(true); // write parentYKey\n encoder.writeString(parent);\n } else if (parent.constructor === ID) {\n encoder.writeParentInfo(false); // write parent id\n encoder.writeLeftID(parent);\n } else {\n error.unexpectedCase();\n }\n if (parentSub !== null) {\n encoder.writeString(parentSub);\n }\n }\n this.content.write(encoder, offset);\n }\n}\n\n/**\n * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder\n * @param {number} info\n */\nconst readItemContent = (decoder, info) => contentRefs[info & binary.BITS5](decoder);\n\n/**\n * A lookup map for reading Item content.\n *\n * @type {Array}\n */\nconst contentRefs = [\n () => { error.unexpectedCase(); }, // GC is not ItemContent\n readContentDeleted, // 1\n readContentJSON, // 2\n readContentBinary, // 3\n readContentString, // 4\n readContentEmbed, // 5\n readContentFormat, // 6\n readContentType, // 7\n readContentAny, // 8\n readContentDoc, // 9\n () => { error.unexpectedCase(); } // 10 - Skip is not ItemContent\n];\n\nconst structSkipRefNumber = 10;\n\n/**\n * @private\n */\nclass Skip extends AbstractStruct {\n get deleted () {\n return true\n }\n\n delete () {}\n\n /**\n * @param {Skip} right\n * @return {boolean}\n */\n mergeWith (right) {\n if (this.constructor !== right.constructor) {\n return false\n }\n this.length += right.length;\n return true\n }\n\n /**\n * @param {Transaction} transaction\n * @param {number} offset\n */\n integrate (transaction, offset) {\n // skip structs cannot be integrated\n error.unexpectedCase();\n }\n\n /**\n * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {number} offset\n */\n write (encoder, offset) {\n encoder.writeInfo(structSkipRefNumber);\n // write as VarUint because Skips can't make use of predictable length-encoding\n encoding.writeVarUint(encoder.restEncoder, this.length - offset);\n }\n\n /**\n * @param {Transaction} transaction\n * @param {StructStore} store\n * @return {null | number}\n */\n getMissing (transaction, store) {\n return null\n }\n}\n\n/** eslint-env browser */\n\n\nconst glo = /** @type {any} */ (typeof globalThis !== 'undefined'\n ? globalThis\n : typeof window !== 'undefined'\n ? window\n // @ts-ignore\n : typeof global !== 'undefined' ? global : {});\n\nconst importIdentifier = '__ $YJS$ __';\n\nif (glo[importIdentifier] === true) {\n /**\n * Dear reader of this message. Please take this seriously.\n *\n * If you see this message, make sure that you only import one version of Yjs. In many cases,\n * your package manager installs two versions of Yjs that are used by different packages within your project.\n * Another reason for this message is that some parts of your project use the commonjs version of Yjs\n * and others use the EcmaScript version of Yjs.\n *\n * This often leads to issues that are hard to debug. We often need to perform constructor checks,\n * e.g. `struct instanceof GC`. If you imported different versions of Yjs, it is impossible for us to\n * do the constructor checks anymore - which might break the CRDT algorithm.\n *\n * https://github.com/yjs/yjs/issues/438\n */\n console.error('Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438');\n}\nglo[importIdentifier] = true;\n\nexport { AbsolutePosition, AbstractConnector, AbstractStruct, AbstractType, YArray as Array, ContentAny, ContentBinary, ContentDeleted, ContentDoc, ContentEmbed, ContentFormat, ContentJSON, ContentString, ContentType, Doc, GC, ID, Item, YMap as Map, PermanentUserData, RelativePosition, Skip, Snapshot, YText as Text, Transaction, UndoManager, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, YXmlElement as XmlElement, YXmlFragment as XmlFragment, YXmlHook as XmlHook, YXmlText as XmlText, YArrayEvent, YEvent, YMapEvent, YTextEvent, YXmlEvent, applyUpdate, applyUpdateV2, cleanupYTextFormatting, compareIDs, compareRelativePositions, convertUpdateFormatV1ToV2, convertUpdateFormatV2ToV1, createAbsolutePositionFromRelativePosition, createDeleteSet, createDeleteSetFromStructStore, createDocFromSnapshot, createID, createRelativePositionFromJSON, createRelativePositionFromTypeIndex, createSnapshot, decodeRelativePosition, decodeSnapshot, decodeSnapshotV2, decodeStateVector, decodeUpdate, decodeUpdateV2, diffUpdate, diffUpdateV2, emptySnapshot, encodeRelativePosition, encodeSnapshot, encodeSnapshotV2, encodeStateAsUpdate, encodeStateAsUpdateV2, encodeStateVector, encodeStateVectorFromUpdate, encodeStateVectorFromUpdateV2, equalDeleteSets, equalSnapshots, findIndexSS, findRootTypeKey, getItem, getState, getTypeChildren, isDeleted, isParentOf, iterateDeletedStructs, logType, logUpdate, logUpdateV2, mergeDeleteSets, mergeUpdates, mergeUpdatesV2, obfuscateUpdate, obfuscateUpdateV2, parseUpdateMeta, parseUpdateMetaV2, readUpdate, readUpdateV2, relativePositionToJSON, snapshot, snapshotContainsUpdate, transact, tryGc, typeListToArraySnapshot, typeMapGetAllSnapshot, typeMapGetSnapshot };\n//# sourceMappingURL=yjs.mjs.map\n"],"names":["ds","DeleteItem","constructor","clock","len","DeleteSet","clients","Map","iterateDeletedStructs","transaction","f","forEach","deletes","clientid","structs","doc","store","get","i","length","del","iterateStructs","findIndexDS","dis","left","right","midindex","mid","midclock","isDeleted","id","client","undefined","sortAndMergeDeleteSet","dels","j","sort","a","b","mergeDeleteSets","dss","merged","dssI","delsLeft","has","slice","set","addToDeleteSet","push","writeDeleteSet","encoder","restEncoder","size","entries","dsitems","resetDsCurVal","item","writeDsClock","writeDsLen","readDeleteSet","decoder","numClients","restDecoder","numberOfDeletes","dsField","readDsClock","readDsLen","readAndApplyDeleteSet","unappliedDS","state","getState","clockEnd","index","findIndexSS","struct","deleted","splice","splitItem","delete","UpdateEncoderV2","toUint8Array","generateNewClientId","Doc","guid","collectionid","gc","gcFilter","meta","autoLoad","shouldLoad","clientID","share","StructStore","_transaction","_transactionCleanups","subdocs","Set","_item","isLoaded","isSynced","whenLoaded","resolve","on","provideSyncedPromise","eventHandler","off","whenSynced","emit","load","transact","parent","subdocsLoaded","add","getSubdocs","getSubdocGuids","map","origin","name","TypeConstructor","AbstractType","type","t","_integrate","Constr","_map","n","_start","_length","getArray","YArray","getText","YText","getMap","YMap","getXmlElement","YXmlElement","getXmlFragment","YXmlFragment","toJSON","value","key","destroy","subdoc","content","opts","subdocsAdded","subdocsRemoved","DSDecoderV1","UpdateDecoderV1","readLeftID","createID","readRightID","readClient","readInfo","readString","readParentInfo","readTypeRef","readLen","readAny","readBuf","readJSON","JSON","parse","readKey","DSDecoderV2","dsCurrVal","diff","UpdateDecoderV2","keys","keyClockDecoder","clientDecoder","leftClockDecoder","rightClockDecoder","infoDecoder","stringDecoder","parentInfoDecoder","typeRefDecoder","lenDecoder","ID","read","keyClock","DSEncoderV1","UpdateEncoderV1","writeLeftID","writeRightID","writeClient","writeInfo","info","writeString","s","writeParentInfo","isYKey","writeTypeRef","writeLen","writeAny","any","writeBuf","buf","writeJSON","embed","stringify","writeKey","DSEncoderV2","keyMap","keyClockEncoder","clientEncoder","leftClockEncoder","rightClockEncoder","infoEncoder","stringEncoder","parentInfoEncoder","typeRefEncoder","lenEncoder","write","writeStructs","startNewStructs","firstStruct","writeClientsStructs","_sm","sm","getStateVector","_clock","readClientsStructRefs","clientRefs","numOfStateUpdates","numberOfStructs","refs","GC","Skip","cantCopyParentInfo","Item","readItemContent","integrateStructs","clientsStructRefs","stack","clientsStructRefsIds","getNextStructTarget","nextStructsTarget","pop","curStructsTarget","restStructs","missingSV","updateMissingSv","mclock","stackHead","addStackToRestSS","unapplicableItems","filter","c","offset","localClock","missing","getMissing","structRefs","integrate","update","writeStructsFromTransaction","beforeState","readUpdateV2","ydoc","transactionOrigin","structDecoder","local","retry","pending","pendingStructs","mergeUpdatesV2","dsRest","pendingDs","pendingDSUpdate","dsRest2","applyUpdateV2","YDecoder","applyUpdate","EventHandler","l","createEventHandler","addEventHandlerListener","removeEventHandlerListener","g","console","error","callEventHandlerListeners","arg0","arg1","compareIDs","findRootTypeKey","sv","isVisible","snapshot","splitSnapshotAffectedStructs","getItemCleanStart","lastStruct","addStruct","getItem","findIndexCleanStart","getItemCleanEnd","replaceStruct","newStruct","clockStart","Transaction","deleteSet","afterState","changed","changedParentTypes","_mergeStructs","_needFormattingCleanup","writeUpdateMessageFromTransaction","addChangedTypeToTransaction","parentSub","tryToMergeWithLefts","pos","mergeWith","tryGcDeleteSet","deleteItems","di","deleteItem","endDeleteItemClock","si","keep","tryMergeDeleteSet","mostRightIndexToCheck","cleanupTransactions","transactionCleanups","mergeStructs","fs","subs","itemtype","_callObserver","events","_dEH","event","target","currentTarget","_path","event1","event2","path","cleanupYTextAfterTransaction","beforeClock","firstChangePos","replacedStructPos","_observers","loaded","added","removed","initialCall","result","finishCleanup","LazyStructReader","filterSkips","gen","lazyStructReaderGenerator","curr","done","next","LazyStructWriter","currClient","startClock","written","clientStructs","sliceStruct","leftItem","rightOrigin","updates","YEncoder","updateDecoders","lazyStructDecoders","currWrite","updateEncoder","lazyStructEncoder","dec","dec1","dec2","clockDiff","currDecoder","firstClient","iterated","writeStructToLazyStructWriter","finishLazyStructWriting","flushLazyStructWriter","lazyWriter","partStructs","errorComputeChanges","YEvent","_changes","_keys","_delta","getPathTo","action","oldValue","adds","prev","getContent","delta","changes","lastOp","packOp","insert","concat","retain","child","unshift","countable","globalSearchMarkerTimestamp","ArraySearchMarker","p","marker","timestamp","refreshMarkerTimestamp","overwriteMarker","markPosition","searchMarker","reduce","pm","findMarker","yarray","_searchMarker","pindex","updateMarkerChanges","m","callTypeObservers","changedType","_eH","y","_copy","clone","_write","_encoder","_first","_parentSubs","observe","observeDeep","unobserve","unobserveDeep","typeListSlice","start","end","cs","typeListToArray","typeListForEach","typeListMap","typeListCreateIterator","currentContent","currentContentIndex","Symbol","iterator","typeListGet","typeListInsertGenericsAfter","referenceItem","ownClientId","jsonContent","packJsonContent","lastId","ContentAny","Number","Object","Boolean","Array","String","Uint8Array","ArrayBuffer","ContentBinary","ContentDoc","ContentType","lengthExceeded","typeListInsertGenerics","startIndex","typeListPushGenerics","maxMarker","currMarker","typeListDelete","startLength","typeMapDelete","typeMapSet","typeMapGet","val","typeMapGetAll","res","typeMapHas","typeMapGetAllSnapshot","v","createMapIterator","entry","YArrayEvent","_prelimContent","from","items","arr","toArray","el","parentSubs","YArrayRefID","YMapEvent","ymap","keysChanged","values","clear","_value","YMapRefID","equalAttrs","ItemTextListPosition","currentAttributes","forward","ContentFormat","updateCurrentAttributes","findNextPosition","count","findPosition","useSearchMarker","insertNegatedAttributes","currPos","negatedAttributes","nextFormat","format","minimizeAttributeChanges","attributes","insertAttributes","currentVal","insertText","text","_val","ContentString","ContentEmbed","getLength","formatText","attr","newlines","cleanupFormattingGap","startAttributes","currAttributes","endFormats","cf","cleanups","reachedCurr","startAttrValue","cleanupContextlessFormattingGap","attrs","cleanupYTextFormatting","needFullCleanup","afterClock","yText","_hasFormatting","deleteText","startAttrs","YTextEvent","ytext","childListChanged","sub","oldAttributes","deleteLen","addOp","op","str","curVal","string","_pending","e","applyDelta","toDelta","toString","sanitize","ins","prevSnapshot","computeYChange","ops","packStr","addAttributes","computeDelta","cur","user","k","insertEmbed","removeAttribute","attributeName","setAttribute","attributeValue","getAttribute","getAttributes","YTextRefID","YXmlTreeWalker","root","_filter","_root","_currentNode","_firstCall","firstChild","first","createTreeWalker","querySelector","query","toUpperCase","element","nodeName","querySelectorAll","YXmlEvent","xml","join","toDOM","_document","document","hooks","binding","fragment","createDocumentFragment","_createAssociation","xmlType","insertBefore","insertAfter","ref","pc","findIndex","YXmlFragmentRefID","_prelimAttrs","nextSibling","prevSibling","stringBuilder","keysLen","toLocaleLowerCase","attrsString","hasAttribute","dom","createElement","yxml","appendChild","YXmlElementRefID","attributesChanged","YXmlHook","hookName","hook","createDom","YXmlHookRefID","YXmlText","createTextNode","nestedNodes","node","YXmlTextRefID","AbstractStruct","encodingRef","isCountable","copy","getRef","ContentDeleted","markDeleted","createDocFromOpts","_offset","_right","ContentJSON","split","firstCharCode","charCodeAt","typeRefs","_decoder","rightItem","redone","isMarked","doKeep","doDelete","parentItem","o","conflictingItems","itemsBeforeOrigin","r","parentGCd","ykey","contentRefs","glo","globalThis","window","global","importIdentifier"],"sourceRoot":""}