"use strict";
/*
 * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
(self["webpackChunk_JUPYTERLAB_CORE_OUTPUT"] = self["webpackChunk_JUPYTERLAB_CORE_OUTPUT"] || []).push([["vendors-node_modules_yjs_dist_yjs_mjs"],{

/***/ "../node_modules/lib0/dom.js":
/*!***********************************!*\
  !*** ../node_modules/lib0/dom.js ***!
  \***********************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   CDATA_SECTION_NODE: () => (/* binding */ CDATA_SECTION_NODE),\n/* harmony export */   COMMENT_NODE: () => (/* binding */ COMMENT_NODE),\n/* harmony export */   DOCUMENT_FRAGMENT_NODE: () => (/* binding */ DOCUMENT_FRAGMENT_NODE),\n/* harmony export */   DOCUMENT_NODE: () => (/* binding */ DOCUMENT_NODE),\n/* harmony export */   DOCUMENT_TYPE_NODE: () => (/* binding */ DOCUMENT_TYPE_NODE),\n/* harmony export */   ELEMENT_NODE: () => (/* binding */ ELEMENT_NODE),\n/* harmony export */   TEXT_NODE: () => (/* binding */ TEXT_NODE),\n/* harmony export */   addEventListener: () => (/* binding */ addEventListener),\n/* harmony export */   addEventListeners: () => (/* binding */ addEventListeners),\n/* harmony export */   append: () => (/* binding */ append),\n/* harmony export */   appendChild: () => (/* binding */ appendChild),\n/* harmony export */   canvas: () => (/* binding */ canvas),\n/* harmony export */   checkNodeType: () => (/* binding */ checkNodeType),\n/* harmony export */   createDocumentFragment: () => (/* binding */ createDocumentFragment),\n/* harmony export */   createElement: () => (/* binding */ createElement),\n/* harmony export */   createTextNode: () => (/* binding */ createTextNode),\n/* harmony export */   doc: () => (/* binding */ doc),\n/* harmony export */   domParser: () => (/* binding */ domParser),\n/* harmony export */   element: () => (/* binding */ element),\n/* harmony export */   emitCustomEvent: () => (/* binding */ emitCustomEvent),\n/* harmony export */   fragment: () => (/* binding */ fragment),\n/* harmony export */   getElementById: () => (/* binding */ getElementById),\n/* harmony export */   insertBefore: () => (/* binding */ insertBefore),\n/* harmony export */   isParentOf: () => (/* binding */ isParentOf),\n/* harmony export */   mapToStyleString: () => (/* binding */ mapToStyleString),\n/* harmony export */   pairToStyleString: () => (/* binding */ pairToStyleString),\n/* harmony export */   pairsToStyleString: () => (/* binding */ pairsToStyleString),\n/* harmony export */   parseElement: () => (/* binding */ parseElement),\n/* harmony export */   parseFragment: () => (/* binding */ parseFragment),\n/* harmony export */   querySelector: () => (/* binding */ querySelector),\n/* harmony export */   querySelectorAll: () => (/* binding */ querySelectorAll),\n/* harmony export */   remove: () => (/* binding */ remove),\n/* harmony export */   removeEventListener: () => (/* binding */ removeEventListener),\n/* harmony export */   removeEventListeners: () => (/* binding */ removeEventListeners),\n/* harmony export */   replaceWith: () => (/* binding */ replaceWith),\n/* harmony export */   setAttributes: () => (/* binding */ setAttributes),\n/* harmony export */   setAttributesMap: () => (/* binding */ setAttributesMap),\n/* harmony export */   text: () => (/* binding */ text)\n/* harmony export */ });\n/* harmony import */ var _pair_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./pair.js */ \"../node_modules/lib0/pair.js\");\n/* harmony import */ var _map_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./map.js */ \"../node_modules/lib0/map.js\");\n/* eslint-env browser */\n\n/**\n * Utility module to work with the DOM.\n *\n * @module dom\n */\n\n\n\n\n/* c8 ignore start */\n/**\n * @type {Document}\n */\nconst doc = /** @type {Document} */ (typeof document !== 'undefined' ? document : {})\n\n/**\n * @param {string} name\n * @return {HTMLElement}\n */\nconst createElement = name => doc.createElement(name)\n\n/**\n * @return {DocumentFragment}\n */\nconst createDocumentFragment = () => doc.createDocumentFragment()\n\n/**\n * @param {string} text\n * @return {Text}\n */\nconst createTextNode = text => doc.createTextNode(text)\n\nconst domParser = /** @type {DOMParser} */ (typeof DOMParser !== 'undefined' ? new DOMParser() : null)\n\n/**\n * @param {HTMLElement} el\n * @param {string} name\n * @param {Object} opts\n */\nconst emitCustomEvent = (el, name, opts) => el.dispatchEvent(new CustomEvent(name, opts))\n\n/**\n * @param {Element} el\n * @param {Array<pair.Pair<string,string|boolean>>} attrs Array of key-value pairs\n * @return {Element}\n */\nconst setAttributes = (el, attrs) => {\n  _pair_js__WEBPACK_IMPORTED_MODULE_0__.forEach(attrs, (key, value) => {\n    if (value === false) {\n      el.removeAttribute(key)\n    } else if (value === true) {\n      el.setAttribute(key, '')\n    } else {\n      // @ts-ignore\n      el.setAttribute(key, value)\n    }\n  })\n  return el\n}\n\n/**\n * @param {Element} el\n * @param {Map<string, string>} attrs Array of key-value pairs\n * @return {Element}\n */\nconst setAttributesMap = (el, attrs) => {\n  attrs.forEach((value, key) => { el.setAttribute(key, value) })\n  return el\n}\n\n/**\n * @param {Array<Node>|HTMLCollection} children\n * @return {DocumentFragment}\n */\nconst fragment = children => {\n  const fragment = createDocumentFragment()\n  for (let i = 0; i < children.length; i++) {\n    appendChild(fragment, children[i])\n  }\n  return fragment\n}\n\n/**\n * @param {Element} parent\n * @param {Array<Node>} nodes\n * @return {Element}\n */\nconst append = (parent, nodes) => {\n  appendChild(parent, fragment(nodes))\n  return parent\n}\n\n/**\n * @param {HTMLElement} el\n */\nconst remove = el => el.remove()\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\nconst addEventListener = (el, name, f) => el.addEventListener(name, f)\n\n/**\n * @param {EventTarget} el\n * @param {string} name\n * @param {EventListener} f\n */\nconst removeEventListener = (el, name, f) => el.removeEventListener(name, f)\n\n/**\n * @param {Node} node\n * @param {Array<pair.Pair<string,EventListener>>} listeners\n * @return {Node}\n */\nconst addEventListeners = (node, listeners) => {\n  _pair_js__WEBPACK_IMPORTED_MODULE_0__.forEach(listeners, (name, f) => addEventListener(node, name, f))\n  return node\n}\n\n/**\n * @param {Node} node\n * @param {Array<pair.Pair<string,EventListener>>} listeners\n * @return {Node}\n */\nconst removeEventListeners = (node, listeners) => {\n  _pair_js__WEBPACK_IMPORTED_MODULE_0__.forEach(listeners, (name, f) => removeEventListener(node, name, f))\n  return node\n}\n\n/**\n * @param {string} name\n * @param {Array<pair.Pair<string,string>|pair.Pair<string,boolean>>} attrs Array of key-value pairs\n * @param {Array<Node>} children\n * @return {Element}\n */\nconst element = (name, attrs = [], children = []) =>\n  append(setAttributes(createElement(name), attrs), children)\n\n/**\n * @param {number} width\n * @param {number} height\n */\nconst canvas = (width, height) => {\n  const c = /** @type {HTMLCanvasElement} */ (createElement('canvas'))\n  c.height = height\n  c.width = width\n  return c\n}\n\n/**\n * @param {string} t\n * @return {Text}\n */\nconst text = createTextNode\n\n/**\n * @param {pair.Pair<string,string>} pair\n */\nconst pairToStyleString = pair => `${pair.left}:${pair.right};`\n\n/**\n * @param {Array<pair.Pair<string,string>>} pairs\n * @return {string}\n */\nconst pairsToStyleString = pairs => pairs.map(pairToStyleString).join('')\n\n/**\n * @param {Map<string,string>} m\n * @return {string}\n */\nconst mapToStyleString = m => _map_js__WEBPACK_IMPORTED_MODULE_1__.map(m, (value, key) => `${key}:${value};`).join('')\n\n/**\n * @todo should always query on a dom element\n *\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {HTMLElement | null}\n */\nconst querySelector = (el, query) => el.querySelector(query)\n\n/**\n * @param {HTMLElement|ShadowRoot} el\n * @param {string} query\n * @return {NodeListOf<HTMLElement>}\n */\nconst querySelectorAll = (el, query) => el.querySelectorAll(query)\n\n/**\n * @param {string} id\n * @return {HTMLElement}\n */\nconst getElementById = id => /** @type {HTMLElement} */ (doc.getElementById(id))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\nconst _parse = html => domParser.parseFromString(`<html><body>${html}</body></html>`, 'text/html').body\n\n/**\n * @param {string} html\n * @return {DocumentFragment}\n */\nconst parseFragment = html => fragment(/** @type {any} */ (_parse(html).childNodes))\n\n/**\n * @param {string} html\n * @return {HTMLElement}\n */\nconst parseElement = html => /** @type HTMLElement */ (_parse(html).firstElementChild)\n\n/**\n * @param {HTMLElement} oldEl\n * @param {HTMLElement|DocumentFragment} newEl\n */\nconst replaceWith = (oldEl, newEl) => oldEl.replaceWith(newEl)\n\n/**\n * @param {HTMLElement} parent\n * @param {HTMLElement} el\n * @param {Node|null} ref\n * @return {HTMLElement}\n */\nconst insertBefore = (parent, el, ref) => parent.insertBefore(el, ref)\n\n/**\n * @param {Node} parent\n * @param {Node} child\n * @return {Node}\n */\nconst appendChild = (parent, child) => parent.appendChild(child)\n\nconst ELEMENT_NODE = doc.ELEMENT_NODE\nconst TEXT_NODE = doc.TEXT_NODE\nconst CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE\nconst COMMENT_NODE = doc.COMMENT_NODE\nconst DOCUMENT_NODE = doc.DOCUMENT_NODE\nconst DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE\nconst DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE\n\n/**\n * @param {any} node\n * @param {number} type\n */\nconst checkNodeType = (node, type) => node.nodeType === type\n\n/**\n * @param {Node} parent\n * @param {HTMLElement} child\n */\nconst isParentOf = (parent, child) => {\n  let p = child.parentNode\n  while (p && p !== parent) {\n    p = p.parentNode\n  }\n  return p === parent\n}\n/* c8 ignore stop */\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/dom.js?");

/***/ }),

/***/ "../node_modules/lib0/eventloop.js":
/*!*****************************************!*\
  !*** ../node_modules/lib0/eventloop.js ***!
  \*****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   Animation: () => (/* binding */ Animation),\n/* harmony export */   animationFrame: () => (/* binding */ animationFrame),\n/* harmony export */   createDebouncer: () => (/* binding */ createDebouncer),\n/* harmony export */   enqueue: () => (/* binding */ enqueue),\n/* harmony export */   idleCallback: () => (/* binding */ idleCallback),\n/* harmony export */   interval: () => (/* binding */ interval),\n/* harmony export */   timeout: () => (/* binding */ timeout)\n/* harmony export */ });\n/* global requestIdleCallback, requestAnimationFrame, cancelIdleCallback, cancelAnimationFrame */\n\n/**\n * Utility module to work with EcmaScript's event loop.\n *\n * @module eventloop\n */\n\n/**\n * @type {Array<function>}\n */\nlet queue = []\n\nconst _runQueue = () => {\n  for (let i = 0; i < queue.length; i++) {\n    queue[i]()\n  }\n  queue = []\n}\n\n/**\n * @param {function():void} f\n */\nconst enqueue = f => {\n  queue.push(f)\n  if (queue.length === 1) {\n    setTimeout(_runQueue, 0)\n  }\n}\n\n/**\n * @typedef {Object} TimeoutObject\n * @property {function} TimeoutObject.destroy\n */\n\n/**\n * @param {function(number):void} clearFunction\n */\nconst createTimeoutClass = clearFunction => class TT {\n  /**\n   * @param {number} timeoutId\n   */\n  constructor (timeoutId) {\n    this._ = timeoutId\n  }\n\n  destroy () {\n    clearFunction(this._)\n  }\n}\n\nconst Timeout = createTimeoutClass(clearTimeout)\n\n/**\n * @param {number} timeout\n * @param {function} callback\n * @return {TimeoutObject}\n */\nconst timeout = (timeout, callback) => new Timeout(setTimeout(callback, timeout))\n\nconst Interval = createTimeoutClass(clearInterval)\n\n/**\n * @param {number} timeout\n * @param {function} callback\n * @return {TimeoutObject}\n */\nconst interval = (timeout, callback) => new Interval(setInterval(callback, timeout))\n\n/* c8 ignore next */\nconst Animation = createTimeoutClass(arg => typeof requestAnimationFrame !== 'undefined' && cancelAnimationFrame(arg))\n\n/**\n * @param {function(number):void} cb\n * @return {TimeoutObject}\n */\n/* c8 ignore next */\nconst animationFrame = cb => typeof requestAnimationFrame === 'undefined' ? timeout(0, cb) : new Animation(requestAnimationFrame(cb))\n\n/* c8 ignore next */\n// @ts-ignore\nconst Idle = createTimeoutClass(arg => typeof cancelIdleCallback !== 'undefined' && cancelIdleCallback(arg))\n\n/**\n * Note: this is experimental and is probably only useful in browsers.\n *\n * @param {function} cb\n * @return {TimeoutObject}\n */\n/* c8 ignore next 2 */\n// @ts-ignore\nconst idleCallback = cb => typeof requestIdleCallback !== 'undefined' ? new Idle(requestIdleCallback(cb)) : timeout(1000, cb)\n\n/**\n * @param {number} timeout Timeout of the debounce action\n * @return {function(function():void):void}\n */\nconst createDebouncer = timeout => {\n  let timer = -1\n  return f => {\n    clearTimeout(timer)\n    if (f) {\n      timer = /** @type {any} */ (setTimeout(f, timeout))\n    }\n  }\n}\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/eventloop.js?");

/***/ }),

/***/ "../node_modules/lib0/iterator.js":
/*!****************************************!*\
  !*** ../node_modules/lib0/iterator.js ***!
  \****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   createIterator: () => (/* binding */ createIterator),\n/* harmony export */   iteratorFilter: () => (/* binding */ iteratorFilter),\n/* harmony export */   iteratorMap: () => (/* binding */ iteratorMap),\n/* harmony export */   mapIterator: () => (/* binding */ mapIterator)\n/* harmony export */ });\n/**\n * Utility module to create and manipulate Iterators.\n *\n * @module iterator\n */\n\n/**\n * @template T,R\n * @param {Iterator<T>} iterator\n * @param {function(T):R} f\n * @return {IterableIterator<R>}\n */\nconst mapIterator = (iterator, f) => ({\n  [Symbol.iterator] () {\n    return this\n  },\n  // @ts-ignore\n  next () {\n    const r = iterator.next()\n    return { value: r.done ? undefined : f(r.value), done: r.done }\n  }\n})\n\n/**\n * @template T\n * @param {function():IteratorResult<T>} next\n * @return {IterableIterator<T>}\n */\nconst createIterator = next => ({\n  /**\n   * @return {IterableIterator<T>}\n   */\n  [Symbol.iterator] () {\n    return this\n  },\n  // @ts-ignore\n  next\n})\n\n/**\n * @template T\n * @param {Iterator<T>} iterator\n * @param {function(T):boolean} filter\n */\nconst iteratorFilter = (iterator, filter) => createIterator(() => {\n  let res\n  do {\n    res = iterator.next()\n  } while (!res.done && !filter(res.value))\n  return res\n})\n\n/**\n * @template T,M\n * @param {Iterator<T>} iterator\n * @param {function(T):M} fmap\n */\nconst iteratorMap = (iterator, fmap) => createIterator(() => {\n  const { done, value } = iterator.next()\n  return { done, value: done ? undefined : fmap(value) }\n})\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/iterator.js?");

/***/ }),

/***/ "../node_modules/lib0/json.js":
/*!************************************!*\
  !*** ../node_modules/lib0/json.js ***!
  \************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   parse: () => (/* binding */ parse),\n/* harmony export */   stringify: () => (/* binding */ stringify)\n/* harmony export */ });\n/**\n * JSON utility functions.\n *\n * @module json\n */\n\n/**\n * Transform JavaScript object to JSON.\n *\n * @param {any} object\n * @return {string}\n */\nconst stringify = JSON.stringify\n\n/**\n * Parse JSON object.\n *\n * @param {string} json\n * @return {any}\n */\nconst parse = JSON.parse\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/json.js?");

/***/ }),

/***/ "../node_modules/lib0/logging.common.js":
/*!**********************************************!*\
  !*** ../node_modules/lib0/logging.common.js ***!
  \**********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   BLUE: () => (/* binding */ BLUE),\n/* harmony export */   BOLD: () => (/* binding */ BOLD),\n/* harmony export */   GREEN: () => (/* binding */ GREEN),\n/* harmony export */   GREY: () => (/* binding */ GREY),\n/* harmony export */   ORANGE: () => (/* binding */ ORANGE),\n/* harmony export */   PURPLE: () => (/* binding */ PURPLE),\n/* harmony export */   RED: () => (/* binding */ RED),\n/* harmony export */   UNBOLD: () => (/* binding */ UNBOLD),\n/* harmony export */   UNCOLOR: () => (/* binding */ UNCOLOR),\n/* harmony export */   computeNoColorLoggingArgs: () => (/* binding */ computeNoColorLoggingArgs),\n/* harmony export */   createModuleLogger: () => (/* binding */ createModuleLogger)\n/* harmony export */ });\n/* harmony import */ var _symbol_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./symbol.js */ \"../node_modules/lib0/symbol.js\");\n/* harmony import */ var _time_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./time.js */ \"../node_modules/lib0/time.js\");\n/* harmony import */ var _environment_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./environment.js */ \"../node_modules/lib0/environment.js\");\n/* harmony import */ var _function_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./function.js */ \"../node_modules/lib0/function.js\");\n\n\n\n\n\nconst BOLD = _symbol_js__WEBPACK_IMPORTED_MODULE_0__.create()\nconst UNBOLD = _symbol_js__WEBPACK_IMPORTED_MODULE_0__.create()\nconst BLUE = _symbol_js__WEBPACK_IMPORTED_MODULE_0__.create()\nconst GREY = _symbol_js__WEBPACK_IMPORTED_MODULE_0__.create()\nconst GREEN = _symbol_js__WEBPACK_IMPORTED_MODULE_0__.create()\nconst RED = _symbol_js__WEBPACK_IMPORTED_MODULE_0__.create()\nconst PURPLE = _symbol_js__WEBPACK_IMPORTED_MODULE_0__.create()\nconst ORANGE = _symbol_js__WEBPACK_IMPORTED_MODULE_0__.create()\nconst UNCOLOR = _symbol_js__WEBPACK_IMPORTED_MODULE_0__.create()\n\n/* c8 ignore start */\n/**\n * @param {Array<string|Symbol|Object|number>} args\n * @return {Array<string|object|number>}\n */\nconst computeNoColorLoggingArgs = args => {\n  const strBuilder = []\n  const logArgs = []\n  // try with formatting until we find something unsupported\n  let i = 0\n  for (; i < args.length; i++) {\n    const arg = args[i]\n    if (arg.constructor === String || arg.constructor === Number) {\n      strBuilder.push(arg)\n    } else if (arg.constructor === Object) {\n      logArgs.push(JSON.stringify(arg))\n    }\n  }\n  return logArgs\n}\n/* c8 ignore stop */\n\nconst loggingColors = [GREEN, PURPLE, ORANGE, BLUE]\nlet nextColor = 0\nlet lastLoggingTime = _time_js__WEBPACK_IMPORTED_MODULE_1__.getUnixTime()\n\n/* c8 ignore start */\n/**\n * @param {function(...any):void} _print\n * @param {string} moduleName\n * @return {function(...any):void}\n */\nconst createModuleLogger = (_print, moduleName) => {\n  const color = loggingColors[nextColor]\n  const debugRegexVar = _environment_js__WEBPACK_IMPORTED_MODULE_2__.getVariable('log')\n  const doLogging = debugRegexVar !== null &&\n    (debugRegexVar === '*' || debugRegexVar === 'true' ||\n      new RegExp(debugRegexVar, 'gi').test(moduleName))\n  nextColor = (nextColor + 1) % loggingColors.length\n  moduleName += ': '\n  return !doLogging\n    ? _function_js__WEBPACK_IMPORTED_MODULE_3__.nop\n    : (...args) => {\n        const timeNow = _time_js__WEBPACK_IMPORTED_MODULE_1__.getUnixTime()\n        const timeDiff = timeNow - lastLoggingTime\n        lastLoggingTime = timeNow\n        _print(\n          color,\n          moduleName,\n          UNCOLOR,\n          ...args.map((arg) =>\n            (typeof arg === 'string' || typeof arg === 'symbol')\n              ? arg\n              : JSON.stringify(arg)\n          ),\n          color,\n          ' +' + timeDiff + 'ms'\n        )\n      }\n}\n/* c8 ignore stop */\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/logging.common.js?");

/***/ }),

/***/ "../node_modules/lib0/logging.js":
/*!***************************************!*\
  !*** ../node_modules/lib0/logging.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   BLUE: () => (/* reexport safe */ _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.BLUE),\n/* harmony export */   BOLD: () => (/* reexport safe */ _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.BOLD),\n/* harmony export */   GREEN: () => (/* reexport safe */ _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.GREEN),\n/* harmony export */   GREY: () => (/* reexport safe */ _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.GREY),\n/* harmony export */   ORANGE: () => (/* reexport safe */ _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.ORANGE),\n/* harmony export */   PURPLE: () => (/* reexport safe */ _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.PURPLE),\n/* harmony export */   RED: () => (/* reexport safe */ _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.RED),\n/* harmony export */   UNBOLD: () => (/* reexport safe */ _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.UNBOLD),\n/* harmony export */   UNCOLOR: () => (/* reexport safe */ _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.UNCOLOR),\n/* harmony export */   VConsole: () => (/* binding */ VConsole),\n/* harmony export */   createModuleLogger: () => (/* binding */ createModuleLogger),\n/* harmony export */   createVConsole: () => (/* binding */ createVConsole),\n/* harmony export */   group: () => (/* binding */ group),\n/* harmony export */   groupCollapsed: () => (/* binding */ groupCollapsed),\n/* harmony export */   groupEnd: () => (/* binding */ groupEnd),\n/* harmony export */   print: () => (/* binding */ print),\n/* harmony export */   printCanvas: () => (/* binding */ printCanvas),\n/* harmony export */   printDom: () => (/* binding */ printDom),\n/* harmony export */   printError: () => (/* binding */ printError),\n/* harmony export */   printImg: () => (/* binding */ printImg),\n/* harmony export */   printImgBase64: () => (/* binding */ printImgBase64),\n/* harmony export */   vconsoles: () => (/* binding */ vconsoles),\n/* harmony export */   warn: () => (/* binding */ warn)\n/* harmony export */ });\n/* harmony import */ var _environment_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./environment.js */ \"../node_modules/lib0/environment.js\");\n/* harmony import */ var _set_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./set.js */ \"../node_modules/lib0/set.js\");\n/* harmony import */ var _pair_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./pair.js */ \"../node_modules/lib0/pair.js\");\n/* harmony import */ var _dom_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dom.js */ \"../node_modules/lib0/dom.js\");\n/* harmony import */ var _json_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./json.js */ \"../node_modules/lib0/json.js\");\n/* harmony import */ var _map_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./map.js */ \"../node_modules/lib0/map.js\");\n/* harmony import */ var _eventloop_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./eventloop.js */ \"../node_modules/lib0/eventloop.js\");\n/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./math.js */ \"../node_modules/lib0/math.js\");\n/* harmony import */ var _logging_common_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logging.common.js */ \"../node_modules/lib0/logging.common.js\");\n/**\n * Isomorphic logging module with support for colors!\n *\n * @module logging\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n/**\n * @type {Object<Symbol,pair.Pair<string,string>>}\n */\nconst _browserStyleMap = {\n  [_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.BOLD]: _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('font-weight', 'bold'),\n  [_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.UNBOLD]: _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('font-weight', 'normal'),\n  [_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.BLUE]: _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('color', 'blue'),\n  [_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.GREEN]: _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('color', 'green'),\n  [_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.GREY]: _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('color', 'grey'),\n  [_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.RED]: _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('color', 'red'),\n  [_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.PURPLE]: _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('color', 'purple'),\n  [_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.ORANGE]: _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate\n  [_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.UNCOLOR]: _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('color', 'black')\n}\n\n/**\n * @param {Array<string|Symbol|Object|number>} args\n * @return {Array<string|object|number>}\n */\n/* c8 ignore start */\nconst computeBrowserLoggingArgs = (args) => {\n  const strBuilder = []\n  const styles = []\n  const currentStyle = _map_js__WEBPACK_IMPORTED_MODULE_2__.create()\n  /**\n   * @type {Array<string|Object|number>}\n   */\n  let logArgs = []\n  // try with formatting until we find something unsupported\n  let i = 0\n  for (; i < args.length; i++) {\n    const arg = args[i]\n    // @ts-ignore\n    const style = _browserStyleMap[arg]\n    if (style !== undefined) {\n      currentStyle.set(style.left, style.right)\n    } else {\n      if (arg.constructor === String || arg.constructor === Number) {\n        const style = _dom_js__WEBPACK_IMPORTED_MODULE_3__.mapToStyleString(currentStyle)\n        if (i > 0 || style.length > 0) {\n          strBuilder.push('%c' + arg)\n          styles.push(style)\n        } else {\n          strBuilder.push(arg)\n        }\n      } else {\n        break\n      }\n    }\n  }\n  if (i > 0) {\n    // create logArgs with what we have so far\n    logArgs = styles\n    logArgs.unshift(strBuilder.join(''))\n  }\n  // append the rest\n  for (; i < args.length; i++) {\n    const arg = args[i]\n    if (!(arg instanceof Symbol)) {\n      logArgs.push(arg)\n    }\n  }\n  return logArgs\n}\n/* c8 ignore stop */\n\n/* c8 ignore start */\nconst computeLoggingArgs = _environment_js__WEBPACK_IMPORTED_MODULE_4__.supportsColor\n  ? computeBrowserLoggingArgs\n  : _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.computeNoColorLoggingArgs\n/* c8 ignore stop */\n\n/**\n * @param {Array<string|Symbol|Object|number>} args\n */\nconst print = (...args) => {\n  console.log(...computeLoggingArgs(args))\n  /* c8 ignore next */\n  vconsoles.forEach((vc) => vc.print(args))\n}\n\n/* c8 ignore start */\n/**\n * @param {Array<string|Symbol|Object|number>} args\n */\nconst warn = (...args) => {\n  console.warn(...computeLoggingArgs(args))\n  args.unshift(_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.ORANGE)\n  vconsoles.forEach((vc) => vc.print(args))\n}\n/* c8 ignore stop */\n\n/**\n * @param {Error} err\n */\n/* c8 ignore start */\nconst printError = (err) => {\n  console.error(err)\n  vconsoles.forEach((vc) => vc.printError(err))\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} url image location\n * @param {number} height height of the image in pixel\n */\n/* c8 ignore start */\nconst printImg = (url, height) => {\n  if (_environment_js__WEBPACK_IMPORTED_MODULE_4__.isBrowser) {\n    console.log(\n      '%c                      ',\n      `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})`\n    )\n    // console.log('%c                ', `font-size: ${height}x; background: url(${url}) no-repeat;`)\n  }\n  vconsoles.forEach((vc) => vc.printImg(url, height))\n}\n/* c8 ignore stop */\n\n/**\n * @param {string} base64\n * @param {number} height\n */\n/* c8 ignore next 2 */\nconst printImgBase64 = (base64, height) =>\n  printImg(`data:image/gif;base64,${base64}`, height)\n\n/**\n * @param {Array<string|Symbol|Object|number>} args\n */\nconst group = (...args) => {\n  console.group(...computeLoggingArgs(args))\n  /* c8 ignore next */\n  vconsoles.forEach((vc) => vc.group(args))\n}\n\n/**\n * @param {Array<string|Symbol|Object|number>} args\n */\nconst groupCollapsed = (...args) => {\n  console.groupCollapsed(...computeLoggingArgs(args))\n  /* c8 ignore next */\n  vconsoles.forEach((vc) => vc.groupCollapsed(args))\n}\n\nconst groupEnd = () => {\n  console.groupEnd()\n  /* c8 ignore next */\n  vconsoles.forEach((vc) => vc.groupEnd())\n}\n\n/**\n * @param {function():Node} createNode\n */\n/* c8 ignore next 2 */\nconst printDom = (createNode) =>\n  vconsoles.forEach((vc) => vc.printDom(createNode()))\n\n/**\n * @param {HTMLCanvasElement} canvas\n * @param {number} height\n */\n/* c8 ignore next 2 */\nconst printCanvas = (canvas, height) =>\n  printImg(canvas.toDataURL(), height)\n\nconst vconsoles = _set_js__WEBPACK_IMPORTED_MODULE_5__.create()\n\n/**\n * @param {Array<string|Symbol|Object|number>} args\n * @return {Array<Element>}\n */\n/* c8 ignore start */\nconst _computeLineSpans = (args) => {\n  const spans = []\n  const currentStyle = new Map()\n  // try with formatting until we find something unsupported\n  let i = 0\n  for (; i < args.length; i++) {\n    const arg = args[i]\n    // @ts-ignore\n    const style = _browserStyleMap[arg]\n    if (style !== undefined) {\n      currentStyle.set(style.left, style.right)\n    } else {\n      if (arg.constructor === String || arg.constructor === Number) {\n        // @ts-ignore\n        const span = _dom_js__WEBPACK_IMPORTED_MODULE_3__.element('span', [\n          _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('style', _dom_js__WEBPACK_IMPORTED_MODULE_3__.mapToStyleString(currentStyle))\n        ], [_dom_js__WEBPACK_IMPORTED_MODULE_3__.text(arg.toString())])\n        if (span.innerHTML === '') {\n          span.innerHTML = '&nbsp;'\n        }\n        spans.push(span)\n      } else {\n        break\n      }\n    }\n  }\n  // append the rest\n  for (; i < args.length; i++) {\n    let content = args[i]\n    if (!(content instanceof Symbol)) {\n      if (content.constructor !== String && content.constructor !== Number) {\n        content = ' ' + _json_js__WEBPACK_IMPORTED_MODULE_6__.stringify(content) + ' '\n      }\n      spans.push(\n        _dom_js__WEBPACK_IMPORTED_MODULE_3__.element('span', [], [_dom_js__WEBPACK_IMPORTED_MODULE_3__.text(/** @type {string} */ (content))])\n      )\n    }\n  }\n  return spans\n}\n/* c8 ignore stop */\n\nconst lineStyle =\n  'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;'\n\n/* c8 ignore start */\nclass VConsole {\n  /**\n   * @param {Element} dom\n   */\n  constructor (dom) {\n    this.dom = dom\n    /**\n     * @type {Element}\n     */\n    this.ccontainer = this.dom\n    this.depth = 0\n    vconsoles.add(this)\n  }\n\n  /**\n   * @param {Array<string|Symbol|Object|number>} args\n   * @param {boolean} collapsed\n   */\n  group (args, collapsed = false) {\n    _eventloop_js__WEBPACK_IMPORTED_MODULE_7__.enqueue(() => {\n      const triangleDown = _dom_js__WEBPACK_IMPORTED_MODULE_3__.element('span', [\n        _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('hidden', collapsed),\n        _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('style', 'color:grey;font-size:120%;')\n      ], [_dom_js__WEBPACK_IMPORTED_MODULE_3__.text('▼')])\n      const triangleRight = _dom_js__WEBPACK_IMPORTED_MODULE_3__.element('span', [\n        _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('hidden', !collapsed),\n        _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('style', 'color:grey;font-size:125%;')\n      ], [_dom_js__WEBPACK_IMPORTED_MODULE_3__.text('▶')])\n      const content = _dom_js__WEBPACK_IMPORTED_MODULE_3__.element(\n        'div',\n        [_pair_js__WEBPACK_IMPORTED_MODULE_1__.create(\n          'style',\n          `${lineStyle};padding-left:${this.depth * 10}px`\n        )],\n        [triangleDown, triangleRight, _dom_js__WEBPACK_IMPORTED_MODULE_3__.text(' ')].concat(\n          _computeLineSpans(args)\n        )\n      )\n      const nextContainer = _dom_js__WEBPACK_IMPORTED_MODULE_3__.element('div', [\n        _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('hidden', collapsed)\n      ])\n      const nextLine = _dom_js__WEBPACK_IMPORTED_MODULE_3__.element('div', [], [content, nextContainer])\n      _dom_js__WEBPACK_IMPORTED_MODULE_3__.append(this.ccontainer, [nextLine])\n      this.ccontainer = nextContainer\n      this.depth++\n      // when header is clicked, collapse/uncollapse container\n      _dom_js__WEBPACK_IMPORTED_MODULE_3__.addEventListener(content, 'click', (_event) => {\n        nextContainer.toggleAttribute('hidden')\n        triangleDown.toggleAttribute('hidden')\n        triangleRight.toggleAttribute('hidden')\n      })\n    })\n  }\n\n  /**\n   * @param {Array<string|Symbol|Object|number>} args\n   */\n  groupCollapsed (args) {\n    this.group(args, true)\n  }\n\n  groupEnd () {\n    _eventloop_js__WEBPACK_IMPORTED_MODULE_7__.enqueue(() => {\n      if (this.depth > 0) {\n        this.depth--\n        // @ts-ignore\n        this.ccontainer = this.ccontainer.parentElement.parentElement\n      }\n    })\n  }\n\n  /**\n   * @param {Array<string|Symbol|Object|number>} args\n   */\n  print (args) {\n    _eventloop_js__WEBPACK_IMPORTED_MODULE_7__.enqueue(() => {\n      _dom_js__WEBPACK_IMPORTED_MODULE_3__.append(this.ccontainer, [\n        _dom_js__WEBPACK_IMPORTED_MODULE_3__.element('div', [\n          _pair_js__WEBPACK_IMPORTED_MODULE_1__.create(\n            'style',\n            `${lineStyle};padding-left:${this.depth * 10}px`\n          )\n        ], _computeLineSpans(args))\n      ])\n    })\n  }\n\n  /**\n   * @param {Error} err\n   */\n  printError (err) {\n    this.print([_logging_common_js__WEBPACK_IMPORTED_MODULE_0__.RED, _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.BOLD, err.toString()])\n  }\n\n  /**\n   * @param {string} url\n   * @param {number} height\n   */\n  printImg (url, height) {\n    _eventloop_js__WEBPACK_IMPORTED_MODULE_7__.enqueue(() => {\n      _dom_js__WEBPACK_IMPORTED_MODULE_3__.append(this.ccontainer, [\n        _dom_js__WEBPACK_IMPORTED_MODULE_3__.element('img', [\n          _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('src', url),\n          _pair_js__WEBPACK_IMPORTED_MODULE_1__.create('height', `${_math_js__WEBPACK_IMPORTED_MODULE_8__.round(height * 1.5)}px`)\n        ])\n      ])\n    })\n  }\n\n  /**\n   * @param {Node} node\n   */\n  printDom (node) {\n    _eventloop_js__WEBPACK_IMPORTED_MODULE_7__.enqueue(() => {\n      _dom_js__WEBPACK_IMPORTED_MODULE_3__.append(this.ccontainer, [node])\n    })\n  }\n\n  destroy () {\n    _eventloop_js__WEBPACK_IMPORTED_MODULE_7__.enqueue(() => {\n      vconsoles.delete(this)\n    })\n  }\n}\n/* c8 ignore stop */\n\n/**\n * @param {Element} dom\n */\n/* c8 ignore next */\nconst createVConsole = (dom) => new VConsole(dom)\n\n/**\n * @param {string} moduleName\n * @return {function(...any):void}\n */\nconst createModuleLogger = (moduleName) => _logging_common_js__WEBPACK_IMPORTED_MODULE_0__.createModuleLogger(print, moduleName)\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/logging.js?");

/***/ }),

/***/ "../node_modules/lib0/pair.js":
/*!************************************!*\
  !*** ../node_modules/lib0/pair.js ***!
  \************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   Pair: () => (/* binding */ Pair),\n/* harmony export */   create: () => (/* binding */ create),\n/* harmony export */   createReversed: () => (/* binding */ createReversed),\n/* harmony export */   forEach: () => (/* binding */ forEach),\n/* harmony export */   map: () => (/* binding */ map)\n/* harmony export */ });\n/**\n * Working with value pairs.\n *\n * @module pair\n */\n\n/**\n * @template L,R\n */\nclass Pair {\n  /**\n   * @param {L} left\n   * @param {R} right\n   */\n  constructor (left, right) {\n    this.left = left\n    this.right = right\n  }\n}\n\n/**\n * @template L,R\n * @param {L} left\n * @param {R} right\n * @return {Pair<L,R>}\n */\nconst create = (left, right) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {R} right\n * @param {L} left\n * @return {Pair<L,R>}\n */\nconst createReversed = (right, left) => new Pair(left, right)\n\n/**\n * @template L,R\n * @param {Array<Pair<L,R>>} arr\n * @param {function(L, R):any} f\n */\nconst forEach = (arr, f) => arr.forEach(p => f(p.left, p.right))\n\n/**\n * @template L,R,X\n * @param {Array<Pair<L,R>>} arr\n * @param {function(L, R):X} f\n * @return {Array<X>}\n */\nconst map = (arr, f) => arr.map(p => f(p.left, p.right))\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/pair.js?");

/***/ }),

/***/ "../node_modules/lib0/promise.js":
/*!***************************************!*\
  !*** ../node_modules/lib0/promise.js ***!
  \***************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   all: () => (/* binding */ all),\n/* harmony export */   create: () => (/* binding */ create),\n/* harmony export */   createEmpty: () => (/* binding */ createEmpty),\n/* harmony export */   isPromise: () => (/* binding */ isPromise),\n/* harmony export */   reject: () => (/* binding */ reject),\n/* harmony export */   resolve: () => (/* binding */ resolve),\n/* harmony export */   resolveWith: () => (/* binding */ resolveWith),\n/* harmony export */   until: () => (/* binding */ until),\n/* harmony export */   wait: () => (/* binding */ wait)\n/* harmony export */ });\n/* harmony import */ var _time_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./time.js */ \"../node_modules/lib0/time.js\");\n/**\n * Utility helpers to work with promises.\n *\n * @module promise\n */\n\n\n\n/**\n * @template T\n * @callback PromiseResolve\n * @param {T|PromiseLike<T>} [result]\n */\n\n/**\n * @template T\n * @param {function(PromiseResolve<T>,function(Error):void):any} f\n * @return {Promise<T>}\n */\nconst create = f => /** @type {Promise<T>} */ (new Promise(f))\n\n/**\n * @param {function(function():void,function(Error):void):void} f\n * @return {Promise<void>}\n */\nconst createEmpty = f => new Promise(f)\n\n/**\n * `Promise.all` wait for all promises in the array to resolve and return the result\n * @template {unknown[] | []} PS\n *\n * @param {PS} ps\n * @return {Promise<{ -readonly [P in keyof PS]: Awaited<PS[P]> }>}\n */\nconst all = Promise.all.bind(Promise)\n\n/**\n * @param {Error} [reason]\n * @return {Promise<never>}\n */\nconst reject = reason => Promise.reject(reason)\n\n/**\n * @template T\n * @param {T|void} res\n * @return {Promise<T|void>}\n */\nconst resolve = res => Promise.resolve(res)\n\n/**\n * @template T\n * @param {T} res\n * @return {Promise<T>}\n */\nconst resolveWith = res => Promise.resolve(res)\n\n/**\n * @todo Next version, reorder parameters: check, [timeout, [intervalResolution]]\n *\n * @param {number} timeout\n * @param {function():boolean} check\n * @param {number} [intervalResolution]\n * @return {Promise<void>}\n */\nconst until = (timeout, check, intervalResolution = 10) => create((resolve, reject) => {\n  const startTime = _time_js__WEBPACK_IMPORTED_MODULE_0__.getUnixTime()\n  const hasTimeout = timeout > 0\n  const untilInterval = () => {\n    if (check()) {\n      clearInterval(intervalHandle)\n      resolve()\n    } else if (hasTimeout) {\n      /* c8 ignore else */\n      if (_time_js__WEBPACK_IMPORTED_MODULE_0__.getUnixTime() - startTime > timeout) {\n        clearInterval(intervalHandle)\n        reject(new Error('Timeout'))\n      }\n    }\n  }\n  const intervalHandle = setInterval(untilInterval, intervalResolution)\n})\n\n/**\n * @param {number} timeout\n * @return {Promise<undefined>}\n */\nconst wait = timeout => create((resolve, reject) => setTimeout(resolve, timeout))\n\n/**\n * Checks if an object is a promise using ducktyping.\n *\n * Promises are often polyfilled, so it makes sense to add some additional guarantees if the user of this\n * library has some insane environment where global Promise objects are overwritten.\n *\n * @param {any} p\n * @return {boolean}\n */\nconst isPromise = p => p instanceof Promise || (p && p.then && p.catch && p.finally)\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/promise.js?");

/***/ }),

/***/ "../node_modules/lib0/random.js":
/*!**************************************!*\
  !*** ../node_modules/lib0/random.js ***!
  \**************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   oneOf: () => (/* binding */ oneOf),\n/* harmony export */   rand: () => (/* binding */ rand),\n/* harmony export */   uint32: () => (/* binding */ uint32),\n/* harmony export */   uint53: () => (/* binding */ uint53),\n/* harmony export */   uuidv4: () => (/* binding */ uuidv4)\n/* harmony export */ });\n/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./math.js */ \"../node_modules/lib0/math.js\");\n/* harmony import */ var _binary_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./binary.js */ \"../node_modules/lib0/binary.js\");\n/* harmony import */ var lib0_webcrypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lib0/webcrypto */ \"../node_modules/lib0/webcrypto.js\");\n/**\n * Isomorphic module for true random numbers / buffers / uuids.\n *\n * Attention: falls back to Math.random if the browser does not support crypto.\n *\n * @module random\n */\n\n\n\n\n\nconst rand = Math.random\n\nconst uint32 = () => (0,lib0_webcrypto__WEBPACK_IMPORTED_MODULE_0__.getRandomValues)(new Uint32Array(1))[0]\n\nconst uint53 = () => {\n  const arr = (0,lib0_webcrypto__WEBPACK_IMPORTED_MODULE_0__.getRandomValues)(new Uint32Array(8))\n  return (arr[0] & _binary_js__WEBPACK_IMPORTED_MODULE_1__.BITS21) * (_binary_js__WEBPACK_IMPORTED_MODULE_1__.BITS32 + 1) + (arr[1] >>> 0)\n}\n\n/**\n * @template T\n * @param {Array<T>} arr\n * @return {T}\n */\nconst oneOf = arr => arr[_math_js__WEBPACK_IMPORTED_MODULE_2__.floor(rand() * arr.length)]\n\n// @ts-ignore\nconst uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11\n\n/**\n * @return {string}\n */\nconst uuidv4 = () => uuidv4Template.replace(/[018]/g, /** @param {number} c */ c =>\n  (c ^ uint32() & 15 >> c / 4).toString(16)\n)\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/random.js?");

/***/ }),

/***/ "../node_modules/lib0/symbol.js":
/*!**************************************!*\
  !*** ../node_modules/lib0/symbol.js ***!
  \**************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   create: () => (/* binding */ create),\n/* harmony export */   isSymbol: () => (/* binding */ isSymbol)\n/* harmony export */ });\n/**\n * Utility module to work with EcmaScript Symbols.\n *\n * @module symbol\n */\n\n/**\n * Return fresh symbol.\n *\n * @return {Symbol}\n */\nconst create = Symbol\n\n/**\n * @param {any} s\n * @return {boolean}\n */\nconst isSymbol = s => typeof s === 'symbol'\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/symbol.js?");

/***/ }),

/***/ "../node_modules/lib0/webcrypto.js":
/*!*****************************************!*\
  !*** ../node_modules/lib0/webcrypto.js ***!
  \*****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   getRandomValues: () => (/* binding */ getRandomValues),\n/* harmony export */   subtle: () => (/* binding */ subtle)\n/* harmony export */ });\n/* eslint-env browser */\n\nconst subtle = crypto.subtle\nconst getRandomValues = crypto.getRandomValues.bind(crypto)\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/lib0/webcrypto.js?");

/***/ }),

/***/ "../node_modules/yjs/dist/yjs.mjs":
/*!****************************************!*\
  !*** ../node_modules/yjs/dist/yjs.mjs ***!
  \****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   AbsolutePosition: () => (/* binding */ AbsolutePosition),\n/* harmony export */   AbstractConnector: () => (/* binding */ AbstractConnector),\n/* harmony export */   AbstractStruct: () => (/* binding */ AbstractStruct),\n/* harmony export */   AbstractType: () => (/* binding */ AbstractType),\n/* harmony export */   Array: () => (/* binding */ YArray),\n/* harmony export */   ContentAny: () => (/* binding */ ContentAny),\n/* harmony export */   ContentBinary: () => (/* binding */ ContentBinary),\n/* harmony export */   ContentDeleted: () => (/* binding */ ContentDeleted),\n/* harmony export */   ContentEmbed: () => (/* binding */ ContentEmbed),\n/* harmony export */   ContentFormat: () => (/* binding */ ContentFormat),\n/* harmony export */   ContentJSON: () => (/* binding */ ContentJSON),\n/* harmony export */   ContentString: () => (/* binding */ ContentString),\n/* harmony export */   ContentType: () => (/* binding */ ContentType),\n/* harmony export */   Doc: () => (/* binding */ Doc),\n/* harmony export */   GC: () => (/* binding */ GC),\n/* harmony export */   ID: () => (/* binding */ ID),\n/* harmony export */   Item: () => (/* binding */ Item),\n/* harmony export */   Map: () => (/* binding */ YMap),\n/* harmony export */   PermanentUserData: () => (/* binding */ PermanentUserData),\n/* harmony export */   RelativePosition: () => (/* binding */ RelativePosition),\n/* harmony export */   Snapshot: () => (/* binding */ Snapshot),\n/* harmony export */   Text: () => (/* binding */ YText),\n/* harmony export */   Transaction: () => (/* binding */ Transaction),\n/* harmony export */   UndoManager: () => (/* binding */ UndoManager),\n/* harmony export */   UpdateEncoderV1: () => (/* binding */ UpdateEncoderV1),\n/* harmony export */   XmlElement: () => (/* binding */ YXmlElement),\n/* harmony export */   XmlFragment: () => (/* binding */ YXmlFragment),\n/* harmony export */   XmlHook: () => (/* binding */ YXmlHook),\n/* harmony export */   XmlText: () => (/* binding */ YXmlText),\n/* harmony export */   YArrayEvent: () => (/* binding */ YArrayEvent),\n/* harmony export */   YEvent: () => (/* binding */ YEvent),\n/* harmony export */   YMapEvent: () => (/* binding */ YMapEvent),\n/* harmony export */   YTextEvent: () => (/* binding */ YTextEvent),\n/* harmony export */   YXmlEvent: () => (/* binding */ YXmlEvent),\n/* harmony export */   applyUpdate: () => (/* binding */ applyUpdate),\n/* harmony export */   applyUpdateV2: () => (/* binding */ applyUpdateV2),\n/* harmony export */   cleanupYTextFormatting: () => (/* binding */ cleanupYTextFormatting),\n/* harmony export */   compareIDs: () => (/* binding */ compareIDs),\n/* harmony export */   compareRelativePositions: () => (/* binding */ compareRelativePositions),\n/* harmony export */   convertUpdateFormatV1ToV2: () => (/* binding */ convertUpdateFormatV1ToV2),\n/* harmony export */   convertUpdateFormatV2ToV1: () => (/* binding */ convertUpdateFormatV2ToV1),\n/* harmony export */   createAbsolutePositionFromRelativePosition: () => (/* binding */ createAbsolutePositionFromRelativePosition),\n/* harmony export */   createDeleteSet: () => (/* binding */ createDeleteSet),\n/* harmony export */   createDeleteSetFromStructStore: () => (/* binding */ createDeleteSetFromStructStore),\n/* harmony export */   createDocFromSnapshot: () => (/* binding */ createDocFromSnapshot),\n/* harmony export */   createID: () => (/* binding */ createID),\n/* harmony export */   createRelativePositionFromJSON: () => (/* binding */ createRelativePositionFromJSON),\n/* harmony export */   createRelativePositionFromTypeIndex: () => (/* binding */ createRelativePositionFromTypeIndex),\n/* harmony export */   createSnapshot: () => (/* binding */ createSnapshot),\n/* harmony export */   decodeRelativePosition: () => (/* binding */ decodeRelativePosition),\n/* harmony export */   decodeSnapshot: () => (/* binding */ decodeSnapshot),\n/* harmony export */   decodeSnapshotV2: () => (/* binding */ decodeSnapshotV2),\n/* harmony export */   decodeStateVector: () => (/* binding */ decodeStateVector),\n/* harmony export */   decodeUpdate: () => (/* binding */ decodeUpdate),\n/* harmony export */   decodeUpdateV2: () => (/* binding */ decodeUpdateV2),\n/* harmony export */   diffUpdate: () => (/* binding */ diffUpdate),\n/* harmony export */   diffUpdateV2: () => (/* binding */ diffUpdateV2),\n/* harmony export */   emptySnapshot: () => (/* binding */ emptySnapshot),\n/* harmony export */   encodeRelativePosition: () => (/* binding */ encodeRelativePosition),\n/* harmony export */   encodeSnapshot: () => (/* binding */ encodeSnapshot),\n/* harmony export */   encodeSnapshotV2: () => (/* binding */ encodeSnapshotV2),\n/* harmony export */   encodeStateAsUpdate: () => (/* binding */ encodeStateAsUpdate),\n/* harmony export */   encodeStateAsUpdateV2: () => (/* binding */ encodeStateAsUpdateV2),\n/* harmony export */   encodeStateVector: () => (/* binding */ encodeStateVector),\n/* harmony export */   encodeStateVectorFromUpdate: () => (/* binding */ encodeStateVectorFromUpdate),\n/* harmony export */   encodeStateVectorFromUpdateV2: () => (/* binding */ encodeStateVectorFromUpdateV2),\n/* harmony export */   equalDeleteSets: () => (/* binding */ equalDeleteSets),\n/* harmony export */   equalSnapshots: () => (/* binding */ equalSnapshots),\n/* harmony export */   findIndexSS: () => (/* binding */ findIndexSS),\n/* harmony export */   findRootTypeKey: () => (/* binding */ findRootTypeKey),\n/* harmony export */   getItem: () => (/* binding */ getItem),\n/* harmony export */   getState: () => (/* binding */ getState),\n/* harmony export */   getTypeChildren: () => (/* binding */ getTypeChildren),\n/* harmony export */   isDeleted: () => (/* binding */ isDeleted),\n/* harmony export */   isParentOf: () => (/* binding */ isParentOf),\n/* harmony export */   iterateDeletedStructs: () => (/* binding */ iterateDeletedStructs),\n/* harmony export */   logType: () => (/* binding */ logType),\n/* harmony export */   logUpdate: () => (/* binding */ logUpdate),\n/* harmony export */   logUpdateV2: () => (/* binding */ logUpdateV2),\n/* harmony export */   mergeUpdates: () => (/* binding */ mergeUpdates),\n/* harmony export */   mergeUpdatesV2: () => (/* binding */ mergeUpdatesV2),\n/* harmony export */   obfuscateUpdate: () => (/* binding */ obfuscateUpdate),\n/* harmony export */   obfuscateUpdateV2: () => (/* binding */ obfuscateUpdateV2),\n/* harmony export */   parseUpdateMeta: () => (/* binding */ parseUpdateMeta),\n/* harmony export */   parseUpdateMetaV2: () => (/* binding */ parseUpdateMetaV2),\n/* harmony export */   readUpdate: () => (/* binding */ readUpdate),\n/* harmony export */   readUpdateV2: () => (/* binding */ readUpdateV2),\n/* harmony export */   relativePositionToJSON: () => (/* binding */ relativePositionToJSON),\n/* harmony export */   snapshot: () => (/* binding */ snapshot),\n/* harmony export */   snapshotContainsUpdate: () => (/* binding */ snapshotContainsUpdate),\n/* harmony export */   transact: () => (/* binding */ transact),\n/* harmony export */   tryGc: () => (/* binding */ tryGc),\n/* harmony export */   typeListToArraySnapshot: () => (/* binding */ typeListToArraySnapshot),\n/* harmony export */   typeMapGetSnapshot: () => (/* binding */ typeMapGetSnapshot)\n/* harmony export */ });\n/* harmony import */ var lib0_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lib0/observable */ \"../node_modules/lib0/observable.js\");\n/* harmony import */ var lib0_array__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lib0/array */ \"../node_modules/lib0/array.js\");\n/* harmony import */ var lib0_math__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lib0/math */ \"../node_modules/lib0/math.js\");\n/* harmony import */ var lib0_map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lib0/map */ \"../node_modules/lib0/map.js\");\n/* harmony import */ var lib0_encoding__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lib0/encoding */ \"../node_modules/lib0/encoding.js\");\n/* harmony import */ var lib0_decoding__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! lib0/decoding */ \"../node_modules/lib0/decoding.js\");\n/* harmony import */ var lib0_random__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! lib0/random */ \"../node_modules/lib0/random.js\");\n/* harmony import */ var lib0_promise__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lib0/promise */ \"../node_modules/lib0/promise.js\");\n/* harmony import */ var lib0_buffer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! lib0/buffer */ \"../node_modules/lib0/buffer.js\");\n/* harmony import */ var lib0_error__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! lib0/error */ \"../node_modules/lib0/error.js\");\n/* harmony import */ var lib0_binary__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! lib0/binary */ \"../node_modules/lib0/binary.js\");\n/* harmony import */ var lib0_function__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! lib0/function */ \"../node_modules/lib0/function.js\");\n/* harmony import */ var lib0_set__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! lib0/set */ \"../node_modules/lib0/set.js\");\n/* harmony import */ var lib0_logging__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! lib0/logging */ \"../node_modules/lib0/logging.js\");\n/* harmony import */ var lib0_logging__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! lib0/logging */ \"../node_modules/lib0/logging.common.js\");\n/* harmony import */ var lib0_time__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! lib0/time */ \"../node_modules/lib0/time.js\");\n/* harmony import */ var lib0_string__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! lib0/string */ \"../node_modules/lib0/string.js\");\n/* harmony import */ var lib0_iterator__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! lib0/iterator */ \"../node_modules/lib0/iterator.js\");\n/* harmony import */ var lib0_object__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! lib0/object */ \"../node_modules/lib0/object.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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 {Observable<any>}\n */\nclass AbstractConnector extends lib0_observable__WEBPACK_IMPORTED_MODULE_0__.Observable {\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<number,Array<DeleteItem>>}\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<GC|Item>} */ (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<DeleteItem>} 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 = lib0_math__WEBPACK_IMPORTED_MODULE_1__.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 = lib0_math__WEBPACK_IMPORTED_MODULE_1__.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<DeleteSet>} 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<DeleteItem>}\n         */\n        const dels = delsLeft.slice();\n        for (let i = dssI + 1; i < dss.length; i++) {\n          lib0_array__WEBPACK_IMPORTED_MODULE_2__.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  lib0_map__WEBPACK_IMPORTED_MODULE_3__.setIfUndefined(ds.clients, client, () => /** @type {Array<DeleteItem>} */ ([])).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<DeleteItem>}\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  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder.restEncoder, ds.clients.size);\n\n  // Ensure that the delete set is written in a deterministic order\n  lib0_array__WEBPACK_IMPORTED_MODULE_2__.from(ds.clients.entries())\n    .sort((a, b) => b[0] - a[0])\n    .forEach(([client, dsitems]) => {\n      encoder.resetDsCurVal();\n      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder.restEncoder, client);\n      const len = dsitems.length;\n      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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 = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n  for (let i = 0; i < numClients; i++) {\n    decoder.resetDsCurVal();\n    const client = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n    const numberOfDeletes = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n    if (numberOfDeletes > 0) {\n      const dsField = lib0_map__WEBPACK_IMPORTED_MODULE_3__.setIfUndefined(ds.clients, client, () => /** @type {Array<DeleteItem>} */ ([]));\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 = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n  for (let i = 0; i < numClients; i++) {\n    decoder.resetDsCurVal();\n    const client = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n    const numberOfDeletes = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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<import('../internals.js').DeleteItem>} */ (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\nconst generateNewClientId = lib0_random__WEBPACK_IMPORTED_MODULE_6__.uint32;\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 * A Yjs instance handles the state of shared data.\n * @extends Observable<string>\n */\nclass Doc extends lib0_observable__WEBPACK_IMPORTED_MODULE_0__.Observable {\n  /**\n   * @param {DocOpts} opts configuration\n   */\n  constructor ({ guid = lib0_random__WEBPACK_IMPORTED_MODULE_6__.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<string, AbstractType<YEvent<any>>>}\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<Transaction>}\n     */\n    this._transactionCleanups = [];\n    /**\n     * @type {Set<Doc>}\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 = lib0_promise__WEBPACK_IMPORTED_MODULE_7__.create(resolve => {\n      this.on('load', () => {\n        this.isLoaded = true;\n        resolve(this);\n      });\n    });\n    const provideSyncedPromise = () => lib0_promise__WEBPACK_IMPORTED_MODULE_7__.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.isLoaded) {\n        this.emit('load', []);\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(lib0_array__WEBPACK_IMPORTED_MODULE_2__.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 `y.get(name, TypeConstructor)` yield the same result\n   * and do not overwrite each other. I.e.\n   * `y.define(name, Y.Array) === y.define(name, Y.Array)`\n   *\n   * After this method is called, the type is also available on `y.share.get(name)`.\n   *\n   * *Best Practices:*\n   * Define all types right after the Yjs instance is created and store them in a separate object.\n   * Also use the typed methods `getText(name)`, `getArray(name)`, ..\n   *\n   * @example\n   *   const y = new Y(..)\n   *   const appState = {\n   *     document: y.getText('document')\n   *     comments: y.getArray('comments')\n   *   }\n   *\n   * @param {string} name\n   * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...\n   * @return {AbstractType<any>} The created type. Constructed with TypeConstructor\n   *\n   * @public\n   */\n  get (name, TypeConstructor = AbstractType) {\n    const type = lib0_map__WEBPACK_IMPORTED_MODULE_3__.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 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\n  }\n\n  /**\n   * @template T\n   * @param {string} [name]\n   * @return {YArray<T>}\n   *\n   * @public\n   */\n  getArray (name = '') {\n    // @ts-ignore\n    return this.get(name, YArray)\n  }\n\n  /**\n   * @param {string} [name]\n   * @return {YText}\n   *\n   * @public\n   */\n  getText (name = '') {\n    // @ts-ignore\n    return this.get(name, YText)\n  }\n\n  /**\n   * @template T\n   * @param {string} [name]\n   * @return {YMap<T>}\n   *\n   * @public\n   */\n  getMap (name = '') {\n    // @ts-ignore\n    return this.get(name, YMap)\n  }\n\n  /**\n   * @param {string} [name]\n   * @return {YXmlFragment}\n   *\n   * @public\n   */\n  getXmlFragment (name = '') {\n    // @ts-ignore\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<string, any>}\n   */\n  toJSON () {\n    /**\n     * @type {Object<string, any>}\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    lib0_array__WEBPACK_IMPORTED_MODULE_2__.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    this.emit('destroyed', [true]);\n    this.emit('destroy', [this]);\n    super.destroy();\n  }\n\n  /**\n   * @param {string} eventName\n   * @param {function(...any):any} f\n   */\n  on (eventName, f) {\n    super.on(eventName, f);\n  }\n\n  /**\n   * @param {string} eventName\n   * @param {function} f\n   */\n  off (eventName, f) {\n    super.off(eventName, f);\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 lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(this.restDecoder)\n  }\n\n  /**\n   * @return {number}\n   */\n  readDsLen () {\n    return lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(this.restDecoder)\n  }\n}\n\nclass UpdateDecoderV1 extends DSDecoderV1 {\n  /**\n   * @return {ID}\n   */\n  readLeftID () {\n    return createID(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(this.restDecoder), lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(this.restDecoder))\n  }\n\n  /**\n   * @return {ID}\n   */\n  readRightID () {\n    return createID(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(this.restDecoder), lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(this.restDecoder)\n  }\n\n  /**\n   * @return {number} info An unsigned 8-bit integer\n   */\n  readInfo () {\n    return lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readUint8(this.restDecoder)\n  }\n\n  /**\n   * @return {string}\n   */\n  readString () {\n    return lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarString(this.restDecoder)\n  }\n\n  /**\n   * @return {boolean} isKey\n   */\n  readParentInfo () {\n    return lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(this.restDecoder) === 1\n  }\n\n  /**\n   * @return {number} info An unsigned 8-bit integer\n   */\n  readTypeRef () {\n    return lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(this.restDecoder)\n  }\n\n  /**\n   * @return {any}\n   */\n  readAny () {\n    return lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readAny(this.restDecoder)\n  }\n\n  /**\n   * @return {Uint8Array}\n   */\n  readBuf () {\n    return lib0_buffer__WEBPACK_IMPORTED_MODULE_8__.copyUint8Array(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarString(this.restDecoder))\n  }\n\n  /**\n   * @return {string}\n   */\n  readKey () {\n    return lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 += lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(this.restDecoder);\n    return this.dsCurrVal\n  }\n\n  /**\n   * @return {number}\n   */\n  readDsLen () {\n    const diff = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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<string>}\n     */\n    this.keys = [];\n    lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder); // read feature flag - currently unused\n    this.keyClockDecoder = new lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.IntDiffOptRleDecoder(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint8Array(decoder));\n    this.clientDecoder = new lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.UintOptRleDecoder(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint8Array(decoder));\n    this.leftClockDecoder = new lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.IntDiffOptRleDecoder(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint8Array(decoder));\n    this.rightClockDecoder = new lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.IntDiffOptRleDecoder(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint8Array(decoder));\n    this.infoDecoder = new lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.RleDecoder(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint8Array(decoder), lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readUint8);\n    this.stringDecoder = new lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.StringDecoder(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint8Array(decoder));\n    this.parentInfoDecoder = new lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.RleDecoder(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint8Array(decoder), lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readUint8);\n    this.typeRefDecoder = new lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.UintOptRleDecoder(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint8Array(decoder));\n    this.lenDecoder = new lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.UintOptRleDecoder(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readAny(this.restDecoder)\n  }\n\n  /**\n   * @return {Uint8Array}\n   */\n  readBuf () {\n    return lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder();\n  }\n\n  toUint8Array () {\n    return lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(this.restEncoder)\n  }\n\n  resetDsCurVal () {\n    // nop\n  }\n\n  /**\n   * @param {number} clock\n   */\n  writeDsClock (clock) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(this.restEncoder, clock);\n  }\n\n  /**\n   * @param {number} len\n   */\n  writeDsLen (len) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(this.restEncoder, len);\n  }\n}\n\nclass UpdateEncoderV1 extends DSEncoderV1 {\n  /**\n   * @param {ID} id\n   */\n  writeLeftID (id) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(this.restEncoder, id.client);\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(this.restEncoder, id.clock);\n  }\n\n  /**\n   * @param {ID} id\n   */\n  writeRightID (id) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(this.restEncoder, id.client);\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(this.restEncoder, client);\n  }\n\n  /**\n   * @param {number} info An unsigned 8-bit integer\n   */\n  writeInfo (info) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeUint8(this.restEncoder, info);\n  }\n\n  /**\n   * @param {string} s\n   */\n  writeString (s) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarString(this.restEncoder, s);\n  }\n\n  /**\n   * @param {boolean} isYKey\n   */\n  writeParentInfo (isYKey) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(this.restEncoder, isYKey ? 1 : 0);\n  }\n\n  /**\n   * @param {number} info An unsigned 8-bit integer\n   */\n  writeTypeRef (info) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(this.restEncoder, len);\n  }\n\n  /**\n   * @param {any} any\n   */\n  writeAny (any) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeAny(this.restEncoder, any);\n  }\n\n  /**\n   * @param {Uint8Array} buf\n   */\n  writeBuf (buf) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(this.restEncoder, buf);\n  }\n\n  /**\n   * @param {any} embed\n   */\n  writeJSON (embed) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarString(this.restEncoder, JSON.stringify(embed));\n  }\n\n  /**\n   * @param {string} key\n   */\n  writeKey (key) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarString(this.restEncoder, key);\n  }\n}\n\nclass DSEncoderV2 {\n  constructor () {\n    this.restEncoder = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder(); // encodes all the rest / non-optimized\n    this.dsCurrVal = 0;\n  }\n\n  toUint8Array () {\n    return lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(this.restEncoder, diff);\n  }\n\n  /**\n   * @param {number} len\n   */\n  writeDsLen (len) {\n    if (len === 0) {\n      lib0_error__WEBPACK_IMPORTED_MODULE_9__.unexpectedCase();\n    }\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(this.restEncoder, len - 1);\n    this.dsCurrVal += len;\n  }\n}\n\nclass UpdateEncoderV2 extends DSEncoderV2 {\n  constructor () {\n    super();\n    /**\n     * @type {Map<string,number>}\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 lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.IntDiffOptRleEncoder();\n    this.clientEncoder = new lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.UintOptRleEncoder();\n    this.leftClockEncoder = new lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.IntDiffOptRleEncoder();\n    this.rightClockEncoder = new lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.IntDiffOptRleEncoder();\n    this.infoEncoder = new lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.RleEncoder(lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeUint8);\n    this.stringEncoder = new lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.StringEncoder();\n    this.parentInfoEncoder = new lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.RleEncoder(lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeUint8);\n    this.typeRefEncoder = new lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.UintOptRleEncoder();\n    this.lenEncoder = new lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.UintOptRleEncoder();\n  }\n\n  toUint8Array () {\n    const encoder = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder();\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder, 0); // this is a feature flag that we might use in the future\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array());\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(encoder, this.clientEncoder.toUint8Array());\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array());\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array());\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(encoder, lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(this.infoEncoder));\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(encoder, this.stringEncoder.toUint8Array());\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(encoder, lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(this.parentInfoEncoder));\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array());\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(encoder, this.lenEncoder.toUint8Array());\n    // @note The rest encoder is appended! (note the missing var)\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeUint8Array(encoder, lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(this.restEncoder));\n    return lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeAny(this.restEncoder, any);\n  }\n\n  /**\n   * @param {Uint8Array} buf\n   */\n  writeBuf (buf) {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder\n * @param {Array<GC|Item>} 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 = lib0_math__WEBPACK_IMPORTED_MODULE_1__.max(clock, structs[0].id.clock); // make sure the first id exists\n  const startNewStructs = findIndexSS(structs, clock);\n  // write # encoded structs\n  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder.restEncoder, structs.length - startNewStructs);\n  encoder.writeClient(client);\n  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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<number,number>} _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  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder.restEncoder, sm.size);\n  // Write items with higher client ids first\n  // This heavily improves the conflict algorithm.\n  lib0_array__WEBPACK_IMPORTED_MODULE_2__.from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n    writeStructs(encoder, /** @type {Array<GC|Item>} */ (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<number, { i: number, refs: Array<Item | GC> }>}\n *\n * @private\n * @function\n */\nconst readClientsStructRefs = (decoder, doc) => {\n  /**\n   * @type {Map<number, { i: number, refs: Array<Item | GC> }>}\n   */\n  const clientRefs = lib0_map__WEBPACK_IMPORTED_MODULE_3__.create();\n  const numOfStateUpdates = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n  for (let i = 0; i < numOfStateUpdates; i++) {\n    const numberOfStructs = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n    /**\n     * @type {Array<GC|Item>}\n     */\n    const refs = new Array(numberOfStructs);\n    const client = decoder.readClient();\n    let clock = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 (lib0_binary__WEBPACK_IMPORTED_MODULE_10__.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 = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 & (lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT7 | lib0_binary__WEBPACK_IMPORTED_MODULE_10__.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, // leftd\n            (info & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT8) === lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT8 ? decoder.readLeftID() : null, // origin\n            null, // right\n            (info & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT7) === lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT7 ? decoder.readRightID() : null, // right origin\n            cantCopyParentInfo ? (decoder.readParentInfo() ? doc.get(decoder.readString()) : decoder.readLeftID()) : null, // parent\n            cantCopyParentInfo && (info & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT6) === lib0_binary__WEBPACK_IMPORTED_MODULE_10__.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, // leftd\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<number, { i: number, refs: (GC | Item)[] }>} clientsStructRefs\n * @return { null | { update: Uint8Array, missing: Map<number,number> } }\n *\n * @private\n * @function\n */\nconst integrateStructs = (transaction, store, clientsStructRefs) => {\n  /**\n   * @type {Array<Item | GC>}\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 = lib0_array__WEBPACK_IMPORTED_MODULE_2__.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<GC|Item>}} */ (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<GC|Item>}} */ (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 && stack.length === 0) {\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 = lib0_map__WEBPACK_IMPORTED_MODULE_3__.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<GC|Item>, 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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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 an 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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.createDecoder(store.pendingDs));\n      lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 an 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 = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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<number,number>} [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<number,number>} 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 = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n  for (let i = 0; i < ssLength; i++) {\n    const client = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n    const clock = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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<number,number>} 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<number,number>} Maps `client` to the number next expected `clock` from that client.\n *\n * @function\n */\nconst decodeStateVector = decodedState => readStateVector(new DSDecoderV1(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.createDecoder(decodedState)));\n\n/**\n * @param {DSEncoderV1 | DSEncoderV2} encoder\n * @param {Map<number,number>} sv\n * @function\n */\nconst writeStateVector = (encoder, sv) => {\n  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder.restEncoder, sv.size);\n  lib0_array__WEBPACK_IMPORTED_MODULE_2__.from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder.restEncoder, client); // @todo use a special client decoder that is based on mapping\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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<number,number>} 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<number,number>} 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<function(ARG0, ARG1):void>}\n     */\n    this.l = [];\n  }\n}\n\n/**\n * @template ARG0,ARG1\n * @returns {EventHandler<ARG0,ARG1>}\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<ARG0,ARG1>} 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<ARG0,ARG1>} 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<ARG0,ARG1>} eventHandler\n * @param {ARG0} arg0\n * @param {ARG1} arg1\n *\n * @private\n * @function\n */\nconst callEventHandlerListeners = (eventHandler, arg0, arg1) =>\n  lib0_function__WEBPACK_IMPORTED_MODULE_11__.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  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder, id.client);\n  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder), lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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<any>} 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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.unexpectedCase()\n};\n\n/**\n * Check if `parent` is a parent of `child`.\n *\n * @param {AbstractType<any>} 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<any>} */ (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<any>} 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<any>} [storeType]\n   */\n  constructor (doc, storeType = doc.getMap('users')) {\n    /**\n     * @type {Map<string,DeleteSet>}\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<number,string>}\n     */\n    this.clients = new Map();\n    this.dss = dss;\n    /**\n     * @param {YMap<any>} user\n     * @param {string} userDescription\n     */\n    const initUser = (user, userDescription) => {\n      /**\n       * @type {YArray<Uint8Array>}\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<any>} 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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.createDecoder(encodedDs)))]));\n            }\n          });\n        });\n      });\n      this.dss.set(userDescription, mergeDeleteSets(ds.map(encodedDs => readDeleteSet(new DSDecoderV1(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.createDecoder(encodedDs))))));\n      ids.observe(/** @param {YArrayEvent<any>} 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<any>} type\n   * @param {number} index\n   * @param {number} [assoc]\n   */\n  constructor (type, index, assoc = 0) {\n    /**\n     * @type {AbstractType<any>}\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<any>} 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<any>} 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<any>} 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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeUint8(encoder, 1);\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeUint8(encoder, 2);\n    writeID(encoder, type);\n  } else {\n    throw lib0_error__WEBPACK_IMPORTED_MODULE_9__.unexpectedCase()\n  }\n  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarInt(encoder, assoc);\n  return encoder\n};\n\n/**\n * @param {RelativePosition} rpos\n * @return {Uint8Array}\n */\nconst encodeRelativePosition = rpos => {\n  const encoder = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder();\n  writeRelativePosition(encoder, rpos);\n  return lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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 (lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.hasContent(decoder) ? lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.createDecoder(uint8Array));\n\n/**\n * @param {RelativePosition} rpos\n * @param {Doc} doc\n * @return {AbsolutePosition|null}\n *\n * @function\n */\nconst createAbsolutePositionFromRelativePosition = (rpos, doc) => {\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 = followRedone(store, rightID);\n    const right = res.item;\n    if (!(right instanceof Item)) {\n      return null\n    }\n    type = /** @type {AbstractType<any>} */ (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 } = followRedone(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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<number,number>} sv state map\n   */\n  constructor (ds, sv) {\n    /**\n     * @type {DeleteSet}\n     */\n    this.ds = ds;\n    /**\n     * State Map\n     * @type {Map<number,number>}\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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.createDecoder(buf)));\n\n/**\n * @param {DeleteSet} ds\n * @param {Map<number,number>} 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 = lib0_map__WEBPACK_IMPORTED_MODULE_3__.setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, lib0_set__WEBPACK_IMPORTED_MODULE_12__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder.restEncoder, lastStructIndex + 1);\n      encoder.writeClient(client);\n      // first clock written is 0\n      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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<number,Array<GC|Item>>}\n     */\n    this.clients = new Map();\n    /**\n     * @type {null | { missing: Map<number, number>, 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<client,clock>.\n * Note that clock refers to the next expected clock id.\n *\n * @param {StructStore} store\n * @return {Map<number,number>}\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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.unexpectedCase()\n    }\n  }\n  structs.push(struct);\n};\n\n/**\n * Perform a binary search on a sorted array\n * @param {Array<Item|GC>} 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 = lib0_math__WEBPACK_IMPORTED_MODULE_1__.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 = lib0_math__WEBPACK_IMPORTED_MODULE_1__.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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<GC|Item>}\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<Item|GC>} 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<Item>} */ (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<Item>}\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<GC|Item>} */ (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<Item|GC>} 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 map = y.define('map', YMap)\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 * y.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<Number,Number>}\n     */\n    this.beforeState = getStateVector(doc.store);\n    /**\n     * Holds the state after the transaction.\n     * @type {Map<Number,Number>}\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<AbstractType<YEvent<any>>,Set<String|null>>}\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<AbstractType<YEvent<any>>,Array<YEvent<any>>>}\n     */\n    this.changedParentTypes = new Map();\n    /**\n     * @type {Array<AbstractStruct>}\n     */\n    this._mergeStructs = [];\n    /**\n     * @type {any}\n     */\n    this.origin = origin;\n    /**\n     * Stores meta information on the transaction\n     * @type {Map<any,any>}\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<Doc>}\n     */\n    this.subdocsAdded = new Set();\n    /**\n     * @type {Set<Doc>}\n     */\n    this.subdocsRemoved = new Set();\n    /**\n     * @type {Set<Doc>}\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 && !lib0_map__WEBPACK_IMPORTED_MODULE_3__.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<YEvent<any>>} 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    lib0_map__WEBPACK_IMPORTED_MODULE_3__.setIfUndefined(transaction.changed, type, lib0_set__WEBPACK_IMPORTED_MODULE_12__.create).add(parentSub);\n  }\n};\n\n/**\n * @param {Array<AbstractStruct>} 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<any>} */ (right.parent)._map.get(right.parentSub) === right) {\n          /** @type {AbstractType<any>} */ (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<GC|Item>} */ (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 efficiecy and so we don't miss any merge targets\n  ds.clients.forEach((deleteItems, client) => {\n    const structs = /** @type {Array<GC|Item>} */ (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 = lib0_math__WEBPACK_IMPORTED_MODULE_1__.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<Transaction>} 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<function():void>}\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      (0,lib0_function__WEBPACK_IMPORTED_MODULE_11__.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<GC|Item>} */ (store.clients.get(client));\n          // we iterate from right to left so we can safely remove entries\n          const firstChangePos = lib0_math__WEBPACK_IMPORTED_MODULE_1__.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<GC|Item>} */ (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        lib0_logging__WEBPACK_IMPORTED_MODULE_13__.print(lib0_logging__WEBPACK_IMPORTED_MODULE_14__.ORANGE, lib0_logging__WEBPACK_IMPORTED_MODULE_14__.BOLD, '[yjs] ', lib0_logging__WEBPACK_IMPORTED_MODULE_14__.UNBOLD, lib0_logging__WEBPACK_IMPORTED_MODULE_14__.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<StackItem>} stack\n * @param {string} eventType\n * @return {StackItem?}\n */\nconst popStackItem = (undoManager, stack, eventType) => {\n  /**\n   * Whether a change happened\n   * @type {StackItem?}\n   */\n  let result = null;\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 && result === null) {\n      const store = doc.store;\n      const stackItem = /** @type {StackItem} */ (stack.pop());\n      /**\n       * @type {Set<Item>}\n       */\n      const itemsToRedo = new Set();\n      /**\n       * @type {Array<Item>}\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      result = 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  if (result != null) {\n    const changedParentTypes = _tr.changedParentTypes;\n    undoManager.emit('stack-item-popped', [{ stackItem: result, type: eventType, changedParentTypes }, undoManager]);\n  }\n  return result\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<any>} [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 * 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 {Observable<'stack-item-added'|'stack-item-popped'|'stack-cleared'|'stack-item-updated'>}\n */\nclass UndoManager extends lib0_observable__WEBPACK_IMPORTED_MODULE_0__.Observable {\n  /**\n   * @param {AbstractType<any>|Array<AbstractType<any>>} 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} */ (lib0_array__WEBPACK_IMPORTED_MODULE_2__.isArray(typeScope) ? typeScope[0].doc : typeScope.doc)\n  } = {}) {\n    super();\n    /**\n     * @type {Array<AbstractType<any>>}\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<StackItem>}\n     */\n    this.undoStack = [];\n    /**\n     * @type {Array<StackItem>}\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    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 = lib0_time__WEBPACK_IMPORTED_MODULE_15__.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      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<any>> | AbstractType<any>} ytypes\n   */\n  addToScope (ytypes) {\n    ytypes = lib0_array__WEBPACK_IMPORTED_MODULE_2__.isArray(ytypes) ? ytypes : [ytypes];\n    ytypes.forEach(ytype => {\n      if (this.scope.every(yt => yt !== ytype)) {\n        if (ytype.doc !== this.doc) lib0_logging__WEBPACK_IMPORTED_MODULE_13__.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 = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n  for (let i = 0; i < numOfStateUpdates; i++) {\n    const numberOfStructs = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n    const client = decoder.readClient();\n    let clock = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder.restDecoder);\n        yield new Skip(createID(client, clock), len);\n        clock += len;\n      } else if ((lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BITS5 & info) !== 0) {\n        const cantCopyParentInfo = (info & (lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT7 | lib0_binary__WEBPACK_IMPORTED_MODULE_10__.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 & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT8) === lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT8 ? decoder.readLeftID() : null, // origin\n          null, // right\n          (info & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT7) === lib0_binary__WEBPACK_IMPORTED_MODULE_10__.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 & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT6) === lib0_binary__WEBPACK_IMPORTED_MODULE_10__.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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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  lib0_logging__WEBPACK_IMPORTED_MODULE_13__.print('Structs: ', structs);\n  const ds = readDeleteSet(updateDecoder);\n  lib0_logging__WEBPACK_IMPORTED_MODULE_13__.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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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<Uint8Array>} 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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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          lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder.restEncoder, currClient);\n          lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder.restEncoder, currClient);\n      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder.restEncoder, currClock);\n    }\n    // prepend the size of the state vector\n    const enc = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder();\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(enc, size);\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeBinaryEncoder(enc, encoder.restEncoder);\n    encoder.restEncoder = enc;\n    return encoder.toUint8Array()\n  } else {\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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<number,number>, to: Map<number,number> }}\n */\nconst parseUpdateMetaV2 = (update, YDecoder = UpdateDecoderV2) => {\n  /**\n   * @type {Map<number, number>}\n   */\n  const from = new Map();\n  /**\n   * @type {Map<number, number>}\n   */\n  const to = new Map();\n  const updateDecoder = new LazyStructReader(new YDecoder(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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<number,number>, to: Map<number,number> }}\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<Uint8Array>} 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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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, lib0_math__WEBPACK_IMPORTED_MODULE_1__.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: lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(lazyWriter.encoder.restEncoder) });\n    lazyWriter.encoder.restEncoder = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(restEncoder, partStructs.written);\n    // write the rest of the fragment\n    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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(lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.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 = lib0_map__WEBPACK_IMPORTED_MODULE_3__.create();\n  const nodeNameCache = lib0_map__WEBPACK_IMPORTED_MODULE_3__.create();\n  const formattingKeyCache = lib0_map__WEBPACK_IMPORTED_MODULE_3__.create();\n  const formattingValueCache = lib0_map__WEBPACK_IMPORTED_MODULE_3__.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 = lib0_map__WEBPACK_IMPORTED_MODULE_3__.setIfUndefined(nodeNameCache, type.nodeName, () => 'node-' + i);\n              }\n              if (type instanceof YXmlHook) {\n                type.hookName = lib0_map__WEBPACK_IMPORTED_MODULE_3__.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 = lib0_map__WEBPACK_IMPORTED_MODULE_3__.setIfUndefined(formattingKeyCache, c.key, () => i + '');\n              c.value = lib0_map__WEBPACK_IMPORTED_MODULE_3__.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 = lib0_string__WEBPACK_IMPORTED_MODULE_16__.repeat((i % 10) + '', c.str.length);\n            break\n          }\n          default:\n            // unknown content type\n            lib0_error__WEBPACK_IMPORTED_MODULE_9__.unexpectedCase();\n        }\n        if (item.parentSub) {\n          item.parentSub = lib0_map__WEBPACK_IMPORTED_MODULE_3__.setIfUndefined(mapKeyCache, item.parentSub, () => i + '');\n        }\n        i++;\n        return block\n      }\n      default:\n        // unknown block-type\n        lib0_error__WEBPACK_IMPORTED_MODULE_9__.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, lib0_function__WEBPACK_IMPORTED_MODULE_11__.id, UpdateDecoderV1, UpdateEncoderV2);\n\n/**\n * @param {Uint8Array} update\n */\nconst convertUpdateFormatV2ToV1 = update => convertUpdateFormat(update, lib0_function__WEBPACK_IMPORTED_MODULE_11__.id, UpdateDecoderV2, UpdateEncoderV1);\n\nconst errorComputeChanges = 'You must not compute changes after the event-handler fired.';\n\n/**\n * @template {AbstractType<any>} 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<any>}\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<string, { action: 'add' | 'update' | 'delete', oldValue: any, newValue: any }>}\n     */\n    this._keys = null;\n    /**\n     * @type {null | Array<{ insert?: string | Array<any> | object | AbstractType<any>, retain?: number, delete?: number, attributes?: Object<string, any> }>}\n     */\n    this._delta = null;\n    /**\n     * @type {Array<string|number>|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<string, { action: 'add' | 'update' | 'delete', oldValue: any, newValue: any }>}\n   */\n  get keys () {\n    if (this._keys === null) {\n      if (this.transaction.doc._transactionCleanups.length === 0) {\n        throw lib0_error__WEBPACK_IMPORTED_MODULE_9__.create(errorComputeChanges)\n      }\n      const keys = new Map();\n      const target = this.target;\n      const changed = /** @type Set<string|null> */ (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 = lib0_array__WEBPACK_IMPORTED_MODULE_2__.last(prev.content.getContent());\n              } else {\n                return\n              }\n            } else {\n              if (prev !== null && this.deletes(prev)) {\n                action = 'update';\n                oldValue = lib0_array__WEBPACK_IMPORTED_MODULE_2__.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 = lib0_array__WEBPACK_IMPORTED_MODULE_2__.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<any> | object | AbstractType<any>, retain?: number, delete?: number, attributes?: Object<string, any>}>}\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<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.create(errorComputeChanges)\n      }\n      const target = this.target;\n      const added = lib0_set__WEBPACK_IMPORTED_MODULE_12__.create();\n      const deleted = lib0_set__WEBPACK_IMPORTED_MODULE_12__.create();\n      /**\n       * @type {Array<{insert:Array<any>}|{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<string|null> */ (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<any>} parent\n * @param {AbstractType<any>} child target\n * @return {Array<string|number>} 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<any>} */ (child._item.parent)._start;\n      while (c !== child._item && c !== null) {\n        if (!c.deleted) {\n          i++;\n        }\n        c = c.right;\n      }\n      path.unshift(i);\n    }\n    child = /** @type {AbstractType<any>} */ (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<ArraySearchMarker>} 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<any>} 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) => lib0_math__WEBPACK_IMPORTED_MODULE_1__.abs(index - a.index) < lib0_math__WEBPACK_IMPORTED_MODULE_1__.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 && lib0_math__WEBPACK_IMPORTED_MODULE_1__.abs(marker.index - pindex) < /** @type {YText|YArray<any>} */ (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<ArraySearchMarker>} 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 = lib0_math__WEBPACK_IMPORTED_MODULE_1__.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<any>} t\n * @return {Array<Item>}\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<EventType>} 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    lib0_map__WEBPACK_IMPORTED_MODULE_3__.setIfUndefined(changedParentTypes, type, () => []).push(event);\n    if (type._item === null) {\n      break\n    }\n    type = /** @type {AbstractType<any>} */ (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<string,Item>}\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<EventType,Transaction>}\n     */\n    this._eH = createEventHandler();\n    /**\n     * Deep event handlers\n     * @type {EventHandler<Array<YEvent<any>>,Transaction>}\n     */\n    this._dEH = createEventHandler();\n    /**\n     * @type {null | Array<ArraySearchMarker>}\n     */\n    this._searchMarker = null;\n  }\n\n  /**\n   * @return {AbstractType<any>|null}\n   */\n  get parent () {\n    return this._item ? /** @type {AbstractType<any>} */ (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<EventType>}\n   */\n  _copy () {\n    throw lib0_error__WEBPACK_IMPORTED_MODULE_9__.methodUnimplemented()\n  }\n\n  /**\n   * @return {AbstractType<EventType>}\n   */\n  clone () {\n    throw lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<null|string>} _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<YEvent<any>>,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<YEvent<any>>,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<any>} type\n * @param {number} start\n * @param {number} end\n * @return {Array<any>}\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<any>} type\n * @return {Array<any>}\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<any>} type\n * @param {Snapshot} snapshot\n * @return {Array<any>}\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 overy element of this YArray.\n *\n * @param {AbstractType<any>} 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<any>} type\n * @param {function(C,number,AbstractType<any>):R} f\n * @return {Array<R>}\n *\n * @private\n * @function\n */\nconst typeListMap = (type, f) => {\n  /**\n   * @type {Array<any>}\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<any>} type\n * @return {IterableIterator<any>}\n *\n * @private\n * @function\n */\nconst typeListCreateIterator = type => {\n  let n = type._start;\n  /**\n   * @type {Array<any>|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<any>} 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<any>} parent\n * @param {Item?} referenceItem\n * @param {Array<Object<string,any>|Array<any>|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<Object|Array<any>|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 = () => lib0_error__WEBPACK_IMPORTED_MODULE_9__.create('Length exceeded!');\n\n/**\n * @param {Transaction} transaction\n * @param {AbstractType<any>} parent\n * @param {number} index\n * @param {Array<Object<string,any>|Array<any>|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<any>} parent\n * @param {Array<Object<string,any>|Array<any>|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<any>} 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<any>} 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<any>} parent\n * @param {string} key\n * @param {Object|number|null|Array<any>|string|Uint8Array|AbstractType<any>} 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<any>} parent\n * @param {string} key\n * @return {Object<string,any>|number|null|Array<any>|string|Uint8Array|AbstractType<any>|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<any>} parent\n * @return {Object<string,Object<string,any>|number|null|Array<any>|string|Uint8Array|AbstractType<any>|undefined>}\n *\n * @private\n * @function\n */\nconst typeMapGetAll = (parent) => {\n  /**\n   * @type {Object<string,any>}\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<any>} 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<any>} parent\n * @param {string} key\n * @param {Snapshot} snapshot\n * @return {Object<string,any>|number|null|Array<any>|string|Uint8Array|AbstractType<any>|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 {Map<string,Item>} map\n * @return {IterableIterator<Array<any>>}\n *\n * @private\n * @function\n */\nconst createMapIterator = map => lib0_iterator__WEBPACK_IMPORTED_MODULE_17__.iteratorFilter(map.entries(), /** @param {any} entry */ entry => !entry[1].deleted);\n\n/**\n * @module YArray\n */\n\n/**\n * Event that describes the changes on a YArray\n * @template T\n * @extends YEvent<YArray<T>>\n */\nclass YArrayEvent extends YEvent {\n  /**\n   * @param {YArray<T>} yarray The changed type\n   * @param {Transaction} transaction The transaction object\n   */\n  constructor (yarray, transaction) {\n    super(yarray, transaction);\n    this._transaction = transaction;\n  }\n}\n\n/**\n * A shared Array implementation.\n * @template T\n * @extends AbstractType<YArrayEvent<T>>\n * @implements {Iterable<T>}\n */\nclass YArray extends AbstractType {\n  constructor () {\n    super();\n    /**\n     * @type {Array<any>?}\n     * @private\n     */\n    this._prelimContent = [];\n    /**\n     * @type {Array<ArraySearchMarker>}\n     */\n    this._searchMarker = [];\n  }\n\n  /**\n   * Construct a new YArray containing the specified items.\n   * @template {Object<string,any>|Array<any>|number|null|string|Uint8Array} T\n   * @param {Array<T>} items\n   * @return {YArray<T>}\n   */\n  static from (items) {\n    /**\n     * @type {YArray<T>}\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<any>} */ (this._prelimContent));\n    this._prelimContent = null;\n  }\n\n  /**\n   * @return {YArray<T>}\n   */\n  _copy () {\n    return new YArray()\n  }\n\n  /**\n   * @return {YArray<T>}\n   */\n  clone () {\n    /**\n     * @type {YArray<T>}\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<null|string>} 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<T>} 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<any>} */ (this._prelimContent).splice(index, 0, ...content);\n    }\n  }\n\n  /**\n   * Appends content to this YArray.\n   *\n   * @param {Array<T>} 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<any>} */ (this._prelimContent).push(...content);\n    }\n  }\n\n  /**\n   * Preppends content to this YArray.\n   *\n   * @param {Array<T>} content Array of content to preppend.\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<any>} */ (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<T>}\n   */\n  toArray () {\n    return typeListToArray(this)\n  }\n\n  /**\n   * Transforms this YArray to a JavaScript Array.\n   *\n   * @param {number} [start]\n   * @param {number} [end]\n   * @return {Array<T>}\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<any>}\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<T>):M} f Function that produces an element of the new Array\n   * @return {Array<M>} 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 overy element of this YArray.\n   *\n   * @param {function(T,number,YArray<T>):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<T>}\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 * @template T\n * @extends YEvent<YMap<T>>\n * Event that describes the changes on a YMap.\n */\nclass YMapEvent extends YEvent {\n  /**\n   * @param {YMap<T>} ymap The YArray that changed.\n   * @param {Transaction} transaction\n   * @param {Set<any>} 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<YMapEvent<MapType>>\n * @implements {Iterable<MapType>}\n */\nclass YMap extends AbstractType {\n  /**\n   *\n   * @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap\n   */\n  constructor (entries) {\n    super();\n    /**\n     * @type {Map<string,any>?}\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<string, any>} */ (this._prelimContent).forEach((value, key) => {\n      this.set(key, value);\n    });\n    this._prelimContent = null;\n  }\n\n  /**\n   * @return {YMap<MapType>}\n   */\n  _copy () {\n    return new YMap()\n  }\n\n  /**\n   * @return {YMap<MapType>}\n   */\n  clone () {\n    /**\n     * @type {YMap<MapType>}\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<null|string>} 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<string,any>}\n   */\n  toJSON () {\n    /**\n     * @type {Object<string,MapType>}\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<string>}\n   */\n  keys () {\n    return lib0_iterator__WEBPACK_IMPORTED_MODULE_17__.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<any>}\n   */\n  values () {\n    return lib0_iterator__WEBPACK_IMPORTED_MODULE_17__.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<any>}\n   */\n  entries () {\n    return lib0_iterator__WEBPACK_IMPORTED_MODULE_17__.iteratorMap(createMapIterator(this._map), /** @param {any} v */ v => [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<MapType>):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<any>}\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<string, any>} */ (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<string, any>} */ (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<string, any>} */ (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 * @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 && lib0_object__WEBPACK_IMPORTED_MODULE_18__.equalFlat(a, b));\n\nclass ItemTextListPosition {\n  /**\n   * @param {Item|null} left\n   * @param {Item|null} right\n   * @param {number} index\n   * @param {Map<string,any>} 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      lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<any>} parent\n * @param {number} index\n * @return {ItemTextListPosition}\n *\n * @private\n * @function\n */\nconst findPosition = (transaction, parent, index) => {\n  const currentAttributes = new Map();\n  const marker = findMarker(parent, index);\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<any>} parent\n * @param {ItemTextListPosition} currPos\n * @param {Map<string,any>} 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<string,any>} 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<string,any>} 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<any>} parent\n * @param {ItemTextListPosition} currPos\n * @param {Object<string,any>} attributes\n * @return {Map<string,any>}\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<any>} parent\n * @param {ItemTextListPosition} currPos\n * @param {string|object|AbstractType<any>} text\n * @param {Object<string,any>} 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<any>} parent\n * @param {ItemTextListPosition} currPos\n * @param {number} length\n * @param {Object<string,any>} 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<string,any>} startAttributes\n * @param {Map<string,any>} 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<string,ContentFormat>}\n   */\n  const endFormats = lib0_map__WEBPACK_IMPORTED_MODULE_3__.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 = lib0_map__WEBPACK_IMPORTED_MODULE_3__.create();\n    const currentAttributes = lib0_map__WEBPACK_IMPORTED_MODULE_3__.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 = lib0_map__WEBPACK_IMPORTED_MODULE_3__.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<YText>}\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<Item|GC>} */ (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 = lib0_map__WEBPACK_IMPORTED_MODULE_3__.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<any>} */ (/** @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<YText>\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<any>} 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<string>}\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<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string, delete?:number, retain?:number}>}}\n   */\n  get changes () {\n    if (this._changes === null) {\n      /**\n       * @type {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string|AbstractType<any>|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<any>, delete?:number, retain?:number, attributes?: Object<string,any>}>}\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<any>, delete?:number, retain?:number, attributes?: Object<string,any>}>}\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<string,any>}\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 (!lib0_object__WEBPACK_IMPORTED_MODULE_18__.isEmpty(attributes)) {\n                    op.attributes = lib0_object__WEBPACK_IMPORTED_MODULE_18__.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<YTextEvent>\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<function():void>?}\n     */\n    this._pending = string !== undefined ? [() => this.insert(0, string)] : [];\n    /**\n     * @type {Array<ArraySearchMarker>|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<function>} */ (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   * @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<null|string>} 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<function>} */ (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<any>}\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<string,any>}\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<string,any>}\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<string,any>}\n               */\n              const op = {\n                insert: n.content.getContent()[0]\n              };\n              if (currentAttributes.size > 0) {\n                const attrs = /** @type {Object<string,any>} */ ({});\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);\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<function>} */ (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<any>} 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);\n        insertText(transaction, this, pos, embed, attributes);\n      });\n    } else {\n      /** @type {Array<function>} */ (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), length);\n      });\n    } else {\n      /** @type {Array<function>} */ (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);\n        if (pos.right === null) {\n          return\n        }\n        formatText(transaction, this, pos, length, attributes);\n      });\n    } else {\n      /** @type {Array<function>} */ (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<function>} */ (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<function>} */ (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<string, any>} 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 * 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<YXmlElement|YXmlText|YXmlElement|YXmlHook>}\n */\nclass YXmlTreeWalker {\n  /**\n   * @param {YXmlFragment | YXmlElement} root\n   * @param {function(AbstractType<any>):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<YXmlElement|YXmlText|YXmlHook>} 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<any>} */ (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<YXmlEvent>\n */\nclass YXmlFragment extends AbstractType {\n  constructor () {\n    super();\n    /**\n     * @type {Array<any>|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<any>} */ (this._prelimContent));\n    this._prelimContent = null;\n  }\n\n  _copy () {\n    return new YXmlFragment()\n  }\n\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<any>):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<YXmlElement|YXmlText|YXmlHook|null>} The elements that match this query.\n   *\n   * @public\n   */\n  querySelectorAll (query) {\n    query = query.toUpperCase();\n    // @ts-ignore\n    return lib0_array__WEBPACK_IMPORTED_MODULE_2__.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<null|string>} 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<string, any>} [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<YXmlElement|YXmlText>} 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<YXmlElement|YXmlText>} 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<any>} */ (this._prelimContent);\n      const index = ref === null ? 0 : pc.findIndex(el => el === ref) + 1;\n      if (index === 0 && ref !== null) {\n        throw lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<YXmlElement|YXmlText|YXmlHook>}\n   */\n  toArray () {\n    return typeListToArray(this)\n  }\n\n  /**\n   * Appends content to this YArray.\n   *\n   * @param {Array<YXmlElement|YXmlText>} content Array of content to append.\n   */\n  push (content) {\n    this.insert(this.length, content);\n  }\n\n  /**\n   * Preppends content to this YArray.\n   *\n   * @param {Array<YXmlElement|YXmlText>} content Array of content to preppend.\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   * Transforms this YArray to a JavaScript Array.\n   *\n   * @param {number} [start]\n   * @param {number} [end]\n   * @return {Array<YXmlElement|YXmlText>}\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 overy 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<any>|string|Uint8Array|AbstractType<any>} ValueTypes\n */\n\n/**\n * An YXmlElement imitates the behavior of a\n * {@link 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<string, any>|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<string, any>} */ (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   * @return {YXmlElement<KV>}\n   */\n  clone () {\n    /**\n     * @type {YXmlElement<KV>}\n     */\n    const el = new YXmlElement(this.nodeName);\n    const attrs = this.getAttributes();\n    lib0_object__WEBPACK_IMPORTED_MODULE_18__.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()}</${nodeName}>`\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<string,any>} */ (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<string, any>} */ (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   * @return {{ [Key in Extract<keyof KV,string>]?: KV[Key]}} A JSON Object that describes the attributes.\n   *\n   * @public\n   */\n  getAttributes () {\n    return /** @type {any} */ (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<string, any>} [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<YXmlElement|YXmlText|YXmlFragment>\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<string|null>} 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<string>}\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<any>}\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   * @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.<string, any>} [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   * @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<string, any>} [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 += `</${nestedNodes[i].nodeName}>`;\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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.methodUnimplemented()\n  }\n\n  /**\n   * @param {Transaction} transaction\n   * @param {number} offset\n   */\n  integrate (transaction, offset) {\n    throw lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<any>}\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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<any>}\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<string, any>} 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<any>}\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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<any>}\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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<any>}\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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<any>} arr\n   */\n  constructor (arr) {\n    /**\n     * @type {Array<any>}\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<any>}\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<any>} arr\n   */\n  constructor (arr) {\n    /**\n     * @type {Array<any>}\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<any>}\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<any>}\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<function(UpdateDecoderV1 | UpdateDecoderV2):AbstractType<any>>}\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<any>} type\n   */\n  constructor (type) {\n    /**\n     * @type {AbstractType<any>}\n     */\n    this.type = type;\n  }\n\n  /**\n   * @return {number}\n   */\n  getLength () {\n    return 1\n  }\n\n  /**\n   * @return {Array<any>}\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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.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<any>} */ (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<any>} */ (rightItem.parent)._map.set(rightItem.parentSub, rightItem);\n  }\n  leftItem.length = diff;\n  return rightItem\n};\n\n/**\n * @param {Array<StackItem>} stack\n * @param {ID} id\n */\nconst isDeletedByUndoStack = (stack, id) => lib0_array__WEBPACK_IMPORTED_MODULE_2__.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<Item>} 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<any>} */ (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<any>} */ (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<any>} */ (leftTrace.parent)._item !== parentItem) {\n        leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone);\n      }\n      if (leftTrace !== null && /** @type {AbstractType<any>} */ (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<any>} */ (rightTrace.parent)._item !== parentItem) {\n        rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone);\n      }\n      if (rightTrace !== null && /** @type {AbstractType<any>} */ (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<any>|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<any>|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() ? lib0_binary__WEBPACK_IMPORTED_MODULE_10__.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 & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT4) > 0) !== isMarked) {\n      this.info ^= lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT4;\n    }\n  }\n\n  get marker () {\n    return (this.info & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT4) > 0\n  }\n\n  /**\n   * If true, do not garbage collect this Item.\n   */\n  get keep () {\n    return (this.info & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT1) > 0\n  }\n\n  set keep (doKeep) {\n    if (this.keep !== doKeep) {\n      this.info ^= lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT1;\n    }\n  }\n\n  get countable () {\n    return (this.info & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT2) > 0\n  }\n\n  /**\n   * Whether this item was deleted or not.\n   * @type {Boolean}\n   */\n  get deleted () {\n    return (this.info & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT3) > 0\n  }\n\n  set deleted (doDelete) {\n    if (this.deleted !== doDelete) {\n      this.info ^= lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT3;\n    }\n  }\n\n  markDeleted () {\n    this.info |= lib0_binary__WEBPACK_IMPORTED_MODULE_10__.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<any>} */ (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<any>} */ (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<Item>}\n         */\n        const conflictingItems = new Set();\n        /**\n         * @type {Set<Item>}\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<any>} */ (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<any>} */ (this.parent)._start\n          ;/** @type {AbstractType<any>} */ (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<any>} */ (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<any>} */ (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<any>} */ (this.parent), this.parentSub);\n      if ((/** @type {AbstractType<any>} */ (this.parent)._item !== null && /** @type {AbstractType<any>} */ (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<any>} */ (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<any>} */ (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 lib0_error__WEBPACK_IMPORTED_MODULE_9__.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() & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BITS5) |\n      (origin === null ? 0 : lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT8) | // origin is defined\n      (rightOrigin === null ? 0 : lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BIT7) | // right origin is defined\n      (parentSub === null ? 0 : lib0_binary__WEBPACK_IMPORTED_MODULE_10__.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<any>} */ (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        lib0_error__WEBPACK_IMPORTED_MODULE_9__.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 & lib0_binary__WEBPACK_IMPORTED_MODULE_10__.BITS5](decoder);\n\n/**\n * A lookup map for reading Item content.\n *\n * @type {Array<function(UpdateDecoderV1 | UpdateDecoderV2):AbstractContent>}\n */\nconst contentRefs = [\n  () => { lib0_error__WEBPACK_IMPORTED_MODULE_9__.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  () => { lib0_error__WEBPACK_IMPORTED_MODULE_9__.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    lib0_error__WEBPACK_IMPORTED_MODULE_9__.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    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.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\nconst glo = /** @type {any} */ (typeof globalThis !== 'undefined'\n  ? globalThis\n  : typeof window !== 'undefined'\n    ? window\n    // @ts-ignore\n    : typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : {});\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\n\n//# sourceMappingURL=yjs.mjs.map\n\n\n//# sourceURL=webpack://_JUPYTERLAB.CORE_OUTPUT/../node_modules/yjs/dist/yjs.mjs?");

/***/ })

}]);