import {
  require_client
} from "./chunk-DZXNXIW7.js";
import {
  i
} from "./chunk-RU4TY2CQ.js";
import {
  require_browser
} from "./chunk-5QTNICOS.js";
import {
  require_react_dom
} from "./chunk-LRUX6XQC.js";
import {
  require_jsx_runtime
} from "./chunk-YAGB2RBV.js";
import {
  require_react
} from "./chunk-T3SJLYUH.js";
import {
  __commonJS,
  __export,
  __publicField,
  __toESM
} from "./chunk-4B2QHNJT.js";

// ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js
var require_fast_deep_equal = __commonJS({
  "../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) {
    "use strict";
    module.exports = function equal(a3, b4) {
      if (a3 === b4) return true;
      if (a3 && b4 && typeof a3 == "object" && typeof b4 == "object") {
        if (a3.constructor !== b4.constructor) return false;
        var length2, i3, keys5;
        if (Array.isArray(a3)) {
          length2 = a3.length;
          if (length2 != b4.length) return false;
          for (i3 = length2; i3-- !== 0; )
            if (!equal(a3[i3], b4[i3])) return false;
          return true;
        }
        if (a3.constructor === RegExp) return a3.source === b4.source && a3.flags === b4.flags;
        if (a3.valueOf !== Object.prototype.valueOf) return a3.valueOf() === b4.valueOf();
        if (a3.toString !== Object.prototype.toString) return a3.toString() === b4.toString();
        keys5 = Object.keys(a3);
        length2 = keys5.length;
        if (length2 !== Object.keys(b4).length) return false;
        for (i3 = length2; i3-- !== 0; )
          if (!Object.prototype.hasOwnProperty.call(b4, keys5[i3])) return false;
        for (i3 = length2; i3-- !== 0; ) {
          var key2 = keys5[i3];
          if (!equal(a3[key2], b4[key2])) return false;
        }
        return true;
      }
      return a3 !== a3 && b4 !== b4;
    };
  }
});

// ../../node_modules/.pnpm/extend@3.0.2/node_modules/extend/index.js
var require_extend = __commonJS({
  "../../node_modules/.pnpm/extend@3.0.2/node_modules/extend/index.js"(exports, module) {
    "use strict";
    var hasOwn2 = Object.prototype.hasOwnProperty;
    var toStr = Object.prototype.toString;
    var defineProperty = Object.defineProperty;
    var gOPD = Object.getOwnPropertyDescriptor;
    var isArray2 = function isArray3(arr) {
      if (typeof Array.isArray === "function") {
        return Array.isArray(arr);
      }
      return toStr.call(arr) === "[object Array]";
    };
    var isPlainObject3 = function isPlainObject4(obj) {
      if (!obj || toStr.call(obj) !== "[object Object]") {
        return false;
      }
      var hasOwnConstructor = hasOwn2.call(obj, "constructor");
      var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn2.call(obj.constructor.prototype, "isPrototypeOf");
      if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
        return false;
      }
      var key2;
      for (key2 in obj) {
      }
      return typeof key2 === "undefined" || hasOwn2.call(obj, key2);
    };
    var setProperty = function setProperty2(target, options2) {
      if (defineProperty && options2.name === "__proto__") {
        defineProperty(target, options2.name, {
          enumerable: true,
          configurable: true,
          value: options2.newValue,
          writable: true
        });
      } else {
        target[options2.name] = options2.newValue;
      }
    };
    var getProperty = function getProperty2(obj, name) {
      if (name === "__proto__") {
        if (!hasOwn2.call(obj, name)) {
          return void 0;
        } else if (gOPD) {
          return gOPD(obj, name).value;
        }
      }
      return obj[name];
    };
    module.exports = function extend2() {
      var options2, name, src, copy3, copyIsArray, clone;
      var target = arguments[0];
      var i3 = 1;
      var length2 = arguments.length;
      var deep = false;
      if (typeof target === "boolean") {
        deep = target;
        target = arguments[1] || {};
        i3 = 2;
      }
      if (target == null || typeof target !== "object" && typeof target !== "function") {
        target = {};
      }
      for (; i3 < length2; ++i3) {
        options2 = arguments[i3];
        if (options2 != null) {
          for (name in options2) {
            src = getProperty(target, name);
            copy3 = getProperty(options2, name);
            if (target !== copy3) {
              if (deep && copy3 && (isPlainObject3(copy3) || (copyIsArray = isArray2(copy3)))) {
                if (copyIsArray) {
                  copyIsArray = false;
                  clone = src && isArray2(src) ? src : [];
                } else {
                  clone = src && isPlainObject3(src) ? src : {};
                }
                setProperty(target, { name, newValue: extend2(deep, clone, copy3) });
              } else if (typeof copy3 !== "undefined") {
                setProperty(target, { name, newValue: copy3 });
              }
            }
          }
        }
      }
      return target;
    };
  }
});

// ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js
var require_use_sync_external_store_shim_development = __commonJS({
  "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js"(exports) {
    "use strict";
    (function() {
      function is2(x5, y3) {
        return x5 === y3 && (0 !== x5 || 1 / x5 === 1 / y3) || x5 !== x5 && y3 !== y3;
      }
      function useSyncExternalStore$2(subscribe, getSnapshot) {
        didWarnOld18Alpha || void 0 === React5.startTransition || (didWarnOld18Alpha = true, console.error(
          "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
        ));
        var value = getSnapshot();
        if (!didWarnUncachedGetSnapshot) {
          var cachedValue = getSnapshot();
          objectIs(value, cachedValue) || (console.error(
            "The result of getSnapshot should be cached to avoid an infinite loop"
          ), didWarnUncachedGetSnapshot = true);
        }
        cachedValue = useState4({
          inst: { value, getSnapshot }
        });
        var inst = cachedValue[0].inst, forceUpdate = cachedValue[1];
        useLayoutEffect4(
          function() {
            inst.value = value;
            inst.getSnapshot = getSnapshot;
            checkIfSnapshotChanged(inst) && forceUpdate({ inst });
          },
          [subscribe, value, getSnapshot]
        );
        useEffect4(
          function() {
            checkIfSnapshotChanged(inst) && forceUpdate({ inst });
            return subscribe(function() {
              checkIfSnapshotChanged(inst) && forceUpdate({ inst });
            });
          },
          [subscribe]
        );
        useDebugValue3(value);
        return value;
      }
      function checkIfSnapshotChanged(inst) {
        var latestGetSnapshot = inst.getSnapshot;
        inst = inst.value;
        try {
          var nextValue = latestGetSnapshot();
          return !objectIs(inst, nextValue);
        } catch (error2) {
          return true;
        }
      }
      function useSyncExternalStore$1(subscribe, getSnapshot) {
        return getSnapshot();
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      var React5 = require_react(), objectIs = "function" === typeof Object.is ? Object.is : is2, useState4 = React5.useState, useEffect4 = React5.useEffect, useLayoutEffect4 = React5.useLayoutEffect, useDebugValue3 = React5.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2;
      exports.useSyncExternalStore = void 0 !== React5.useSyncExternalStore ? React5.useSyncExternalStore : shim;
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  }
});

// ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/shim/index.js
var require_shim = __commonJS({
  "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/shim/index.js"(exports, module) {
    "use strict";
    if (false) {
      module.exports = null;
    } else {
      module.exports = require_use_sync_external_store_shim_development();
    }
  }
});

// ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js
var require_with_selector_development = __commonJS({
  "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js"(exports) {
    "use strict";
    (function() {
      function is2(x5, y3) {
        return x5 === y3 && (0 !== x5 || 1 / x5 === 1 / y3) || x5 !== x5 && y3 !== y3;
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      var React5 = require_react(), shim = require_shim(), objectIs = "function" === typeof Object.is ? Object.is : is2, useSyncExternalStore3 = shim.useSyncExternalStore, useRef5 = React5.useRef, useEffect4 = React5.useEffect, useMemo4 = React5.useMemo, useDebugValue3 = React5.useDebugValue;
      exports.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
        var instRef = useRef5(null);
        if (null === instRef.current) {
          var inst = { hasValue: false, value: null };
          instRef.current = inst;
        } else inst = instRef.current;
        instRef = useMemo4(
          function() {
            function memoizedSelector(nextSnapshot) {
              if (!hasMemo) {
                hasMemo = true;
                memoizedSnapshot = nextSnapshot;
                nextSnapshot = selector(nextSnapshot);
                if (void 0 !== isEqual && inst.hasValue) {
                  var currentSelection = inst.value;
                  if (isEqual(currentSelection, nextSnapshot))
                    return memoizedSelection = currentSelection;
                }
                return memoizedSelection = nextSnapshot;
              }
              currentSelection = memoizedSelection;
              if (objectIs(memoizedSnapshot, nextSnapshot))
                return currentSelection;
              var nextSelection = selector(nextSnapshot);
              if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
                return memoizedSnapshot = nextSnapshot, currentSelection;
              memoizedSnapshot = nextSnapshot;
              return memoizedSelection = nextSelection;
            }
            var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot;
            return [
              function() {
                return memoizedSelector(getSnapshot());
              },
              null === maybeGetServerSnapshot ? void 0 : function() {
                return memoizedSelector(maybeGetServerSnapshot());
              }
            ];
          },
          [getSnapshot, getServerSnapshot, selector, isEqual]
        );
        var value = useSyncExternalStore3(subscribe, instRef[0], instRef[1]);
        useEffect4(
          function() {
            inst.hasValue = true;
            inst.value = value;
          },
          [value]
        );
        useDebugValue3(value);
        return value;
      };
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  }
});

// ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/shim/with-selector.js
var require_with_selector = __commonJS({
  "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/shim/with-selector.js"(exports, module) {
    "use strict";
    if (false) {
      module.exports = null;
    } else {
      module.exports = require_with_selector_development();
    }
  }
});

// ../../node_modules/.pnpm/@blocknote+react@0.45.0_@floating-ui+dom@1.7.4_@tiptap+extensions@3.14.0_@tiptap+core@3_4c2381f288dfb667bae932edc4edea17/node_modules/@blocknote/react/dist/blocknote-react.js
var import_react12 = __toESM(require_react());
var import_jsx_runtime10 = __toESM(require_jsx_runtime());

// ../../node_modules/.pnpm/orderedmap@2.1.1/node_modules/orderedmap/dist/index.js
function OrderedMap(content5) {
  this.content = content5;
}
OrderedMap.prototype = {
  constructor: OrderedMap,
  find: function(key2) {
    for (var i3 = 0; i3 < this.content.length; i3 += 2)
      if (this.content[i3] === key2) return i3;
    return -1;
  },
  // :: (string) → ?any
  // Retrieve the value stored under `key`, or return undefined when
  // no such key exists.
  get: function(key2) {
    var found2 = this.find(key2);
    return found2 == -1 ? void 0 : this.content[found2 + 1];
  },
  // :: (string, any, ?string) → OrderedMap
  // Create a new map by replacing the value of `key` with a new
  // value, or adding a binding to the end of the map. If `newKey` is
  // given, the key of the binding will be replaced with that key.
  update: function(key2, value, newKey) {
    var self2 = newKey && newKey != key2 ? this.remove(newKey) : this;
    var found2 = self2.find(key2), content5 = self2.content.slice();
    if (found2 == -1) {
      content5.push(newKey || key2, value);
    } else {
      content5[found2 + 1] = value;
      if (newKey) content5[found2] = newKey;
    }
    return new OrderedMap(content5);
  },
  // :: (string) → OrderedMap
  // Return a map with the given key removed, if it existed.
  remove: function(key2) {
    var found2 = this.find(key2);
    if (found2 == -1) return this;
    var content5 = this.content.slice();
    content5.splice(found2, 2);
    return new OrderedMap(content5);
  },
  // :: (string, any) → OrderedMap
  // Add a new key to the start of the map.
  addToStart: function(key2, value) {
    return new OrderedMap([key2, value].concat(this.remove(key2).content));
  },
  // :: (string, any) → OrderedMap
  // Add a new key to the end of the map.
  addToEnd: function(key2, value) {
    var content5 = this.remove(key2).content.slice();
    content5.push(key2, value);
    return new OrderedMap(content5);
  },
  // :: (string, string, any) → OrderedMap
  // Add a key after the given key. If `place` is not found, the new
  // key is added to the end.
  addBefore: function(place, key2, value) {
    var without = this.remove(key2), content5 = without.content.slice();
    var found2 = without.find(place);
    content5.splice(found2 == -1 ? content5.length : found2, 0, key2, value);
    return new OrderedMap(content5);
  },
  // :: ((key: string, value: any))
  // Call the given function for each key/value pair in the map, in
  // order.
  forEach: function(f6) {
    for (var i3 = 0; i3 < this.content.length; i3 += 2)
      f6(this.content[i3], this.content[i3 + 1]);
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by prepending the keys in this map that don't
  // appear in `map` before the keys in `map`.
  prepend: function(map7) {
    map7 = OrderedMap.from(map7);
    if (!map7.size) return this;
    return new OrderedMap(map7.content.concat(this.subtract(map7).content));
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by appending the keys in this map that don't
  // appear in `map` after the keys in `map`.
  append: function(map7) {
    map7 = OrderedMap.from(map7);
    if (!map7.size) return this;
    return new OrderedMap(this.subtract(map7).content.concat(map7.content));
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a map containing all the keys in this map that don't
  // appear in `map`.
  subtract: function(map7) {
    var result = this;
    map7 = OrderedMap.from(map7);
    for (var i3 = 0; i3 < map7.content.length; i3 += 2)
      result = result.remove(map7.content[i3]);
    return result;
  },
  // :: () → Object
  // Turn ordered map into a plain object.
  toObject: function() {
    var result = {};
    this.forEach(function(key2, value) {
      result[key2] = value;
    });
    return result;
  },
  // :: number
  // The amount of keys in this map.
  get size() {
    return this.content.length >> 1;
  }
};
OrderedMap.from = function(value) {
  if (value instanceof OrderedMap) return value;
  var content5 = [];
  if (value) for (var prop in value) content5.push(prop, value[prop]);
  return new OrderedMap(content5);
};
var dist_default = OrderedMap;

// ../../node_modules/.pnpm/prosemirror-model@1.25.4/node_modules/prosemirror-model/dist/index.js
function findDiffStart(a3, b4, pos) {
  for (let i3 = 0; ; i3++) {
    if (i3 == a3.childCount || i3 == b4.childCount)
      return a3.childCount == b4.childCount ? null : pos;
    let childA = a3.child(i3), childB = b4.child(i3);
    if (childA == childB) {
      pos += childA.nodeSize;
      continue;
    }
    if (!childA.sameMarkup(childB))
      return pos;
    if (childA.isText && childA.text != childB.text) {
      for (let j4 = 0; childA.text[j4] == childB.text[j4]; j4++)
        pos++;
      return pos;
    }
    if (childA.content.size || childB.content.size) {
      let inner = findDiffStart(childA.content, childB.content, pos + 1);
      if (inner != null)
        return inner;
    }
    pos += childA.nodeSize;
  }
}
function findDiffEnd(a3, b4, posA, posB) {
  for (let iA = a3.childCount, iB = b4.childCount; ; ) {
    if (iA == 0 || iB == 0)
      return iA == iB ? null : { a: posA, b: posB };
    let childA = a3.child(--iA), childB = b4.child(--iB), size5 = childA.nodeSize;
    if (childA == childB) {
      posA -= size5;
      posB -= size5;
      continue;
    }
    if (!childA.sameMarkup(childB))
      return { a: posA, b: posB };
    if (childA.isText && childA.text != childB.text) {
      let same = 0, minSize = Math.min(childA.text.length, childB.text.length);
      while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {
        same++;
        posA--;
        posB--;
      }
      return { a: posA, b: posB };
    }
    if (childA.content.size || childB.content.size) {
      let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
      if (inner)
        return inner;
    }
    posA -= size5;
    posB -= size5;
  }
}
var Fragment = class _Fragment {
  /**
  @internal
  */
  constructor(content5, size5) {
    this.content = content5;
    this.size = size5 || 0;
    if (size5 == null)
      for (let i3 = 0; i3 < content5.length; i3++)
        this.size += content5[i3].nodeSize;
  }
  /**
  Invoke a callback for all descendant nodes between the given two
  positions (relative to start of this fragment). Doesn't descend
  into a node when the callback returns `false`.
  */
  nodesBetween(from4, to2, f6, nodeStart = 0, parent) {
    for (let i3 = 0, pos = 0; pos < to2; i3++) {
      let child = this.content[i3], end = pos + child.nodeSize;
      if (end > from4 && f6(child, nodeStart + pos, parent || null, i3) !== false && child.content.size) {
        let start = pos + 1;
        child.nodesBetween(Math.max(0, from4 - start), Math.min(child.content.size, to2 - start), f6, nodeStart + start);
      }
      pos = end;
    }
  }
  /**
  Call the given callback for every descendant node. `pos` will be
  relative to the start of the fragment. The callback may return
  `false` to prevent traversal of a given node's children.
  */
  descendants(f6) {
    this.nodesBetween(0, this.size, f6);
  }
  /**
  Extract the text between `from` and `to`. See the same method on
  [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
  */
  textBetween(from4, to2, blockSeparator, leafText) {
    let text10 = "", first2 = true;
    this.nodesBetween(from4, to2, (node2, pos) => {
      let nodeText = node2.isText ? node2.text.slice(Math.max(from4, pos) - pos, to2 - pos) : !node2.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node2) : leafText : node2.type.spec.leafText ? node2.type.spec.leafText(node2) : "";
      if (node2.isBlock && (node2.isLeaf && nodeText || node2.isTextblock) && blockSeparator) {
        if (first2)
          first2 = false;
        else
          text10 += blockSeparator;
      }
      text10 += nodeText;
    }, 0);
    return text10;
  }
  /**
  Create a new fragment containing the combined content of this
  fragment and the other.
  */
  append(other) {
    if (!other.size)
      return this;
    if (!this.size)
      return other;
    let last2 = this.lastChild, first2 = other.firstChild, content5 = this.content.slice(), i3 = 0;
    if (last2.isText && last2.sameMarkup(first2)) {
      content5[content5.length - 1] = last2.withText(last2.text + first2.text);
      i3 = 1;
    }
    for (; i3 < other.content.length; i3++)
      content5.push(other.content[i3]);
    return new _Fragment(content5, this.size + other.size);
  }
  /**
  Cut out the sub-fragment between the two given positions.
  */
  cut(from4, to2 = this.size) {
    if (from4 == 0 && to2 == this.size)
      return this;
    let result = [], size5 = 0;
    if (to2 > from4)
      for (let i3 = 0, pos = 0; pos < to2; i3++) {
        let child = this.content[i3], end = pos + child.nodeSize;
        if (end > from4) {
          if (pos < from4 || end > to2) {
            if (child.isText)
              child = child.cut(Math.max(0, from4 - pos), Math.min(child.text.length, to2 - pos));
            else
              child = child.cut(Math.max(0, from4 - pos - 1), Math.min(child.content.size, to2 - pos - 1));
          }
          result.push(child);
          size5 += child.nodeSize;
        }
        pos = end;
      }
    return new _Fragment(result, size5);
  }
  /**
  @internal
  */
  cutByIndex(from4, to2) {
    if (from4 == to2)
      return _Fragment.empty;
    if (from4 == 0 && to2 == this.content.length)
      return this;
    return new _Fragment(this.content.slice(from4, to2));
  }
  /**
  Create a new fragment in which the node at the given index is
  replaced by the given node.
  */
  replaceChild(index4, node2) {
    let current = this.content[index4];
    if (current == node2)
      return this;
    let copy3 = this.content.slice();
    let size5 = this.size + node2.nodeSize - current.nodeSize;
    copy3[index4] = node2;
    return new _Fragment(copy3, size5);
  }
  /**
  Create a new fragment by prepending the given node to this
  fragment.
  */
  addToStart(node2) {
    return new _Fragment([node2].concat(this.content), this.size + node2.nodeSize);
  }
  /**
  Create a new fragment by appending the given node to this
  fragment.
  */
  addToEnd(node2) {
    return new _Fragment(this.content.concat(node2), this.size + node2.nodeSize);
  }
  /**
  Compare this fragment to another one.
  */
  eq(other) {
    if (this.content.length != other.content.length)
      return false;
    for (let i3 = 0; i3 < this.content.length; i3++)
      if (!this.content[i3].eq(other.content[i3]))
        return false;
    return true;
  }
  /**
  The first child of the fragment, or `null` if it is empty.
  */
  get firstChild() {
    return this.content.length ? this.content[0] : null;
  }
  /**
  The last child of the fragment, or `null` if it is empty.
  */
  get lastChild() {
    return this.content.length ? this.content[this.content.length - 1] : null;
  }
  /**
  The number of child nodes in this fragment.
  */
  get childCount() {
    return this.content.length;
  }
  /**
  Get the child node at the given index. Raise an error when the
  index is out of range.
  */
  child(index4) {
    let found2 = this.content[index4];
    if (!found2)
      throw new RangeError("Index " + index4 + " out of range for " + this);
    return found2;
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(index4) {
    return this.content[index4] || null;
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(f6) {
    for (let i3 = 0, p4 = 0; i3 < this.content.length; i3++) {
      let child = this.content[i3];
      f6(child, p4, i3);
      p4 += child.nodeSize;
    }
  }
  /**
  Find the first position at which this fragment and another
  fragment differ, or `null` if they are the same.
  */
  findDiffStart(other, pos = 0) {
    return findDiffStart(this, other, pos);
  }
  /**
  Find the first position, searching from the end, at which this
  fragment and the given fragment differ, or `null` if they are
  the same. Since this position will not be the same in both
  nodes, an object with two separate positions is returned.
  */
  findDiffEnd(other, pos = this.size, otherPos = other.size) {
    return findDiffEnd(this, other, pos, otherPos);
  }
  /**
  Find the index and inner offset corresponding to a given relative
  position in this fragment. The result object will be reused
  (overwritten) the next time the function is called. @internal
  */
  findIndex(pos) {
    if (pos == 0)
      return retIndex(0, pos);
    if (pos == this.size)
      return retIndex(this.content.length, pos);
    if (pos > this.size || pos < 0)
      throw new RangeError(`Position ${pos} outside of fragment (${this})`);
    for (let i3 = 0, curPos = 0; ; i3++) {
      let cur = this.child(i3), end = curPos + cur.nodeSize;
      if (end >= pos) {
        if (end == pos)
          return retIndex(i3 + 1, end);
        return retIndex(i3, curPos);
      }
      curPos = end;
    }
  }
  /**
  Return a debugging string that describes this fragment.
  */
  toString() {
    return "<" + this.toStringInner() + ">";
  }
  /**
  @internal
  */
  toStringInner() {
    return this.content.join(", ");
  }
  /**
  Create a JSON-serializeable representation of this fragment.
  */
  toJSON() {
    return this.content.length ? this.content.map((n) => n.toJSON()) : null;
  }
  /**
  Deserialize a fragment from its JSON representation.
  */
  static fromJSON(schema, value) {
    if (!value)
      return _Fragment.empty;
    if (!Array.isArray(value))
      throw new RangeError("Invalid input for Fragment.fromJSON");
    return new _Fragment(value.map(schema.nodeFromJSON));
  }
  /**
  Build a fragment from an array of nodes. Ensures that adjacent
  text nodes with the same marks are joined together.
  */
  static fromArray(array) {
    if (!array.length)
      return _Fragment.empty;
    let joined, size5 = 0;
    for (let i3 = 0; i3 < array.length; i3++) {
      let node2 = array[i3];
      size5 += node2.nodeSize;
      if (i3 && node2.isText && array[i3 - 1].sameMarkup(node2)) {
        if (!joined)
          joined = array.slice(0, i3);
        joined[joined.length - 1] = node2.withText(joined[joined.length - 1].text + node2.text);
      } else if (joined) {
        joined.push(node2);
      }
    }
    return new _Fragment(joined || array, size5);
  }
  /**
  Create a fragment from something that can be interpreted as a
  set of nodes. For `null`, it returns the empty fragment. For a
  fragment, the fragment itself. For a node or array of nodes, a
  fragment containing those nodes.
  */
  static from(nodes) {
    if (!nodes)
      return _Fragment.empty;
    if (nodes instanceof _Fragment)
      return nodes;
    if (Array.isArray(nodes))
      return this.fromArray(nodes);
    if (nodes.attrs)
      return new _Fragment([nodes], nodes.nodeSize);
    throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
  }
};
Fragment.empty = new Fragment([], 0);
var found = { index: 0, offset: 0 };
function retIndex(index4, offset4) {
  found.index = index4;
  found.offset = offset4;
  return found;
}
function compareDeep(a3, b4) {
  if (a3 === b4)
    return true;
  if (!(a3 && typeof a3 == "object") || !(b4 && typeof b4 == "object"))
    return false;
  let array = Array.isArray(a3);
  if (Array.isArray(b4) != array)
    return false;
  if (array) {
    if (a3.length != b4.length)
      return false;
    for (let i3 = 0; i3 < a3.length; i3++)
      if (!compareDeep(a3[i3], b4[i3]))
        return false;
  } else {
    for (let p4 in a3)
      if (!(p4 in b4) || !compareDeep(a3[p4], b4[p4]))
        return false;
    for (let p4 in b4)
      if (!(p4 in a3))
        return false;
  }
  return true;
}
var Mark = class _Mark2 {
  /**
  @internal
  */
  constructor(type, attrs) {
    this.type = type;
    this.attrs = attrs;
  }
  /**
  Given a set of marks, create a new set which contains this one as
  well, in the right position. If this mark is already in the set,
  the set itself is returned. If any marks that are set to be
  [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,
  those are replaced by this one.
  */
  addToSet(set) {
    let copy3, placed = false;
    for (let i3 = 0; i3 < set.length; i3++) {
      let other = set[i3];
      if (this.eq(other))
        return set;
      if (this.type.excludes(other.type)) {
        if (!copy3)
          copy3 = set.slice(0, i3);
      } else if (other.type.excludes(this.type)) {
        return set;
      } else {
        if (!placed && other.type.rank > this.type.rank) {
          if (!copy3)
            copy3 = set.slice(0, i3);
          copy3.push(this);
          placed = true;
        }
        if (copy3)
          copy3.push(other);
      }
    }
    if (!copy3)
      copy3 = set.slice();
    if (!placed)
      copy3.push(this);
    return copy3;
  }
  /**
  Remove this mark from the given set, returning a new set. If this
  mark is not in the set, the set itself is returned.
  */
  removeFromSet(set) {
    for (let i3 = 0; i3 < set.length; i3++)
      if (this.eq(set[i3]))
        return set.slice(0, i3).concat(set.slice(i3 + 1));
    return set;
  }
  /**
  Test whether this mark is in the given set of marks.
  */
  isInSet(set) {
    for (let i3 = 0; i3 < set.length; i3++)
      if (this.eq(set[i3]))
        return true;
    return false;
  }
  /**
  Test whether this mark has the same type and attributes as
  another mark.
  */
  eq(other) {
    return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs);
  }
  /**
  Convert this mark to a JSON-serializeable representation.
  */
  toJSON() {
    let obj = { type: this.type.name };
    for (let _2 in this.attrs) {
      obj.attrs = this.attrs;
      break;
    }
    return obj;
  }
  /**
  Deserialize a mark from JSON.
  */
  static fromJSON(schema, json) {
    if (!json)
      throw new RangeError("Invalid input for Mark.fromJSON");
    let type = schema.marks[json.type];
    if (!type)
      throw new RangeError(`There is no mark type ${json.type} in this schema`);
    let mark2 = type.create(json.attrs);
    type.checkAttrs(mark2.attrs);
    return mark2;
  }
  /**
  Test whether two sets of marks are identical.
  */
  static sameSet(a3, b4) {
    if (a3 == b4)
      return true;
    if (a3.length != b4.length)
      return false;
    for (let i3 = 0; i3 < a3.length; i3++)
      if (!a3[i3].eq(b4[i3]))
        return false;
    return true;
  }
  /**
  Create a properly sorted mark set from null, a single mark, or an
  unsorted array of marks.
  */
  static setFrom(marks) {
    if (!marks || Array.isArray(marks) && marks.length == 0)
      return _Mark2.none;
    if (marks instanceof _Mark2)
      return [marks];
    let copy3 = marks.slice();
    copy3.sort((a3, b4) => a3.type.rank - b4.type.rank);
    return copy3;
  }
};
Mark.none = [];
var ReplaceError = class extends Error {
};
var Slice = class _Slice {
  /**
  Create a slice. When specifying a non-zero open depth, you must
  make sure that there are nodes of at least that depth at the
  appropriate side of the fragment—i.e. if the fragment is an
  empty paragraph node, `openStart` and `openEnd` can't be greater
  than 1.
  
  It is not necessary for the content of open nodes to conform to
  the schema's content constraints, though it should be a valid
  start/end/middle for such a node, depending on which sides are
  open.
  */
  constructor(content5, openStart, openEnd) {
    this.content = content5;
    this.openStart = openStart;
    this.openEnd = openEnd;
  }
  /**
  The size this slice would add when inserted into a document.
  */
  get size() {
    return this.content.size - this.openStart - this.openEnd;
  }
  /**
  @internal
  */
  insertAt(pos, fragment) {
    let content5 = insertInto(this.content, pos + this.openStart, fragment);
    return content5 && new _Slice(content5, this.openStart, this.openEnd);
  }
  /**
  @internal
  */
  removeBetween(from4, to2) {
    return new _Slice(removeRange(this.content, from4 + this.openStart, to2 + this.openStart), this.openStart, this.openEnd);
  }
  /**
  Tests whether this slice is equal to another slice.
  */
  eq(other) {
    return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
  }
  /**
  @internal
  */
  toString() {
    return this.content + "(" + this.openStart + "," + this.openEnd + ")";
  }
  /**
  Convert a slice to a JSON-serializable representation.
  */
  toJSON() {
    if (!this.content.size)
      return null;
    let json = { content: this.content.toJSON() };
    if (this.openStart > 0)
      json.openStart = this.openStart;
    if (this.openEnd > 0)
      json.openEnd = this.openEnd;
    return json;
  }
  /**
  Deserialize a slice from its JSON representation.
  */
  static fromJSON(schema, json) {
    if (!json)
      return _Slice.empty;
    let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
    if (typeof openStart != "number" || typeof openEnd != "number")
      throw new RangeError("Invalid input for Slice.fromJSON");
    return new _Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);
  }
  /**
  Create a slice from a fragment by taking the maximum possible
  open value on both side of the fragment.
  */
  static maxOpen(fragment, openIsolating = true) {
    let openStart = 0, openEnd = 0;
    for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)
      openStart++;
    for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)
      openEnd++;
    return new _Slice(fragment, openStart, openEnd);
  }
};
Slice.empty = new Slice(Fragment.empty, 0, 0);
function removeRange(content5, from4, to2) {
  let { index: index4, offset: offset4 } = content5.findIndex(from4), child = content5.maybeChild(index4);
  let { index: indexTo, offset: offsetTo } = content5.findIndex(to2);
  if (offset4 == from4 || child.isText) {
    if (offsetTo != to2 && !content5.child(indexTo).isText)
      throw new RangeError("Removing non-flat range");
    return content5.cut(0, from4).append(content5.cut(to2));
  }
  if (index4 != indexTo)
    throw new RangeError("Removing non-flat range");
  return content5.replaceChild(index4, child.copy(removeRange(child.content, from4 - offset4 - 1, to2 - offset4 - 1)));
}
function insertInto(content5, dist, insert, parent) {
  let { index: index4, offset: offset4 } = content5.findIndex(dist), child = content5.maybeChild(index4);
  if (offset4 == dist || child.isText) {
    if (parent && !parent.canReplace(index4, index4, insert))
      return null;
    return content5.cut(0, dist).append(insert).append(content5.cut(dist));
  }
  let inner = insertInto(child.content, dist - offset4 - 1, insert, child);
  return inner && content5.replaceChild(index4, child.copy(inner));
}
function replace($from, $to, slice2) {
  if (slice2.openStart > $from.depth)
    throw new ReplaceError("Inserted content deeper than insertion position");
  if ($from.depth - slice2.openStart != $to.depth - slice2.openEnd)
    throw new ReplaceError("Inconsistent open depths");
  return replaceOuter($from, $to, slice2, 0);
}
function replaceOuter($from, $to, slice2, depth) {
  let index4 = $from.index(depth), node2 = $from.node(depth);
  if (index4 == $to.index(depth) && depth < $from.depth - slice2.openStart) {
    let inner = replaceOuter($from, $to, slice2, depth + 1);
    return node2.copy(node2.content.replaceChild(index4, inner));
  } else if (!slice2.content.size) {
    return close(node2, replaceTwoWay($from, $to, depth));
  } else if (!slice2.openStart && !slice2.openEnd && $from.depth == depth && $to.depth == depth) {
    let parent = $from.parent, content5 = parent.content;
    return close(parent, content5.cut(0, $from.parentOffset).append(slice2.content).append(content5.cut($to.parentOffset)));
  } else {
    let { start, end } = prepareSliceForReplace(slice2, $from);
    return close(node2, replaceThreeWay($from, start, end, $to, depth));
  }
}
function checkJoin(main, sub) {
  if (!sub.type.compatibleContent(main.type))
    throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name);
}
function joinable($before, $after, depth) {
  let node2 = $before.node(depth);
  checkJoin(node2, $after.node(depth));
  return node2;
}
function addNode(child, target) {
  let last2 = target.length - 1;
  if (last2 >= 0 && child.isText && child.sameMarkup(target[last2]))
    target[last2] = child.withText(target[last2].text + child.text);
  else
    target.push(child);
}
function addRange($start, $end, depth, target) {
  let node2 = ($end || $start).node(depth);
  let startIndex = 0, endIndex = $end ? $end.index(depth) : node2.childCount;
  if ($start) {
    startIndex = $start.index(depth);
    if ($start.depth > depth) {
      startIndex++;
    } else if ($start.textOffset) {
      addNode($start.nodeAfter, target);
      startIndex++;
    }
  }
  for (let i3 = startIndex; i3 < endIndex; i3++)
    addNode(node2.child(i3), target);
  if ($end && $end.depth == depth && $end.textOffset)
    addNode($end.nodeBefore, target);
}
function close(node2, content5) {
  node2.type.checkContent(content5);
  return node2.copy(content5);
}
function replaceThreeWay($from, $start, $end, $to, depth) {
  let openStart = $from.depth > depth && joinable($from, $start, depth + 1);
  let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);
  let content5 = [];
  addRange(null, $from, depth, content5);
  if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
    checkJoin(openStart, openEnd);
    addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content5);
  } else {
    if (openStart)
      addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content5);
    addRange($start, $end, depth, content5);
    if (openEnd)
      addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content5);
  }
  addRange($to, null, depth, content5);
  return new Fragment(content5);
}
function replaceTwoWay($from, $to, depth) {
  let content5 = [];
  addRange(null, $from, depth, content5);
  if ($from.depth > depth) {
    let type = joinable($from, $to, depth + 1);
    addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content5);
  }
  addRange($to, null, depth, content5);
  return new Fragment(content5);
}
function prepareSliceForReplace(slice2, $along) {
  let extra = $along.depth - slice2.openStart, parent = $along.node(extra);
  let node2 = parent.copy(slice2.content);
  for (let i3 = extra - 1; i3 >= 0; i3--)
    node2 = $along.node(i3).copy(Fragment.from(node2));
  return {
    start: node2.resolveNoCache(slice2.openStart + extra),
    end: node2.resolveNoCache(node2.content.size - slice2.openEnd - extra)
  };
}
var ResolvedPos = class _ResolvedPos {
  /**
  @internal
  */
  constructor(pos, path2, parentOffset) {
    this.pos = pos;
    this.path = path2;
    this.parentOffset = parentOffset;
    this.depth = path2.length / 3 - 1;
  }
  /**
  @internal
  */
  resolveDepth(val) {
    if (val == null)
      return this.depth;
    if (val < 0)
      return this.depth + val;
    return val;
  }
  /**
  The parent node that the position points into. Note that even if
  a position points into a text node, that node is not considered
  the parent—text nodes are ‘flat’ in this model, and have no content.
  */
  get parent() {
    return this.node(this.depth);
  }
  /**
  The root node in which the position was resolved.
  */
  get doc() {
    return this.node(0);
  }
  /**
  The ancestor node at the given level. `p.node(p.depth)` is the
  same as `p.parent`.
  */
  node(depth) {
    return this.path[this.resolveDepth(depth) * 3];
  }
  /**
  The index into the ancestor at the given level. If this points
  at the 3rd node in the 2nd paragraph on the top level, for
  example, `p.index(0)` is 1 and `p.index(1)` is 2.
  */
  index(depth) {
    return this.path[this.resolveDepth(depth) * 3 + 1];
  }
  /**
  The index pointing after this position into the ancestor at the
  given level.
  */
  indexAfter(depth) {
    depth = this.resolveDepth(depth);
    return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
  }
  /**
  The (absolute) position at the start of the node at the given
  level.
  */
  start(depth) {
    depth = this.resolveDepth(depth);
    return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
  }
  /**
  The (absolute) position at the end of the node at the given
  level.
  */
  end(depth) {
    depth = this.resolveDepth(depth);
    return this.start(depth) + this.node(depth).content.size;
  }
  /**
  The (absolute) position directly before the wrapping node at the
  given level, or, when `depth` is `this.depth + 1`, the original
  position.
  */
  before(depth) {
    depth = this.resolveDepth(depth);
    if (!depth)
      throw new RangeError("There is no position before the top-level node");
    return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
  }
  /**
  The (absolute) position directly after the wrapping node at the
  given level, or the original position when `depth` is `this.depth + 1`.
  */
  after(depth) {
    depth = this.resolveDepth(depth);
    if (!depth)
      throw new RangeError("There is no position after the top-level node");
    return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
  }
  /**
  When this position points into a text node, this returns the
  distance between the position and the start of the text node.
  Will be zero for positions that point between nodes.
  */
  get textOffset() {
    return this.pos - this.path[this.path.length - 1];
  }
  /**
  Get the node directly after the position, if any. If the position
  points into a text node, only the part of that node after the
  position is returned.
  */
  get nodeAfter() {
    let parent = this.parent, index4 = this.index(this.depth);
    if (index4 == parent.childCount)
      return null;
    let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index4);
    return dOff ? parent.child(index4).cut(dOff) : child;
  }
  /**
  Get the node directly before the position, if any. If the
  position points into a text node, only the part of that node
  before the position is returned.
  */
  get nodeBefore() {
    let index4 = this.index(this.depth);
    let dOff = this.pos - this.path[this.path.length - 1];
    if (dOff)
      return this.parent.child(index4).cut(0, dOff);
    return index4 == 0 ? null : this.parent.child(index4 - 1);
  }
  /**
  Get the position at the given index in the parent node at the
  given depth (which defaults to `this.depth`).
  */
  posAtIndex(index4, depth) {
    depth = this.resolveDepth(depth);
    let node2 = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
    for (let i3 = 0; i3 < index4; i3++)
      pos += node2.child(i3).nodeSize;
    return pos;
  }
  /**
  Get the marks at this position, factoring in the surrounding
  marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the
  position is at the start of a non-empty node, the marks of the
  node after it (if any) are returned.
  */
  marks() {
    let parent = this.parent, index4 = this.index();
    if (parent.content.size == 0)
      return Mark.none;
    if (this.textOffset)
      return parent.child(index4).marks;
    let main = parent.maybeChild(index4 - 1), other = parent.maybeChild(index4);
    if (!main) {
      let tmp = main;
      main = other;
      other = tmp;
    }
    let marks = main.marks;
    for (var i3 = 0; i3 < marks.length; i3++)
      if (marks[i3].type.spec.inclusive === false && (!other || !marks[i3].isInSet(other.marks)))
        marks = marks[i3--].removeFromSet(marks);
    return marks;
  }
  /**
  Get the marks after the current position, if any, except those
  that are non-inclusive and not present at position `$end`. This
  is mostly useful for getting the set of marks to preserve after a
  deletion. Will return `null` if this position is at the end of
  its parent node or its parent node isn't a textblock (in which
  case no marks should be preserved).
  */
  marksAcross($end) {
    let after = this.parent.maybeChild(this.index());
    if (!after || !after.isInline)
      return null;
    let marks = after.marks, next2 = $end.parent.maybeChild($end.index());
    for (var i3 = 0; i3 < marks.length; i3++)
      if (marks[i3].type.spec.inclusive === false && (!next2 || !marks[i3].isInSet(next2.marks)))
        marks = marks[i3--].removeFromSet(marks);
    return marks;
  }
  /**
  The depth up to which this position and the given (non-resolved)
  position share the same parent nodes.
  */
  sharedDepth(pos) {
    for (let depth = this.depth; depth > 0; depth--)
      if (this.start(depth) <= pos && this.end(depth) >= pos)
        return depth;
    return 0;
  }
  /**
  Returns a range based on the place where this position and the
  given position diverge around block content. If both point into
  the same textblock, for example, a range around that textblock
  will be returned. If they point into different blocks, the range
  around those blocks in their shared ancestor is returned. You can
  pass in an optional predicate that will be called with a parent
  node to see if a range into that parent is acceptable.
  */
  blockRange(other = this, pred) {
    if (other.pos < this.pos)
      return other.blockRange(this);
    for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--)
      if (other.pos <= this.end(d) && (!pred || pred(this.node(d))))
        return new NodeRange(this, other, d);
    return null;
  }
  /**
  Query whether the given position shares the same parent node.
  */
  sameParent(other) {
    return this.pos - this.parentOffset == other.pos - other.parentOffset;
  }
  /**
  Return the greater of this and the given position.
  */
  max(other) {
    return other.pos > this.pos ? other : this;
  }
  /**
  Return the smaller of this and the given position.
  */
  min(other) {
    return other.pos < this.pos ? other : this;
  }
  /**
  @internal
  */
  toString() {
    let str = "";
    for (let i3 = 1; i3 <= this.depth; i3++)
      str += (str ? "/" : "") + this.node(i3).type.name + "_" + this.index(i3 - 1);
    return str + ":" + this.parentOffset;
  }
  /**
  @internal
  */
  static resolve(doc4, pos) {
    if (!(pos >= 0 && pos <= doc4.content.size))
      throw new RangeError("Position " + pos + " out of range");
    let path2 = [];
    let start = 0, parentOffset = pos;
    for (let node2 = doc4; ; ) {
      let { index: index4, offset: offset4 } = node2.content.findIndex(parentOffset);
      let rem = parentOffset - offset4;
      path2.push(node2, index4, start + offset4);
      if (!rem)
        break;
      node2 = node2.child(index4);
      if (node2.isText)
        break;
      parentOffset = rem - 1;
      start += offset4 + 1;
    }
    return new _ResolvedPos(pos, path2, parentOffset);
  }
  /**
  @internal
  */
  static resolveCached(doc4, pos) {
    let cache = resolveCache.get(doc4);
    if (cache) {
      for (let i3 = 0; i3 < cache.elts.length; i3++) {
        let elt = cache.elts[i3];
        if (elt.pos == pos)
          return elt;
      }
    } else {
      resolveCache.set(doc4, cache = new ResolveCache());
    }
    let result = cache.elts[cache.i] = _ResolvedPos.resolve(doc4, pos);
    cache.i = (cache.i + 1) % resolveCacheSize;
    return result;
  }
};
var ResolveCache = class {
  constructor() {
    this.elts = [];
    this.i = 0;
  }
};
var resolveCacheSize = 12;
var resolveCache = /* @__PURE__ */ new WeakMap();
var NodeRange = class {
  /**
  Construct a node range. `$from` and `$to` should point into the
  same node until at least the given `depth`, since a node range
  denotes an adjacent set of nodes in a single parent node.
  */
  constructor($from, $to, depth) {
    this.$from = $from;
    this.$to = $to;
    this.depth = depth;
  }
  /**
  The position at the start of the range.
  */
  get start() {
    return this.$from.before(this.depth + 1);
  }
  /**
  The position at the end of the range.
  */
  get end() {
    return this.$to.after(this.depth + 1);
  }
  /**
  The parent node that the range points into.
  */
  get parent() {
    return this.$from.node(this.depth);
  }
  /**
  The start index of the range in the parent node.
  */
  get startIndex() {
    return this.$from.index(this.depth);
  }
  /**
  The end index of the range in the parent node.
  */
  get endIndex() {
    return this.$to.indexAfter(this.depth);
  }
};
var emptyAttrs = /* @__PURE__ */ Object.create(null);
var Node2 = class _Node2 {
  /**
  @internal
  */
  constructor(type, attrs, content5, marks = Mark.none) {
    this.type = type;
    this.attrs = attrs;
    this.marks = marks;
    this.content = content5 || Fragment.empty;
  }
  /**
  The array of this node's child nodes.
  */
  get children() {
    return this.content.content;
  }
  /**
  The size of this node, as defined by the integer-based [indexing
  scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the
  amount of characters. For other leaf nodes, it is one. For
  non-leaf nodes, it is the size of the content plus two (the
  start and end token).
  */
  get nodeSize() {
    return this.isLeaf ? 1 : 2 + this.content.size;
  }
  /**
  The number of children that the node has.
  */
  get childCount() {
    return this.content.childCount;
  }
  /**
  Get the child node at the given index. Raises an error when the
  index is out of range.
  */
  child(index4) {
    return this.content.child(index4);
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(index4) {
    return this.content.maybeChild(index4);
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(f6) {
    this.content.forEach(f6);
  }
  /**
  Invoke a callback for all descendant nodes recursively between
  the given two positions that are relative to start of this
  node's content. The callback is invoked with the node, its
  position relative to the original node (method receiver),
  its parent node, and its child index. When the callback returns
  false for a given node, that node's children will not be
  recursed over. The last parameter can be used to specify a
  starting position to count from.
  */
  nodesBetween(from4, to2, f6, startPos = 0) {
    this.content.nodesBetween(from4, to2, f6, startPos, this);
  }
  /**
  Call the given callback for every descendant node. Doesn't
  descend into a node when the callback returns `false`.
  */
  descendants(f6) {
    this.nodesBetween(0, this.content.size, f6);
  }
  /**
  Concatenates all the text nodes found in this fragment and its
  children.
  */
  get textContent() {
    return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, "");
  }
  /**
  Get all text between positions `from` and `to`. When
  `blockSeparator` is given, it will be inserted to separate text
  from different block nodes. If `leafText` is given, it'll be
  inserted for every non-text leaf node encountered, otherwise
  [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.
  */
  textBetween(from4, to2, blockSeparator, leafText) {
    return this.content.textBetween(from4, to2, blockSeparator, leafText);
  }
  /**
  Returns this node's first child, or `null` if there are no
  children.
  */
  get firstChild() {
    return this.content.firstChild;
  }
  /**
  Returns this node's last child, or `null` if there are no
  children.
  */
  get lastChild() {
    return this.content.lastChild;
  }
  /**
  Test whether two nodes represent the same piece of document.
  */
  eq(other) {
    return this == other || this.sameMarkup(other) && this.content.eq(other.content);
  }
  /**
  Compare the markup (type, attributes, and marks) of this node to
  those of another. Returns `true` if both have the same markup.
  */
  sameMarkup(other) {
    return this.hasMarkup(other.type, other.attrs, other.marks);
  }
  /**
  Check whether this node's markup correspond to the given type,
  attributes, and marks.
  */
  hasMarkup(type, attrs, marks) {
    return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks || Mark.none);
  }
  /**
  Create a new node with the same markup as this node, containing
  the given content (or empty, if no content is given).
  */
  copy(content5 = null) {
    if (content5 == this.content)
      return this;
    return new _Node2(this.type, this.attrs, content5, this.marks);
  }
  /**
  Create a copy of this node, with the given set of marks instead
  of the node's own marks.
  */
  mark(marks) {
    return marks == this.marks ? this : new _Node2(this.type, this.attrs, this.content, marks);
  }
  /**
  Create a copy of this node with only the content between the
  given positions. If `to` is not given, it defaults to the end of
  the node.
  */
  cut(from4, to2 = this.content.size) {
    if (from4 == 0 && to2 == this.content.size)
      return this;
    return this.copy(this.content.cut(from4, to2));
  }
  /**
  Cut out the part of the document between the given positions, and
  return it as a `Slice` object.
  */
  slice(from4, to2 = this.content.size, includeParents = false) {
    if (from4 == to2)
      return Slice.empty;
    let $from = this.resolve(from4), $to = this.resolve(to2);
    let depth = includeParents ? 0 : $from.sharedDepth(to2);
    let start = $from.start(depth), node2 = $from.node(depth);
    let content5 = node2.content.cut($from.pos - start, $to.pos - start);
    return new Slice(content5, $from.depth - depth, $to.depth - depth);
  }
  /**
  Replace the part of the document between the given positions with
  the given slice. The slice must 'fit', meaning its open sides
  must be able to connect to the surrounding content, and its
  content nodes must be valid children for the node they are placed
  into. If any of this is violated, an error of type
  [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.
  */
  replace(from4, to2, slice2) {
    return replace(this.resolve(from4), this.resolve(to2), slice2);
  }
  /**
  Find the node directly after the given position.
  */
  nodeAt(pos) {
    for (let node2 = this; ; ) {
      let { index: index4, offset: offset4 } = node2.content.findIndex(pos);
      node2 = node2.maybeChild(index4);
      if (!node2)
        return null;
      if (offset4 == pos || node2.isText)
        return node2;
      pos -= offset4 + 1;
    }
  }
  /**
  Find the (direct) child node after the given offset, if any,
  and return it along with its index and offset relative to this
  node.
  */
  childAfter(pos) {
    let { index: index4, offset: offset4 } = this.content.findIndex(pos);
    return { node: this.content.maybeChild(index4), index: index4, offset: offset4 };
  }
  /**
  Find the (direct) child node before the given offset, if any,
  and return it along with its index and offset relative to this
  node.
  */
  childBefore(pos) {
    if (pos == 0)
      return { node: null, index: 0, offset: 0 };
    let { index: index4, offset: offset4 } = this.content.findIndex(pos);
    if (offset4 < pos)
      return { node: this.content.child(index4), index: index4, offset: offset4 };
    let node2 = this.content.child(index4 - 1);
    return { node: node2, index: index4 - 1, offset: offset4 - node2.nodeSize };
  }
  /**
  Resolve the given position in the document, returning an
  [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.
  */
  resolve(pos) {
    return ResolvedPos.resolveCached(this, pos);
  }
  /**
  @internal
  */
  resolveNoCache(pos) {
    return ResolvedPos.resolve(this, pos);
  }
  /**
  Test whether a given mark or mark type occurs in this document
  between the two given positions.
  */
  rangeHasMark(from4, to2, type) {
    let found2 = false;
    if (to2 > from4)
      this.nodesBetween(from4, to2, (node2) => {
        if (type.isInSet(node2.marks))
          found2 = true;
        return !found2;
      });
    return found2;
  }
  /**
  True when this is a block (non-inline node)
  */
  get isBlock() {
    return this.type.isBlock;
  }
  /**
  True when this is a textblock node, a block node with inline
  content.
  */
  get isTextblock() {
    return this.type.isTextblock;
  }
  /**
  True when this node allows inline content.
  */
  get inlineContent() {
    return this.type.inlineContent;
  }
  /**
  True when this is an inline node (a text node or a node that can
  appear among text).
  */
  get isInline() {
    return this.type.isInline;
  }
  /**
  True when this is a text node.
  */
  get isText() {
    return this.type.isText;
  }
  /**
  True when this is a leaf node.
  */
  get isLeaf() {
    return this.type.isLeaf;
  }
  /**
  True when this is an atom, i.e. when it does not have directly
  editable content. This is usually the same as `isLeaf`, but can
  be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)
  on a node's spec (typically used when the node is displayed as
  an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).
  */
  get isAtom() {
    return this.type.isAtom;
  }
  /**
  Return a string representation of this node for debugging
  purposes.
  */
  toString() {
    if (this.type.spec.toDebugString)
      return this.type.spec.toDebugString(this);
    let name = this.type.name;
    if (this.content.size)
      name += "(" + this.content.toStringInner() + ")";
    return wrapMarks(this.marks, name);
  }
  /**
  Get the content match in this node at the given index.
  */
  contentMatchAt(index4) {
    let match2 = this.type.contentMatch.matchFragment(this.content, 0, index4);
    if (!match2)
      throw new Error("Called contentMatchAt on a node with invalid content");
    return match2;
  }
  /**
  Test whether replacing the range between `from` and `to` (by
  child index) with the given replacement fragment (which defaults
  to the empty fragment) would leave the node's content valid. You
  can optionally pass `start` and `end` indices into the
  replacement fragment.
  */
  canReplace(from4, to2, replacement = Fragment.empty, start = 0, end = replacement.childCount) {
    let one6 = this.contentMatchAt(from4).matchFragment(replacement, start, end);
    let two = one6 && one6.matchFragment(this.content, to2);
    if (!two || !two.validEnd)
      return false;
    for (let i3 = start; i3 < end; i3++)
      if (!this.type.allowsMarks(replacement.child(i3).marks))
        return false;
    return true;
  }
  /**
  Test whether replacing the range `from` to `to` (by index) with
  a node of the given type would leave the node's content valid.
  */
  canReplaceWith(from4, to2, type, marks) {
    if (marks && !this.type.allowsMarks(marks))
      return false;
    let start = this.contentMatchAt(from4).matchType(type);
    let end = start && start.matchFragment(this.content, to2);
    return end ? end.validEnd : false;
  }
  /**
  Test whether the given node's content could be appended to this
  node. If that node is empty, this will only return true if there
  is at least one node type that can appear in both nodes (to avoid
  merging completely incompatible nodes).
  */
  canAppend(other) {
    if (other.content.size)
      return this.canReplace(this.childCount, this.childCount, other.content);
    else
      return this.type.compatibleContent(other.type);
  }
  /**
  Check whether this node and its descendants conform to the
  schema, and raise an exception when they do not.
  */
  check() {
    this.type.checkContent(this.content);
    this.type.checkAttrs(this.attrs);
    let copy3 = Mark.none;
    for (let i3 = 0; i3 < this.marks.length; i3++) {
      let mark2 = this.marks[i3];
      mark2.type.checkAttrs(mark2.attrs);
      copy3 = mark2.addToSet(copy3);
    }
    if (!Mark.sameSet(copy3, this.marks))
      throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m2) => m2.type.name)}`);
    this.content.forEach((node2) => node2.check());
  }
  /**
  Return a JSON-serializeable representation of this node.
  */
  toJSON() {
    let obj = { type: this.type.name };
    for (let _2 in this.attrs) {
      obj.attrs = this.attrs;
      break;
    }
    if (this.content.size)
      obj.content = this.content.toJSON();
    if (this.marks.length)
      obj.marks = this.marks.map((n) => n.toJSON());
    return obj;
  }
  /**
  Deserialize a node from its JSON representation.
  */
  static fromJSON(schema, json) {
    if (!json)
      throw new RangeError("Invalid input for Node.fromJSON");
    let marks = void 0;
    if (json.marks) {
      if (!Array.isArray(json.marks))
        throw new RangeError("Invalid mark data for Node.fromJSON");
      marks = json.marks.map(schema.markFromJSON);
    }
    if (json.type == "text") {
      if (typeof json.text != "string")
        throw new RangeError("Invalid text node in JSON");
      return schema.text(json.text, marks);
    }
    let content5 = Fragment.fromJSON(schema, json.content);
    let node2 = schema.nodeType(json.type).create(json.attrs, content5, marks);
    node2.type.checkAttrs(node2.attrs);
    return node2;
  }
};
Node2.prototype.text = void 0;
var TextNode = class _TextNode extends Node2 {
  /**
  @internal
  */
  constructor(type, attrs, content5, marks) {
    super(type, attrs, null, marks);
    if (!content5)
      throw new RangeError("Empty text nodes are not allowed");
    this.text = content5;
  }
  toString() {
    if (this.type.spec.toDebugString)
      return this.type.spec.toDebugString(this);
    return wrapMarks(this.marks, JSON.stringify(this.text));
  }
  get textContent() {
    return this.text;
  }
  textBetween(from4, to2) {
    return this.text.slice(from4, to2);
  }
  get nodeSize() {
    return this.text.length;
  }
  mark(marks) {
    return marks == this.marks ? this : new _TextNode(this.type, this.attrs, this.text, marks);
  }
  withText(text10) {
    if (text10 == this.text)
      return this;
    return new _TextNode(this.type, this.attrs, text10, this.marks);
  }
  cut(from4 = 0, to2 = this.text.length) {
    if (from4 == 0 && to2 == this.text.length)
      return this;
    return this.withText(this.text.slice(from4, to2));
  }
  eq(other) {
    return this.sameMarkup(other) && this.text == other.text;
  }
  toJSON() {
    let base4 = super.toJSON();
    base4.text = this.text;
    return base4;
  }
};
function wrapMarks(marks, str) {
  for (let i3 = marks.length - 1; i3 >= 0; i3--)
    str = marks[i3].type.name + "(" + str + ")";
  return str;
}
var ContentMatch = class _ContentMatch {
  /**
  @internal
  */
  constructor(validEnd) {
    this.validEnd = validEnd;
    this.next = [];
    this.wrapCache = [];
  }
  /**
  @internal
  */
  static parse(string3, nodeTypes) {
    let stream = new TokenStream(string3, nodeTypes);
    if (stream.next == null)
      return _ContentMatch.empty;
    let expr = parseExpr(stream);
    if (stream.next)
      stream.err("Unexpected trailing text");
    let match2 = dfa(nfa(expr));
    checkForDeadEnds(match2, stream);
    return match2;
  }
  /**
  Match a node type, returning a match after that node if
  successful.
  */
  matchType(type) {
    for (let i3 = 0; i3 < this.next.length; i3++)
      if (this.next[i3].type == type)
        return this.next[i3].next;
    return null;
  }
  /**
  Try to match a fragment. Returns the resulting match when
  successful.
  */
  matchFragment(frag, start = 0, end = frag.childCount) {
    let cur = this;
    for (let i3 = start; cur && i3 < end; i3++)
      cur = cur.matchType(frag.child(i3).type);
    return cur;
  }
  /**
  @internal
  */
  get inlineContent() {
    return this.next.length != 0 && this.next[0].type.isInline;
  }
  /**
  Get the first matching node type at this match position that can
  be generated.
  */
  get defaultType() {
    for (let i3 = 0; i3 < this.next.length; i3++) {
      let { type } = this.next[i3];
      if (!(type.isText || type.hasRequiredAttrs()))
        return type;
    }
    return null;
  }
  /**
  @internal
  */
  compatible(other) {
    for (let i3 = 0; i3 < this.next.length; i3++)
      for (let j4 = 0; j4 < other.next.length; j4++)
        if (this.next[i3].type == other.next[j4].type)
          return true;
    return false;
  }
  /**
  Try to match the given fragment, and if that fails, see if it can
  be made to match by inserting nodes in front of it. When
  successful, return a fragment of inserted nodes (which may be
  empty if nothing had to be inserted). When `toEnd` is true, only
  return a fragment if the resulting match goes to the end of the
  content expression.
  */
  fillBefore(after, toEnd = false, startIndex = 0) {
    let seen = [this];
    function search3(match2, types2) {
      let finished = match2.matchFragment(after, startIndex);
      if (finished && (!toEnd || finished.validEnd))
        return Fragment.from(types2.map((tp) => tp.createAndFill()));
      for (let i3 = 0; i3 < match2.next.length; i3++) {
        let { type, next: next2 } = match2.next[i3];
        if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next2) == -1) {
          seen.push(next2);
          let found2 = search3(next2, types2.concat(type));
          if (found2)
            return found2;
        }
      }
      return null;
    }
    return search3(this, []);
  }
  /**
  Find a set of wrapping node types that would allow a node of the
  given type to appear at this position. The result may be empty
  (when it fits directly) and will be null when no such wrapping
  exists.
  */
  findWrapping(target) {
    for (let i3 = 0; i3 < this.wrapCache.length; i3 += 2)
      if (this.wrapCache[i3] == target)
        return this.wrapCache[i3 + 1];
    let computed = this.computeWrapping(target);
    this.wrapCache.push(target, computed);
    return computed;
  }
  /**
  @internal
  */
  computeWrapping(target) {
    let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }];
    while (active.length) {
      let current = active.shift(), match2 = current.match;
      if (match2.matchType(target)) {
        let result = [];
        for (let obj = current; obj.type; obj = obj.via)
          result.push(obj.type);
        return result.reverse();
      }
      for (let i3 = 0; i3 < match2.next.length; i3++) {
        let { type, next: next2 } = match2.next[i3];
        if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next2.validEnd)) {
          active.push({ match: type.contentMatch, type, via: current });
          seen[type.name] = true;
        }
      }
    }
    return null;
  }
  /**
  The number of outgoing edges this node has in the finite
  automaton that describes the content expression.
  */
  get edgeCount() {
    return this.next.length;
  }
  /**
  Get the _n_​th outgoing edge from this node in the finite
  automaton that describes the content expression.
  */
  edge(n) {
    if (n >= this.next.length)
      throw new RangeError(`There's no ${n}th edge in this content match`);
    return this.next[n];
  }
  /**
  @internal
  */
  toString() {
    let seen = [];
    function scan(m2) {
      seen.push(m2);
      for (let i3 = 0; i3 < m2.next.length; i3++)
        if (seen.indexOf(m2.next[i3].next) == -1)
          scan(m2.next[i3].next);
    }
    scan(this);
    return seen.map((m2, i3) => {
      let out = i3 + (m2.validEnd ? "*" : " ") + " ";
      for (let i4 = 0; i4 < m2.next.length; i4++)
        out += (i4 ? ", " : "") + m2.next[i4].type.name + "->" + seen.indexOf(m2.next[i4].next);
      return out;
    }).join("\n");
  }
};
ContentMatch.empty = new ContentMatch(true);
var TokenStream = class {
  constructor(string3, nodeTypes) {
    this.string = string3;
    this.nodeTypes = nodeTypes;
    this.inline = null;
    this.pos = 0;
    this.tokens = string3.split(/\s*(?=\b|\W|$)/);
    if (this.tokens[this.tokens.length - 1] == "")
      this.tokens.pop();
    if (this.tokens[0] == "")
      this.tokens.shift();
  }
  get next() {
    return this.tokens[this.pos];
  }
  eat(tok) {
    return this.next == tok && (this.pos++ || true);
  }
  err(str) {
    throw new SyntaxError(str + " (in content expression '" + this.string + "')");
  }
};
function parseExpr(stream) {
  let exprs = [];
  do {
    exprs.push(parseExprSeq(stream));
  } while (stream.eat("|"));
  return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
}
function parseExprSeq(stream) {
  let exprs = [];
  do {
    exprs.push(parseExprSubscript(stream));
  } while (stream.next && stream.next != ")" && stream.next != "|");
  return exprs.length == 1 ? exprs[0] : { type: "seq", exprs };
}
function parseExprSubscript(stream) {
  let expr = parseExprAtom(stream);
  for (; ; ) {
    if (stream.eat("+"))
      expr = { type: "plus", expr };
    else if (stream.eat("*"))
      expr = { type: "star", expr };
    else if (stream.eat("?"))
      expr = { type: "opt", expr };
    else if (stream.eat("{"))
      expr = parseExprRange(stream, expr);
    else
      break;
  }
  return expr;
}
function parseNum(stream) {
  if (/\D/.test(stream.next))
    stream.err("Expected number, got '" + stream.next + "'");
  let result = Number(stream.next);
  stream.pos++;
  return result;
}
function parseExprRange(stream, expr) {
  let min3 = parseNum(stream), max3 = min3;
  if (stream.eat(",")) {
    if (stream.next != "}")
      max3 = parseNum(stream);
    else
      max3 = -1;
  }
  if (!stream.eat("}"))
    stream.err("Unclosed braced range");
  return { type: "range", min: min3, max: max3, expr };
}
function resolveName(stream, name) {
  let types2 = stream.nodeTypes, type = types2[name];
  if (type)
    return [type];
  let result = [];
  for (let typeName in types2) {
    let type2 = types2[typeName];
    if (type2.isInGroup(name))
      result.push(type2);
  }
  if (result.length == 0)
    stream.err("No node type or group '" + name + "' found");
  return result;
}
function parseExprAtom(stream) {
  if (stream.eat("(")) {
    let expr = parseExpr(stream);
    if (!stream.eat(")"))
      stream.err("Missing closing paren");
    return expr;
  } else if (!/\W/.test(stream.next)) {
    let exprs = resolveName(stream, stream.next).map((type) => {
      if (stream.inline == null)
        stream.inline = type.isInline;
      else if (stream.inline != type.isInline)
        stream.err("Mixing inline and block content");
      return { type: "name", value: type };
    });
    stream.pos++;
    return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
  } else {
    stream.err("Unexpected token '" + stream.next + "'");
  }
}
function nfa(expr) {
  let nfa2 = [[]];
  connect(compile2(expr, 0), node2());
  return nfa2;
  function node2() {
    return nfa2.push([]) - 1;
  }
  function edge(from4, to2, term) {
    let edge2 = { term, to: to2 };
    nfa2[from4].push(edge2);
    return edge2;
  }
  function connect(edges, to2) {
    edges.forEach((edge2) => edge2.to = to2);
  }
  function compile2(expr2, from4) {
    if (expr2.type == "choice") {
      return expr2.exprs.reduce((out, expr3) => out.concat(compile2(expr3, from4)), []);
    } else if (expr2.type == "seq") {
      for (let i3 = 0; ; i3++) {
        let next2 = compile2(expr2.exprs[i3], from4);
        if (i3 == expr2.exprs.length - 1)
          return next2;
        connect(next2, from4 = node2());
      }
    } else if (expr2.type == "star") {
      let loop = node2();
      edge(from4, loop);
      connect(compile2(expr2.expr, loop), loop);
      return [edge(loop)];
    } else if (expr2.type == "plus") {
      let loop = node2();
      connect(compile2(expr2.expr, from4), loop);
      connect(compile2(expr2.expr, loop), loop);
      return [edge(loop)];
    } else if (expr2.type == "opt") {
      return [edge(from4)].concat(compile2(expr2.expr, from4));
    } else if (expr2.type == "range") {
      let cur = from4;
      for (let i3 = 0; i3 < expr2.min; i3++) {
        let next2 = node2();
        connect(compile2(expr2.expr, cur), next2);
        cur = next2;
      }
      if (expr2.max == -1) {
        connect(compile2(expr2.expr, cur), cur);
      } else {
        for (let i3 = expr2.min; i3 < expr2.max; i3++) {
          let next2 = node2();
          edge(cur, next2);
          connect(compile2(expr2.expr, cur), next2);
          cur = next2;
        }
      }
      return [edge(cur)];
    } else if (expr2.type == "name") {
      return [edge(from4, void 0, expr2.value)];
    } else {
      throw new Error("Unknown expr type");
    }
  }
}
function cmp(a3, b4) {
  return b4 - a3;
}
function nullFrom(nfa2, node2) {
  let result = [];
  scan(node2);
  return result.sort(cmp);
  function scan(node3) {
    let edges = nfa2[node3];
    if (edges.length == 1 && !edges[0].term)
      return scan(edges[0].to);
    result.push(node3);
    for (let i3 = 0; i3 < edges.length; i3++) {
      let { term, to: to2 } = edges[i3];
      if (!term && result.indexOf(to2) == -1)
        scan(to2);
    }
  }
}
function dfa(nfa2) {
  let labeled = /* @__PURE__ */ Object.create(null);
  return explore(nullFrom(nfa2, 0));
  function explore(states) {
    let out = [];
    states.forEach((node2) => {
      nfa2[node2].forEach(({ term, to: to2 }) => {
        if (!term)
          return;
        let set;
        for (let i3 = 0; i3 < out.length; i3++)
          if (out[i3][0] == term)
            set = out[i3][1];
        nullFrom(nfa2, to2).forEach((node3) => {
          if (!set)
            out.push([term, set = []]);
          if (set.indexOf(node3) == -1)
            set.push(node3);
        });
      });
    });
    let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1);
    for (let i3 = 0; i3 < out.length; i3++) {
      let states2 = out[i3][1].sort(cmp);
      state.next.push({ type: out[i3][0], next: labeled[states2.join(",")] || explore(states2) });
    }
    return state;
  }
}
function checkForDeadEnds(match2, stream) {
  for (let i3 = 0, work = [match2]; i3 < work.length; i3++) {
    let state = work[i3], dead = !state.validEnd, nodes = [];
    for (let j4 = 0; j4 < state.next.length; j4++) {
      let { type, next: next2 } = state.next[j4];
      nodes.push(type.name);
      if (dead && !(type.isText || type.hasRequiredAttrs()))
        dead = false;
      if (work.indexOf(next2) == -1)
        work.push(next2);
    }
    if (dead)
      stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
  }
}
function defaultAttrs(attrs) {
  let defaults3 = /* @__PURE__ */ Object.create(null);
  for (let attrName in attrs) {
    let attr2 = attrs[attrName];
    if (!attr2.hasDefault)
      return null;
    defaults3[attrName] = attr2.default;
  }
  return defaults3;
}
function computeAttrs(attrs, value) {
  let built = /* @__PURE__ */ Object.create(null);
  for (let name in attrs) {
    let given = value && value[name];
    if (given === void 0) {
      let attr2 = attrs[name];
      if (attr2.hasDefault)
        given = attr2.default;
      else
        throw new RangeError("No value supplied for attribute " + name);
    }
    built[name] = given;
  }
  return built;
}
function checkAttrs(attrs, values2, type, name) {
  for (let name2 in values2)
    if (!(name2 in attrs))
      throw new RangeError(`Unsupported attribute ${name2} for ${type} of type ${name2}`);
  for (let name2 in attrs) {
    let attr2 = attrs[name2];
    if (attr2.validate)
      attr2.validate(values2[name2]);
  }
}
function initAttrs(typeName, attrs) {
  let result = /* @__PURE__ */ Object.create(null);
  if (attrs)
    for (let name in attrs)
      result[name] = new Attribute(typeName, name, attrs[name]);
  return result;
}
var NodeType = class _NodeType {
  /**
  @internal
  */
  constructor(name, schema, spec) {
    this.name = name;
    this.schema = schema;
    this.spec = spec;
    this.markSet = null;
    this.groups = spec.group ? spec.group.split(" ") : [];
    this.attrs = initAttrs(name, spec.attrs);
    this.defaultAttrs = defaultAttrs(this.attrs);
    this.contentMatch = null;
    this.inlineContent = null;
    this.isBlock = !(spec.inline || name == "text");
    this.isText = name == "text";
  }
  /**
  True if this is an inline type.
  */
  get isInline() {
    return !this.isBlock;
  }
  /**
  True if this is a textblock type, a block that contains inline
  content.
  */
  get isTextblock() {
    return this.isBlock && this.inlineContent;
  }
  /**
  True for node types that allow no content.
  */
  get isLeaf() {
    return this.contentMatch == ContentMatch.empty;
  }
  /**
  True when this node is an atom, i.e. when it does not have
  directly editable content.
  */
  get isAtom() {
    return this.isLeaf || !!this.spec.atom;
  }
  /**
  Return true when this node type is part of the given
  [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).
  */
  isInGroup(group) {
    return this.groups.indexOf(group) > -1;
  }
  /**
  The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.
  */
  get whitespace() {
    return this.spec.whitespace || (this.spec.code ? "pre" : "normal");
  }
  /**
  Tells you whether this node type has any required attributes.
  */
  hasRequiredAttrs() {
    for (let n in this.attrs)
      if (this.attrs[n].isRequired)
        return true;
    return false;
  }
  /**
  Indicates whether this node allows some of the same content as
  the given node type.
  */
  compatibleContent(other) {
    return this == other || this.contentMatch.compatible(other.contentMatch);
  }
  /**
  @internal
  */
  computeAttrs(attrs) {
    if (!attrs && this.defaultAttrs)
      return this.defaultAttrs;
    else
      return computeAttrs(this.attrs, attrs);
  }
  /**
  Create a `Node` of this type. The given attributes are
  checked and defaulted (you can pass `null` to use the type's
  defaults entirely, if no required attributes exist). `content`
  may be a `Fragment`, a node, an array of nodes, or
  `null`. Similarly `marks` may be `null` to default to the empty
  set of marks.
  */
  create(attrs = null, content5, marks) {
    if (this.isText)
      throw new Error("NodeType.create can't construct text nodes");
    return new Node2(this, this.computeAttrs(attrs), Fragment.from(content5), Mark.setFrom(marks));
  }
  /**
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content
  against the node type's content restrictions, and throw an error
  if it doesn't match.
  */
  createChecked(attrs = null, content5, marks) {
    content5 = Fragment.from(content5);
    this.checkContent(content5);
    return new Node2(this, this.computeAttrs(attrs), content5, Mark.setFrom(marks));
  }
  /**
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is
  necessary to add nodes to the start or end of the given fragment
  to make it fit the node. If no fitting wrapping can be found,
  return null. Note that, due to the fact that required nodes can
  always be created, this will always succeed if you pass null or
  `Fragment.empty` as content.
  */
  createAndFill(attrs = null, content5, marks) {
    attrs = this.computeAttrs(attrs);
    content5 = Fragment.from(content5);
    if (content5.size) {
      let before = this.contentMatch.fillBefore(content5);
      if (!before)
        return null;
      content5 = before.append(content5);
    }
    let matched = this.contentMatch.matchFragment(content5);
    let after = matched && matched.fillBefore(Fragment.empty, true);
    if (!after)
      return null;
    return new Node2(this, attrs, content5.append(after), Mark.setFrom(marks));
  }
  /**
  Returns true if the given fragment is valid content for this node
  type.
  */
  validContent(content5) {
    let result = this.contentMatch.matchFragment(content5);
    if (!result || !result.validEnd)
      return false;
    for (let i3 = 0; i3 < content5.childCount; i3++)
      if (!this.allowsMarks(content5.child(i3).marks))
        return false;
    return true;
  }
  /**
  Throws a RangeError if the given fragment is not valid content for this
  node type.
  @internal
  */
  checkContent(content5) {
    if (!this.validContent(content5))
      throw new RangeError(`Invalid content for node ${this.name}: ${content5.toString().slice(0, 50)}`);
  }
  /**
  @internal
  */
  checkAttrs(attrs) {
    checkAttrs(this.attrs, attrs, "node", this.name);
  }
  /**
  Check whether the given mark type is allowed in this node.
  */
  allowsMarkType(markType) {
    return this.markSet == null || this.markSet.indexOf(markType) > -1;
  }
  /**
  Test whether the given set of marks are allowed in this node.
  */
  allowsMarks(marks) {
    if (this.markSet == null)
      return true;
    for (let i3 = 0; i3 < marks.length; i3++)
      if (!this.allowsMarkType(marks[i3].type))
        return false;
    return true;
  }
  /**
  Removes the marks that are not allowed in this node from the given set.
  */
  allowedMarks(marks) {
    if (this.markSet == null)
      return marks;
    let copy3;
    for (let i3 = 0; i3 < marks.length; i3++) {
      if (!this.allowsMarkType(marks[i3].type)) {
        if (!copy3)
          copy3 = marks.slice(0, i3);
      } else if (copy3) {
        copy3.push(marks[i3]);
      }
    }
    return !copy3 ? marks : copy3.length ? copy3 : Mark.none;
  }
  /**
  @internal
  */
  static compile(nodes, schema) {
    let result = /* @__PURE__ */ Object.create(null);
    nodes.forEach((name, spec) => result[name] = new _NodeType(name, schema, spec));
    let topType = schema.spec.topNode || "doc";
    if (!result[topType])
      throw new RangeError("Schema is missing its top node type ('" + topType + "')");
    if (!result.text)
      throw new RangeError("Every schema needs a 'text' type");
    for (let _2 in result.text.attrs)
      throw new RangeError("The text node type should not have attributes");
    return result;
  }
};
function validateType(typeName, attrName, type) {
  let types2 = type.split("|");
  return (value) => {
    let name = value === null ? "null" : typeof value;
    if (types2.indexOf(name) < 0)
      throw new RangeError(`Expected value of type ${types2} for attribute ${attrName} on type ${typeName}, got ${name}`);
  };
}
var Attribute = class {
  constructor(typeName, attrName, options2) {
    this.hasDefault = Object.prototype.hasOwnProperty.call(options2, "default");
    this.default = options2.default;
    this.validate = typeof options2.validate == "string" ? validateType(typeName, attrName, options2.validate) : options2.validate;
  }
  get isRequired() {
    return !this.hasDefault;
  }
};
var MarkType = class _MarkType {
  /**
  @internal
  */
  constructor(name, rank, schema, spec) {
    this.name = name;
    this.rank = rank;
    this.schema = schema;
    this.spec = spec;
    this.attrs = initAttrs(name, spec.attrs);
    this.excluded = null;
    let defaults3 = defaultAttrs(this.attrs);
    this.instance = defaults3 ? new Mark(this, defaults3) : null;
  }
  /**
  Create a mark of this type. `attrs` may be `null` or an object
  containing only some of the mark's attributes. The others, if
  they have defaults, will be added.
  */
  create(attrs = null) {
    if (!attrs && this.instance)
      return this.instance;
    return new Mark(this, computeAttrs(this.attrs, attrs));
  }
  /**
  @internal
  */
  static compile(marks, schema) {
    let result = /* @__PURE__ */ Object.create(null), rank = 0;
    marks.forEach((name, spec) => result[name] = new _MarkType(name, rank++, schema, spec));
    return result;
  }
  /**
  When there is a mark of this type in the given set, a new set
  without it is returned. Otherwise, the input set is returned.
  */
  removeFromSet(set) {
    for (var i3 = 0; i3 < set.length; i3++)
      if (set[i3].type == this) {
        set = set.slice(0, i3).concat(set.slice(i3 + 1));
        i3--;
      }
    return set;
  }
  /**
  Tests whether there is a mark of this type in the given set.
  */
  isInSet(set) {
    for (let i3 = 0; i3 < set.length; i3++)
      if (set[i3].type == this)
        return set[i3];
  }
  /**
  @internal
  */
  checkAttrs(attrs) {
    checkAttrs(this.attrs, attrs, "mark", this.name);
  }
  /**
  Queries whether a given mark type is
  [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
  */
  excludes(other) {
    return this.excluded.indexOf(other) > -1;
  }
};
var Schema = class {
  /**
  Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).
  */
  constructor(spec) {
    this.linebreakReplacement = null;
    this.cached = /* @__PURE__ */ Object.create(null);
    let instanceSpec = this.spec = {};
    for (let prop in spec)
      instanceSpec[prop] = spec[prop];
    instanceSpec.nodes = dist_default.from(spec.nodes), instanceSpec.marks = dist_default.from(spec.marks || {}), this.nodes = NodeType.compile(this.spec.nodes, this);
    this.marks = MarkType.compile(this.spec.marks, this);
    let contentExprCache = /* @__PURE__ */ Object.create(null);
    for (let prop in this.nodes) {
      if (prop in this.marks)
        throw new RangeError(prop + " can not be both a node and a mark");
      let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks;
      type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
      type.inlineContent = type.contentMatch.inlineContent;
      if (type.spec.linebreakReplacement) {
        if (this.linebreakReplacement)
          throw new RangeError("Multiple linebreak nodes defined");
        if (!type.isInline || !type.isLeaf)
          throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");
        this.linebreakReplacement = type;
      }
      type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null;
    }
    for (let prop in this.marks) {
      let type = this.marks[prop], excl = type.spec.excludes;
      type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" "));
    }
    this.nodeFromJSON = (json) => Node2.fromJSON(this, json);
    this.markFromJSON = (json) => Mark.fromJSON(this, json);
    this.topNodeType = this.nodes[this.spec.topNode || "doc"];
    this.cached.wrappings = /* @__PURE__ */ Object.create(null);
  }
  /**
  Create a node in this schema. The `type` may be a string or a
  `NodeType` instance. Attributes will be extended with defaults,
  `content` may be a `Fragment`, `null`, a `Node`, or an array of
  nodes.
  */
  node(type, attrs = null, content5, marks) {
    if (typeof type == "string")
      type = this.nodeType(type);
    else if (!(type instanceof NodeType))
      throw new RangeError("Invalid node type: " + type);
    else if (type.schema != this)
      throw new RangeError("Node type from different schema used (" + type.name + ")");
    return type.createChecked(attrs, content5, marks);
  }
  /**
  Create a text node in the schema. Empty text nodes are not
  allowed.
  */
  text(text10, marks) {
    let type = this.nodes.text;
    return new TextNode(type, type.defaultAttrs, text10, Mark.setFrom(marks));
  }
  /**
  Create a mark with the given type and attributes.
  */
  mark(type, attrs) {
    if (typeof type == "string")
      type = this.marks[type];
    return type.create(attrs);
  }
  /**
  @internal
  */
  nodeType(name) {
    let found2 = this.nodes[name];
    if (!found2)
      throw new RangeError("Unknown node type: " + name);
    return found2;
  }
};
function gatherMarks(schema, marks) {
  let found2 = [];
  for (let i3 = 0; i3 < marks.length; i3++) {
    let name = marks[i3], mark2 = schema.marks[name], ok3 = mark2;
    if (mark2) {
      found2.push(mark2);
    } else {
      for (let prop in schema.marks) {
        let mark3 = schema.marks[prop];
        if (name == "_" || mark3.spec.group && mark3.spec.group.split(" ").indexOf(name) > -1)
          found2.push(ok3 = mark3);
      }
    }
    if (!ok3)
      throw new SyntaxError("Unknown mark type: '" + marks[i3] + "'");
  }
  return found2;
}
function isTagRule(rule) {
  return rule.tag != null;
}
function isStyleRule(rule) {
  return rule.style != null;
}
var DOMParser2 = class _DOMParser {
  /**
  Create a parser that targets the given schema, using the given
  parsing rules.
  */
  constructor(schema, rules) {
    this.schema = schema;
    this.rules = rules;
    this.tags = [];
    this.styles = [];
    let matchedStyles = this.matchedStyles = [];
    rules.forEach((rule) => {
      if (isTagRule(rule)) {
        this.tags.push(rule);
      } else if (isStyleRule(rule)) {
        let prop = /[^=]*/.exec(rule.style)[0];
        if (matchedStyles.indexOf(prop) < 0)
          matchedStyles.push(prop);
        this.styles.push(rule);
      }
    });
    this.normalizeLists = !this.tags.some((r4) => {
      if (!/^(ul|ol)\b/.test(r4.tag) || !r4.node)
        return false;
      let node2 = schema.nodes[r4.node];
      return node2.contentMatch.matchType(node2);
    });
  }
  /**
  Parse a document from the content of a DOM node.
  */
  parse(dom, options2 = {}) {
    let context = new ParseContext(this, options2, false);
    context.addAll(dom, Mark.none, options2.from, options2.to);
    return context.finish();
  }
  /**
  Parses the content of the given DOM node, like
  [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of
  options. But unlike that method, which produces a whole node,
  this one returns a slice that is open at the sides, meaning that
  the schema constraints aren't applied to the start of nodes to
  the left of the input and the end of nodes at the end.
  */
  parseSlice(dom, options2 = {}) {
    let context = new ParseContext(this, options2, true);
    context.addAll(dom, Mark.none, options2.from, options2.to);
    return Slice.maxOpen(context.finish());
  }
  /**
  @internal
  */
  matchTag(dom, context, after) {
    for (let i3 = after ? this.tags.indexOf(after) + 1 : 0; i3 < this.tags.length; i3++) {
      let rule = this.tags[i3];
      if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) {
        if (rule.getAttrs) {
          let result = rule.getAttrs(dom);
          if (result === false)
            continue;
          rule.attrs = result || void 0;
        }
        return rule;
      }
    }
  }
  /**
  @internal
  */
  matchStyle(prop, value, context, after) {
    for (let i3 = after ? this.styles.indexOf(after) + 1 : 0; i3 < this.styles.length; i3++) {
      let rule = this.styles[i3], style3 = rule.style;
      if (style3.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop,
      // or has an '=' sign after the prop, followed by the given
      // value.
      style3.length > prop.length && (style3.charCodeAt(prop.length) != 61 || style3.slice(prop.length + 1) != value))
        continue;
      if (rule.getAttrs) {
        let result = rule.getAttrs(value);
        if (result === false)
          continue;
        rule.attrs = result || void 0;
      }
      return rule;
    }
  }
  /**
  @internal
  */
  static schemaRules(schema) {
    let result = [];
    function insert(rule) {
      let priority = rule.priority == null ? 50 : rule.priority, i3 = 0;
      for (; i3 < result.length; i3++) {
        let next2 = result[i3], nextPriority = next2.priority == null ? 50 : next2.priority;
        if (nextPriority < priority)
          break;
      }
      result.splice(i3, 0, rule);
    }
    for (let name in schema.marks) {
      let rules = schema.marks[name].spec.parseDOM;
      if (rules)
        rules.forEach((rule) => {
          insert(rule = copy(rule));
          if (!(rule.mark || rule.ignore || rule.clearMark))
            rule.mark = name;
        });
    }
    for (let name in schema.nodes) {
      let rules = schema.nodes[name].spec.parseDOM;
      if (rules)
        rules.forEach((rule) => {
          insert(rule = copy(rule));
          if (!(rule.node || rule.ignore || rule.mark))
            rule.node = name;
        });
    }
    return result;
  }
  /**
  Construct a DOM parser using the parsing rules listed in a
  schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by
  [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority).
  */
  static fromSchema(schema) {
    return schema.cached.domParser || (schema.cached.domParser = new _DOMParser(schema, _DOMParser.schemaRules(schema)));
  }
};
var blockTags = {
  address: true,
  article: true,
  aside: true,
  blockquote: true,
  canvas: true,
  dd: true,
  div: true,
  dl: true,
  fieldset: true,
  figcaption: true,
  figure: true,
  footer: true,
  form: true,
  h1: true,
  h2: true,
  h3: true,
  h4: true,
  h5: true,
  h6: true,
  header: true,
  hgroup: true,
  hr: true,
  li: true,
  noscript: true,
  ol: true,
  output: true,
  p: true,
  pre: true,
  section: true,
  table: true,
  tfoot: true,
  ul: true
};
var ignoreTags = {
  head: true,
  noscript: true,
  object: true,
  script: true,
  style: true,
  title: true
};
var listTags = { ol: true, ul: true };
var OPT_PRESERVE_WS = 1;
var OPT_PRESERVE_WS_FULL = 2;
var OPT_OPEN_LEFT = 4;
function wsOptionsFor(type, preserveWhitespace, base4) {
  if (preserveWhitespace != null)
    return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0);
  return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base4 & ~OPT_OPEN_LEFT;
}
var NodeContext = class {
  constructor(type, attrs, marks, solid, match2, options2) {
    this.type = type;
    this.attrs = attrs;
    this.marks = marks;
    this.solid = solid;
    this.options = options2;
    this.content = [];
    this.activeMarks = Mark.none;
    this.match = match2 || (options2 & OPT_OPEN_LEFT ? null : type.contentMatch);
  }
  findWrapping(node2) {
    if (!this.match) {
      if (!this.type)
        return [];
      let fill = this.type.contentMatch.fillBefore(Fragment.from(node2));
      if (fill) {
        this.match = this.type.contentMatch.matchFragment(fill);
      } else {
        let start = this.type.contentMatch, wrap5;
        if (wrap5 = start.findWrapping(node2.type)) {
          this.match = start;
          return wrap5;
        } else {
          return null;
        }
      }
    }
    return this.match.findWrapping(node2.type);
  }
  finish(openEnd) {
    if (!(this.options & OPT_PRESERVE_WS)) {
      let last2 = this.content[this.content.length - 1], m2;
      if (last2 && last2.isText && (m2 = /[ \t\r\n\u000c]+$/.exec(last2.text))) {
        let text10 = last2;
        if (last2.text.length == m2[0].length)
          this.content.pop();
        else
          this.content[this.content.length - 1] = text10.withText(text10.text.slice(0, text10.text.length - m2[0].length));
      }
    }
    let content5 = Fragment.from(this.content);
    if (!openEnd && this.match)
      content5 = content5.append(this.match.fillBefore(Fragment.empty, true));
    return this.type ? this.type.create(this.attrs, content5, this.marks) : content5;
  }
  inlineContext(node2) {
    if (this.type)
      return this.type.inlineContent;
    if (this.content.length)
      return this.content[0].isInline;
    return node2.parentNode && !blockTags.hasOwnProperty(node2.parentNode.nodeName.toLowerCase());
  }
};
var ParseContext = class {
  constructor(parser, options2, isOpen) {
    this.parser = parser;
    this.options = options2;
    this.isOpen = isOpen;
    this.open = 0;
    this.localPreserveWS = false;
    let topNode = options2.topNode, topContext;
    let topOptions = wsOptionsFor(null, options2.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);
    if (topNode)
      topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options2.topMatch || topNode.type.contentMatch, topOptions);
    else if (isOpen)
      topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);
    else
      topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);
    this.nodes = [topContext];
    this.find = options2.findPositions;
    this.needsBlock = false;
  }
  get top() {
    return this.nodes[this.open];
  }
  // Add a DOM node to the content. Text is inserted as text node,
  // otherwise, the node is passed to `addElement` or, if it has a
  // `style` attribute, `addElementWithStyles`.
  addDOM(dom, marks) {
    if (dom.nodeType == 3)
      this.addTextNode(dom, marks);
    else if (dom.nodeType == 1)
      this.addElement(dom, marks);
  }
  addTextNode(dom, marks) {
    let value = dom.nodeValue;
    let top = this.top, preserveWS = top.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;
    let { schema } = this.parser;
    if (preserveWS === "full" || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) {
      if (!preserveWS) {
        value = value.replace(/[ \t\r\n\u000c]+/g, " ");
        if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) {
          let nodeBefore = top.content[top.content.length - 1];
          let domNodeBefore = dom.previousSibling;
          if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text))
            value = value.slice(1);
        }
      } else if (preserveWS === "full") {
        value = value.replace(/\r\n?/g, "\n");
      } else if (schema.linebreakReplacement && /[\r\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) {
        let lines = value.split(/\r?\n|\r/);
        for (let i3 = 0; i3 < lines.length; i3++) {
          if (i3)
            this.insertNode(schema.linebreakReplacement.create(), marks, true);
          if (lines[i3])
            this.insertNode(schema.text(lines[i3]), marks, !/\S/.test(lines[i3]));
        }
        value = "";
      } else {
        value = value.replace(/\r?\n|\r/g, " ");
      }
      if (value)
        this.insertNode(schema.text(value), marks, !/\S/.test(value));
      this.findInText(dom);
    } else {
      this.findInside(dom);
    }
  }
  // Try to find a handler for the given tag and use that to parse. If
  // none is found, the element's content nodes are added directly.
  addElement(dom, marks, matchAfter) {
    let outerWS = this.localPreserveWS, top = this.top;
    if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace))
      this.localPreserveWS = true;
    let name = dom.nodeName.toLowerCase(), ruleID;
    if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)
      normalizeList(dom);
    let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter));
    out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {
      this.findInside(dom);
      this.ignoreFallback(dom, marks);
    } else if (!rule || rule.skip || rule.closeParent) {
      if (rule && rule.closeParent)
        this.open = Math.max(0, this.open - 1);
      else if (rule && rule.skip.nodeType)
        dom = rule.skip;
      let sync, oldNeedsBlock = this.needsBlock;
      if (blockTags.hasOwnProperty(name)) {
        if (top.content.length && top.content[0].isInline && this.open) {
          this.open--;
          top = this.top;
        }
        sync = true;
        if (!top.type)
          this.needsBlock = true;
      } else if (!dom.firstChild) {
        this.leafFallback(dom, marks);
        break out;
      }
      let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);
      if (innerMarks)
        this.addAll(dom, innerMarks);
      if (sync)
        this.sync(top);
      this.needsBlock = oldNeedsBlock;
    } else {
      let innerMarks = this.readStyles(dom, marks);
      if (innerMarks)
        this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0);
    }
    this.localPreserveWS = outerWS;
  }
  // Called for leaf DOM nodes that would otherwise be ignored
  leafFallback(dom, marks) {
    if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent)
      this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks);
  }
  // Called for ignored nodes
  ignoreFallback(dom, marks) {
    if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent))
      this.findPlace(this.parser.schema.text("-"), marks, true);
  }
  // Run any style parser associated with the node's styles. Either
  // return an updated array of marks, or null to indicate some of the
  // styles had a rule with `ignore` set.
  readStyles(dom, marks) {
    let styles = dom.style;
    if (styles && styles.length)
      for (let i3 = 0; i3 < this.parser.matchedStyles.length; i3++) {
        let name = this.parser.matchedStyles[i3], value = styles.getPropertyValue(name);
        if (value)
          for (let after = void 0; ; ) {
            let rule = this.parser.matchStyle(name, value, this, after);
            if (!rule)
              break;
            if (rule.ignore)
              return null;
            if (rule.clearMark)
              marks = marks.filter((m2) => !rule.clearMark(m2));
            else
              marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));
            if (rule.consuming === false)
              after = rule;
            else
              break;
          }
      }
    return marks;
  }
  // Look up a handler for the given node. If none are found, return
  // false. Otherwise, apply it, use its return value to drive the way
  // the node's content is wrapped, and return true.
  addElementByRule(dom, rule, marks, continueAfter) {
    let sync, nodeType;
    if (rule.node) {
      nodeType = this.parser.schema.nodes[rule.node];
      if (!nodeType.isLeaf) {
        let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);
        if (inner) {
          sync = true;
          marks = inner;
        }
      } else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == "BR")) {
        this.leafFallback(dom, marks);
      }
    } else {
      let markType = this.parser.schema.marks[rule.mark];
      marks = marks.concat(markType.create(rule.attrs));
    }
    let startIn = this.top;
    if (nodeType && nodeType.isLeaf) {
      this.findInside(dom);
    } else if (continueAfter) {
      this.addElement(dom, marks, continueAfter);
    } else if (rule.getContent) {
      this.findInside(dom);
      rule.getContent(dom, this.parser.schema).forEach((node2) => this.insertNode(node2, marks, false));
    } else {
      let contentDOM = dom;
      if (typeof rule.contentElement == "string")
        contentDOM = dom.querySelector(rule.contentElement);
      else if (typeof rule.contentElement == "function")
        contentDOM = rule.contentElement(dom);
      else if (rule.contentElement)
        contentDOM = rule.contentElement;
      this.findAround(dom, contentDOM, true);
      this.addAll(contentDOM, marks);
      this.findAround(dom, contentDOM, false);
    }
    if (sync && this.sync(startIn))
      this.open--;
  }
  // Add all child nodes between `startIndex` and `endIndex` (or the
  // whole node, if not given). If `sync` is passed, use it to
  // synchronize after every block element.
  addAll(parent, marks, startIndex, endIndex) {
    let index4 = startIndex || 0;
    for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index4) {
      this.findAtPoint(parent, index4);
      this.addDOM(dom, marks);
    }
    this.findAtPoint(parent, index4);
  }
  // Try to find a way to fit the given node type into the current
  // context. May add intermediate wrappers and/or leave non-solid
  // nodes that we're in.
  findPlace(node2, marks, cautious) {
    let route, sync;
    for (let depth = this.open, penalty = 0; depth >= 0; depth--) {
      let cx = this.nodes[depth];
      let found2 = cx.findWrapping(node2);
      if (found2 && (!route || route.length > found2.length + penalty)) {
        route = found2;
        sync = cx;
        if (!found2.length)
          break;
      }
      if (cx.solid) {
        if (cautious)
          break;
        penalty += 2;
      }
    }
    if (!route)
      return null;
    this.sync(sync);
    for (let i3 = 0; i3 < route.length; i3++)
      marks = this.enterInner(route[i3], null, marks, false);
    return marks;
  }
  // Try to insert the given node, adjusting the context when needed.
  insertNode(node2, marks, cautious) {
    if (node2.isInline && this.needsBlock && !this.top.type) {
      let block = this.textblockFromContext();
      if (block)
        marks = this.enterInner(block, null, marks);
    }
    let innerMarks = this.findPlace(node2, marks, cautious);
    if (innerMarks) {
      this.closeExtra();
      let top = this.top;
      if (top.match)
        top.match = top.match.matchType(node2.type);
      let nodeMarks = Mark.none;
      for (let m2 of innerMarks.concat(node2.marks))
        if (top.type ? top.type.allowsMarkType(m2.type) : markMayApply(m2.type, node2.type))
          nodeMarks = m2.addToSet(nodeMarks);
      top.content.push(node2.mark(nodeMarks));
      return true;
    }
    return false;
  }
  // Try to start a node of the given type, adjusting the context when
  // necessary.
  enter(type, attrs, marks, preserveWS) {
    let innerMarks = this.findPlace(type.create(attrs), marks, false);
    if (innerMarks)
      innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);
    return innerMarks;
  }
  // Open a node of the given type
  enterInner(type, attrs, marks, solid = false, preserveWS) {
    this.closeExtra();
    let top = this.top;
    top.match = top.match && top.match.matchType(type);
    let options2 = wsOptionsFor(type, preserveWS, top.options);
    if (top.options & OPT_OPEN_LEFT && top.content.length == 0)
      options2 |= OPT_OPEN_LEFT;
    let applyMarks = Mark.none;
    marks = marks.filter((m2) => {
      if (top.type ? top.type.allowsMarkType(m2.type) : markMayApply(m2.type, type)) {
        applyMarks = m2.addToSet(applyMarks);
        return false;
      }
      return true;
    });
    this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options2));
    this.open++;
    return marks;
  }
  // Make sure all nodes above this.open are finished and added to
  // their parents
  closeExtra(openEnd = false) {
    let i3 = this.nodes.length - 1;
    if (i3 > this.open) {
      for (; i3 > this.open; i3--)
        this.nodes[i3 - 1].content.push(this.nodes[i3].finish(openEnd));
      this.nodes.length = this.open + 1;
    }
  }
  finish() {
    this.open = 0;
    this.closeExtra(this.isOpen);
    return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));
  }
  sync(to2) {
    for (let i3 = this.open; i3 >= 0; i3--) {
      if (this.nodes[i3] == to2) {
        this.open = i3;
        return true;
      } else if (this.localPreserveWS) {
        this.nodes[i3].options |= OPT_PRESERVE_WS;
      }
    }
    return false;
  }
  get currentPos() {
    this.closeExtra();
    let pos = 0;
    for (let i3 = this.open; i3 >= 0; i3--) {
      let content5 = this.nodes[i3].content;
      for (let j4 = content5.length - 1; j4 >= 0; j4--)
        pos += content5[j4].nodeSize;
      if (i3)
        pos++;
    }
    return pos;
  }
  findAtPoint(parent, offset4) {
    if (this.find)
      for (let i3 = 0; i3 < this.find.length; i3++) {
        if (this.find[i3].node == parent && this.find[i3].offset == offset4)
          this.find[i3].pos = this.currentPos;
      }
  }
  findInside(parent) {
    if (this.find)
      for (let i3 = 0; i3 < this.find.length; i3++) {
        if (this.find[i3].pos == null && parent.nodeType == 1 && parent.contains(this.find[i3].node))
          this.find[i3].pos = this.currentPos;
      }
  }
  findAround(parent, content5, before) {
    if (parent != content5 && this.find)
      for (let i3 = 0; i3 < this.find.length; i3++) {
        if (this.find[i3].pos == null && parent.nodeType == 1 && parent.contains(this.find[i3].node)) {
          let pos = content5.compareDocumentPosition(this.find[i3].node);
          if (pos & (before ? 2 : 4))
            this.find[i3].pos = this.currentPos;
        }
      }
  }
  findInText(textNode) {
    if (this.find)
      for (let i3 = 0; i3 < this.find.length; i3++) {
        if (this.find[i3].node == textNode)
          this.find[i3].pos = this.currentPos - (textNode.nodeValue.length - this.find[i3].offset);
      }
  }
  // Determines whether the given context string matches this context.
  matchesContext(context) {
    if (context.indexOf("|") > -1)
      return context.split(/\s*\|\s*/).some(this.matchesContext, this);
    let parts = context.split("/");
    let option2 = this.options.context;
    let useRoot = !this.isOpen && (!option2 || option2.parent.type == this.nodes[0].type);
    let minDepth = -(option2 ? option2.depth + 1 : 0) + (useRoot ? 0 : 1);
    let match2 = (i3, depth) => {
      for (; i3 >= 0; i3--) {
        let part = parts[i3];
        if (part == "") {
          if (i3 == parts.length - 1 || i3 == 0)
            continue;
          for (; depth >= minDepth; depth--)
            if (match2(i3 - 1, depth))
              return true;
          return false;
        } else {
          let next2 = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option2 && depth >= minDepth ? option2.node(depth - minDepth).type : null;
          if (!next2 || next2.name != part && !next2.isInGroup(part))
            return false;
          depth--;
        }
      }
      return true;
    };
    return match2(parts.length - 1, this.open);
  }
  textblockFromContext() {
    let $context = this.options.context;
    if ($context)
      for (let d = $context.depth; d >= 0; d--) {
        let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType;
        if (deflt && deflt.isTextblock && deflt.defaultAttrs)
          return deflt;
      }
    for (let name in this.parser.schema.nodes) {
      let type = this.parser.schema.nodes[name];
      if (type.isTextblock && type.defaultAttrs)
        return type;
    }
  }
};
function normalizeList(dom) {
  for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {
    let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;
    if (name && listTags.hasOwnProperty(name) && prevItem) {
      prevItem.appendChild(child);
      child = prevItem;
    } else if (name == "li") {
      prevItem = child;
    } else if (name) {
      prevItem = null;
    }
  }
}
function matches(dom, selector) {
  return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);
}
function copy(obj) {
  let copy3 = {};
  for (let prop in obj)
    copy3[prop] = obj[prop];
  return copy3;
}
function markMayApply(markType, nodeType) {
  let nodes = nodeType.schema.nodes;
  for (let name in nodes) {
    let parent = nodes[name];
    if (!parent.allowsMarkType(markType))
      continue;
    let seen = [], scan = (match2) => {
      seen.push(match2);
      for (let i3 = 0; i3 < match2.edgeCount; i3++) {
        let { type, next: next2 } = match2.edge(i3);
        if (type == nodeType)
          return true;
        if (seen.indexOf(next2) < 0 && scan(next2))
          return true;
      }
    };
    if (scan(parent.contentMatch))
      return true;
  }
}
var DOMSerializer = class _DOMSerializer {
  /**
  Create a serializer. `nodes` should map node names to functions
  that take a node and return a description of the corresponding
  DOM. `marks` does the same for mark names, but also gets an
  argument that tells it whether the mark's content is block or
  inline content (for typical use, it'll always be inline). A mark
  serializer may be `null` to indicate that marks of that type
  should not be serialized.
  */
  constructor(nodes, marks) {
    this.nodes = nodes;
    this.marks = marks;
  }
  /**
  Serialize the content of this fragment to a DOM fragment. When
  not in the browser, the `document` option, containing a DOM
  document, should be passed so that the serializer can create
  nodes.
  */
  serializeFragment(fragment, options2 = {}, target) {
    if (!target)
      target = doc(options2).createDocumentFragment();
    let top = target, active = [];
    fragment.forEach((node2) => {
      if (active.length || node2.marks.length) {
        let keep = 0, rendered = 0;
        while (keep < active.length && rendered < node2.marks.length) {
          let next2 = node2.marks[rendered];
          if (!this.marks[next2.type.name]) {
            rendered++;
            continue;
          }
          if (!next2.eq(active[keep][0]) || next2.type.spec.spanning === false)
            break;
          keep++;
          rendered++;
        }
        while (keep < active.length)
          top = active.pop()[1];
        while (rendered < node2.marks.length) {
          let add = node2.marks[rendered++];
          let markDOM = this.serializeMark(add, node2.isInline, options2);
          if (markDOM) {
            active.push([add, top]);
            top.appendChild(markDOM.dom);
            top = markDOM.contentDOM || markDOM.dom;
          }
        }
      }
      top.appendChild(this.serializeNodeInner(node2, options2));
    });
    return target;
  }
  /**
  @internal
  */
  serializeNodeInner(node2, options2) {
    let { dom, contentDOM } = renderSpec(doc(options2), this.nodes[node2.type.name](node2), null, node2.attrs);
    if (contentDOM) {
      if (node2.isLeaf)
        throw new RangeError("Content hole not allowed in a leaf node spec");
      this.serializeFragment(node2.content, options2, contentDOM);
    }
    return dom;
  }
  /**
  Serialize this node to a DOM node. This can be useful when you
  need to serialize a part of a document, as opposed to the whole
  document. To serialize a whole document, use
  [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on
  its [content](https://prosemirror.net/docs/ref/#model.Node.content).
  */
  serializeNode(node2, options2 = {}) {
    let dom = this.serializeNodeInner(node2, options2);
    for (let i3 = node2.marks.length - 1; i3 >= 0; i3--) {
      let wrap5 = this.serializeMark(node2.marks[i3], node2.isInline, options2);
      if (wrap5) {
        (wrap5.contentDOM || wrap5.dom).appendChild(dom);
        dom = wrap5.dom;
      }
    }
    return dom;
  }
  /**
  @internal
  */
  serializeMark(mark2, inline4, options2 = {}) {
    let toDOM = this.marks[mark2.type.name];
    return toDOM && renderSpec(doc(options2), toDOM(mark2, inline4), null, mark2.attrs);
  }
  static renderSpec(doc4, structure, xmlNS = null, blockArraysIn) {
    return renderSpec(doc4, structure, xmlNS, blockArraysIn);
  }
  /**
  Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)
  properties in a schema's node and mark specs.
  */
  static fromSchema(schema) {
    return schema.cached.domSerializer || (schema.cached.domSerializer = new _DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));
  }
  /**
  Gather the serializers in a schema's node specs into an object.
  This can be useful as a base to build a custom serializer from.
  */
  static nodesFromSchema(schema) {
    let result = gatherToDOM(schema.nodes);
    if (!result.text)
      result.text = (node2) => node2.text;
    return result;
  }
  /**
  Gather the serializers in a schema's mark specs into an object.
  */
  static marksFromSchema(schema) {
    return gatherToDOM(schema.marks);
  }
};
function gatherToDOM(obj) {
  let result = {};
  for (let name in obj) {
    let toDOM = obj[name].spec.toDOM;
    if (toDOM)
      result[name] = toDOM;
  }
  return result;
}
function doc(options2) {
  return options2.document || window.document;
}
var suspiciousAttributeCache = /* @__PURE__ */ new WeakMap();
function suspiciousAttributes(attrs) {
  let value = suspiciousAttributeCache.get(attrs);
  if (value === void 0)
    suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));
  return value;
}
function suspiciousAttributesInner(attrs) {
  let result = null;
  function scan(value) {
    if (value && typeof value == "object") {
      if (Array.isArray(value)) {
        if (typeof value[0] == "string") {
          if (!result)
            result = [];
          result.push(value);
        } else {
          for (let i3 = 0; i3 < value.length; i3++)
            scan(value[i3]);
        }
      } else {
        for (let prop in value)
          scan(value[prop]);
      }
    }
  }
  scan(attrs);
  return result;
}
function renderSpec(doc4, structure, xmlNS, blockArraysIn) {
  if (typeof structure == "string")
    return { dom: doc4.createTextNode(structure) };
  if (structure.nodeType != null)
    return { dom: structure };
  if (structure.dom && structure.dom.nodeType != null)
    return structure;
  let tagName = structure[0], suspicious;
  if (typeof tagName != "string")
    throw new RangeError("Invalid array passed to renderSpec");
  if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1)
    throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");
  let space2 = tagName.indexOf(" ");
  if (space2 > 0) {
    xmlNS = tagName.slice(0, space2);
    tagName = tagName.slice(space2 + 1);
  }
  let contentDOM;
  let dom = xmlNS ? doc4.createElementNS(xmlNS, tagName) : doc4.createElement(tagName);
  let attrs = structure[1], start = 1;
  if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) {
    start = 2;
    for (let name in attrs)
      if (attrs[name] != null) {
        let space3 = name.indexOf(" ");
        if (space3 > 0)
          dom.setAttributeNS(name.slice(0, space3), name.slice(space3 + 1), attrs[name]);
        else if (name == "style" && dom.style)
          dom.style.cssText = attrs[name];
        else
          dom.setAttribute(name, attrs[name]);
      }
  }
  for (let i3 = start; i3 < structure.length; i3++) {
    let child = structure[i3];
    if (child === 0) {
      if (i3 < structure.length - 1 || i3 > start)
        throw new RangeError("Content hole must be the only child of its parent node");
      return { dom, contentDOM: dom };
    } else {
      let { dom: inner, contentDOM: innerContent } = renderSpec(doc4, child, xmlNS, blockArraysIn);
      dom.appendChild(inner);
      if (innerContent) {
        if (contentDOM)
          throw new RangeError("Multiple content holes");
        contentDOM = innerContent;
      }
    }
  }
  return { dom, contentDOM };
}

// ../../node_modules/.pnpm/prosemirror-transform@1.10.5/node_modules/prosemirror-transform/dist/index.js
var lower16 = 65535;
var factor16 = Math.pow(2, 16);
function makeRecover(index4, offset4) {
  return index4 + offset4 * factor16;
}
function recoverIndex(value) {
  return value & lower16;
}
function recoverOffset(value) {
  return (value - (value & lower16)) / factor16;
}
var DEL_BEFORE = 1;
var DEL_AFTER = 2;
var DEL_ACROSS = 4;
var DEL_SIDE = 8;
var MapResult = class {
  /**
  @internal
  */
  constructor(pos, delInfo, recover) {
    this.pos = pos;
    this.delInfo = delInfo;
    this.recover = recover;
  }
  /**
  Tells you whether the position was deleted, that is, whether the
  step removed the token on the side queried (via the `assoc`)
  argument from the document.
  */
  get deleted() {
    return (this.delInfo & DEL_SIDE) > 0;
  }
  /**
  Tells you whether the token before the mapped position was deleted.
  */
  get deletedBefore() {
    return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0;
  }
  /**
  True when the token after the mapped position was deleted.
  */
  get deletedAfter() {
    return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0;
  }
  /**
  Tells whether any of the steps mapped through deletes across the
  position (including both the token before and after the
  position).
  */
  get deletedAcross() {
    return (this.delInfo & DEL_ACROSS) > 0;
  }
};
var StepMap = class _StepMap {
  /**
  Create a position map. The modifications to the document are
  represented as an array of numbers, in which each group of three
  represents a modified chunk as `[start, oldSize, newSize]`.
  */
  constructor(ranges, inverted = false) {
    this.ranges = ranges;
    this.inverted = inverted;
    if (!ranges.length && _StepMap.empty)
      return _StepMap.empty;
  }
  /**
  @internal
  */
  recover(value) {
    let diff = 0, index4 = recoverIndex(value);
    if (!this.inverted)
      for (let i3 = 0; i3 < index4; i3++)
        diff += this.ranges[i3 * 3 + 2] - this.ranges[i3 * 3 + 1];
    return this.ranges[index4 * 3] + diff + recoverOffset(value);
  }
  mapResult(pos, assoc = 1) {
    return this._map(pos, assoc, false);
  }
  map(pos, assoc = 1) {
    return this._map(pos, assoc, true);
  }
  /**
  @internal
  */
  _map(pos, assoc, simple) {
    let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i3 = 0; i3 < this.ranges.length; i3 += 3) {
      let start = this.ranges[i3] - (this.inverted ? diff : 0);
      if (start > pos)
        break;
      let oldSize = this.ranges[i3 + oldIndex], newSize = this.ranges[i3 + newIndex], end = start + oldSize;
      if (pos <= end) {
        let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;
        let result = start + diff + (side < 0 ? 0 : newSize);
        if (simple)
          return result;
        let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i3 / 3, pos - start);
        let del3 = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;
        if (assoc < 0 ? pos != start : pos != end)
          del3 |= DEL_SIDE;
        return new MapResult(result, del3, recover);
      }
      diff += newSize - oldSize;
    }
    return simple ? pos + diff : new MapResult(pos + diff, 0, null);
  }
  /**
  @internal
  */
  touches(pos, recover) {
    let diff = 0, index4 = recoverIndex(recover);
    let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i3 = 0; i3 < this.ranges.length; i3 += 3) {
      let start = this.ranges[i3] - (this.inverted ? diff : 0);
      if (start > pos)
        break;
      let oldSize = this.ranges[i3 + oldIndex], end = start + oldSize;
      if (pos <= end && i3 == index4 * 3)
        return true;
      diff += this.ranges[i3 + newIndex] - oldSize;
    }
    return false;
  }
  /**
  Calls the given function on each of the changed ranges included in
  this map.
  */
  forEach(f6) {
    let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i3 = 0, diff = 0; i3 < this.ranges.length; i3 += 3) {
      let start = this.ranges[i3], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);
      let oldSize = this.ranges[i3 + oldIndex], newSize = this.ranges[i3 + newIndex];
      f6(oldStart, oldStart + oldSize, newStart, newStart + newSize);
      diff += newSize - oldSize;
    }
  }
  /**
  Create an inverted version of this map. The result can be used to
  map positions in the post-step document to the pre-step document.
  */
  invert() {
    return new _StepMap(this.ranges, !this.inverted);
  }
  /**
  @internal
  */
  toString() {
    return (this.inverted ? "-" : "") + JSON.stringify(this.ranges);
  }
  /**
  Create a map that moves all positions by offset `n` (which may be
  negative). This can be useful when applying steps meant for a
  sub-document to a larger document, or vice-versa.
  */
  static offset(n) {
    return n == 0 ? _StepMap.empty : new _StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);
  }
};
StepMap.empty = new StepMap([]);
var Mapping = class _Mapping {
  /**
  Create a new mapping with the given position maps.
  */
  constructor(maps, mirror, from4 = 0, to2 = maps ? maps.length : 0) {
    this.mirror = mirror;
    this.from = from4;
    this.to = to2;
    this._maps = maps || [];
    this.ownData = !(maps || mirror);
  }
  /**
  The step maps in this mapping.
  */
  get maps() {
    return this._maps;
  }
  /**
  Create a mapping that maps only through a part of this one.
  */
  slice(from4 = 0, to2 = this.maps.length) {
    return new _Mapping(this._maps, this.mirror, from4, to2);
  }
  /**
  Add a step map to the end of this mapping. If `mirrors` is
  given, it should be the index of the step map that is the mirror
  image of this one.
  */
  appendMap(map7, mirrors) {
    if (!this.ownData) {
      this._maps = this._maps.slice();
      this.mirror = this.mirror && this.mirror.slice();
      this.ownData = true;
    }
    this.to = this._maps.push(map7);
    if (mirrors != null)
      this.setMirror(this._maps.length - 1, mirrors);
  }
  /**
  Add all the step maps in a given mapping to this one (preserving
  mirroring information).
  */
  appendMapping(mapping) {
    for (let i3 = 0, startSize = this._maps.length; i3 < mapping._maps.length; i3++) {
      let mirr = mapping.getMirror(i3);
      this.appendMap(mapping._maps[i3], mirr != null && mirr < i3 ? startSize + mirr : void 0);
    }
  }
  /**
  Finds the offset of the step map that mirrors the map at the
  given offset, in this mapping (as per the second argument to
  `appendMap`).
  */
  getMirror(n) {
    if (this.mirror) {
      for (let i3 = 0; i3 < this.mirror.length; i3++)
        if (this.mirror[i3] == n)
          return this.mirror[i3 + (i3 % 2 ? -1 : 1)];
    }
  }
  /**
  @internal
  */
  setMirror(n, m2) {
    if (!this.mirror)
      this.mirror = [];
    this.mirror.push(n, m2);
  }
  /**
  Append the inverse of the given mapping to this one.
  */
  appendMappingInverted(mapping) {
    for (let i3 = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i3 >= 0; i3--) {
      let mirr = mapping.getMirror(i3);
      this.appendMap(mapping._maps[i3].invert(), mirr != null && mirr > i3 ? totalSize - mirr - 1 : void 0);
    }
  }
  /**
  Create an inverted version of this mapping.
  */
  invert() {
    let inverse = new _Mapping();
    inverse.appendMappingInverted(this);
    return inverse;
  }
  /**
  Map a position through this mapping.
  */
  map(pos, assoc = 1) {
    if (this.mirror)
      return this._map(pos, assoc, true);
    for (let i3 = this.from; i3 < this.to; i3++)
      pos = this._maps[i3].map(pos, assoc);
    return pos;
  }
  /**
  Map a position through this mapping, returning a mapping
  result.
  */
  mapResult(pos, assoc = 1) {
    return this._map(pos, assoc, false);
  }
  /**
  @internal
  */
  _map(pos, assoc, simple) {
    let delInfo = 0;
    for (let i3 = this.from; i3 < this.to; i3++) {
      let map7 = this._maps[i3], result = map7.mapResult(pos, assoc);
      if (result.recover != null) {
        let corr = this.getMirror(i3);
        if (corr != null && corr > i3 && corr < this.to) {
          i3 = corr;
          pos = this._maps[corr].recover(result.recover);
          continue;
        }
      }
      delInfo |= result.delInfo;
      pos = result.pos;
    }
    return simple ? pos : new MapResult(pos, delInfo, null);
  }
};
var stepsByID = /* @__PURE__ */ Object.create(null);
var Step = class {
  /**
  Get the step map that represents the changes made by this step,
  and which can be used to transform between positions in the old
  and the new document.
  */
  getMap() {
    return StepMap.empty;
  }
  /**
  Try to merge this step with another one, to be applied directly
  after it. Returns the merged step when possible, null if the
  steps can't be merged.
  */
  merge(other) {
    return null;
  }
  /**
  Deserialize a step from its JSON representation. Will call
  through to the step class' own implementation of this method.
  */
  static fromJSON(schema, json) {
    if (!json || !json.stepType)
      throw new RangeError("Invalid input for Step.fromJSON");
    let type = stepsByID[json.stepType];
    if (!type)
      throw new RangeError(`No step type ${json.stepType} defined`);
    return type.fromJSON(schema, json);
  }
  /**
  To be able to serialize steps to JSON, each step needs a string
  ID to attach to its JSON representation. Use this method to
  register an ID for your step classes. Try to pick something
  that's unlikely to clash with steps from other modules.
  */
  static jsonID(id2, stepClass) {
    if (id2 in stepsByID)
      throw new RangeError("Duplicate use of step JSON ID " + id2);
    stepsByID[id2] = stepClass;
    stepClass.prototype.jsonID = id2;
    return stepClass;
  }
};
var StepResult = class _StepResult {
  /**
  @internal
  */
  constructor(doc4, failed) {
    this.doc = doc4;
    this.failed = failed;
  }
  /**
  Create a successful step result.
  */
  static ok(doc4) {
    return new _StepResult(doc4, null);
  }
  /**
  Create a failed step result.
  */
  static fail(message) {
    return new _StepResult(null, message);
  }
  /**
  Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given
  arguments. Create a successful result if it succeeds, and a
  failed one if it throws a `ReplaceError`.
  */
  static fromReplace(doc4, from4, to2, slice2) {
    try {
      return _StepResult.ok(doc4.replace(from4, to2, slice2));
    } catch (e2) {
      if (e2 instanceof ReplaceError)
        return _StepResult.fail(e2.message);
      throw e2;
    }
  }
};
function mapFragment(fragment, f6, parent) {
  let mapped = [];
  for (let i3 = 0; i3 < fragment.childCount; i3++) {
    let child = fragment.child(i3);
    if (child.content.size)
      child = child.copy(mapFragment(child.content, f6, child));
    if (child.isInline)
      child = f6(child, parent, i3);
    mapped.push(child);
  }
  return Fragment.fromArray(mapped);
}
var AddMarkStep = class _AddMarkStep extends Step {
  /**
  Create a mark step.
  */
  constructor(from4, to2, mark2) {
    super();
    this.from = from4;
    this.to = to2;
    this.mark = mark2;
  }
  apply(doc4) {
    let oldSlice = doc4.slice(this.from, this.to), $from = doc4.resolve(this.from);
    let parent = $from.node($from.sharedDepth(this.to));
    let slice2 = new Slice(mapFragment(oldSlice.content, (node2, parent2) => {
      if (!node2.isAtom || !parent2.type.allowsMarkType(this.mark.type))
        return node2;
      return node2.mark(this.mark.addToSet(node2.marks));
    }, parent), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc4, this.from, this.to, slice2);
  }
  invert() {
    return new RemoveMarkStep(this.from, this.to, this.mark);
  }
  map(mapping) {
    let from4 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1);
    if (from4.deleted && to2.deleted || from4.pos >= to2.pos)
      return null;
    return new _AddMarkStep(from4.pos, to2.pos, this.mark);
  }
  merge(other) {
    if (other instanceof _AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from)
      return new _AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
    return null;
  }
  toJSON() {
    return {
      stepType: "addMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for AddMarkStep.fromJSON");
    return new _AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("addMark", AddMarkStep);
var RemoveMarkStep = class _RemoveMarkStep extends Step {
  /**
  Create a mark-removing step.
  */
  constructor(from4, to2, mark2) {
    super();
    this.from = from4;
    this.to = to2;
    this.mark = mark2;
  }
  apply(doc4) {
    let oldSlice = doc4.slice(this.from, this.to);
    let slice2 = new Slice(mapFragment(oldSlice.content, (node2) => {
      return node2.mark(this.mark.removeFromSet(node2.marks));
    }, doc4), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc4, this.from, this.to, slice2);
  }
  invert() {
    return new AddMarkStep(this.from, this.to, this.mark);
  }
  map(mapping) {
    let from4 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1);
    if (from4.deleted && to2.deleted || from4.pos >= to2.pos)
      return null;
    return new _RemoveMarkStep(from4.pos, to2.pos, this.mark);
  }
  merge(other) {
    if (other instanceof _RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from)
      return new _RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
    return null;
  }
  toJSON() {
    return {
      stepType: "removeMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");
    return new _RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("removeMark", RemoveMarkStep);
var AddNodeMarkStep = class _AddNodeMarkStep extends Step {
  /**
  Create a node mark step.
  */
  constructor(pos, mark2) {
    super();
    this.pos = pos;
    this.mark = mark2;
  }
  apply(doc4) {
    let node2 = doc4.nodeAt(this.pos);
    if (!node2)
      return StepResult.fail("No node at mark step's position");
    let updated = node2.type.create(node2.attrs, null, this.mark.addToSet(node2.marks));
    return StepResult.fromReplace(doc4, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node2.isLeaf ? 0 : 1));
  }
  invert(doc4) {
    let node2 = doc4.nodeAt(this.pos);
    if (node2) {
      let newSet = this.mark.addToSet(node2.marks);
      if (newSet.length == node2.marks.length) {
        for (let i3 = 0; i3 < node2.marks.length; i3++)
          if (!node2.marks[i3].isInSet(newSet))
            return new _AddNodeMarkStep(this.pos, node2.marks[i3]);
        return new _AddNodeMarkStep(this.pos, this.mark);
      }
    }
    return new RemoveNodeMarkStep(this.pos, this.mark);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new _AddNodeMarkStep(pos.pos, this.mark);
  }
  toJSON() {
    return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");
    return new _AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("addNodeMark", AddNodeMarkStep);
var RemoveNodeMarkStep = class _RemoveNodeMarkStep extends Step {
  /**
  Create a mark-removing step.
  */
  constructor(pos, mark2) {
    super();
    this.pos = pos;
    this.mark = mark2;
  }
  apply(doc4) {
    let node2 = doc4.nodeAt(this.pos);
    if (!node2)
      return StepResult.fail("No node at mark step's position");
    let updated = node2.type.create(node2.attrs, null, this.mark.removeFromSet(node2.marks));
    return StepResult.fromReplace(doc4, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node2.isLeaf ? 0 : 1));
  }
  invert(doc4) {
    let node2 = doc4.nodeAt(this.pos);
    if (!node2 || !this.mark.isInSet(node2.marks))
      return this;
    return new AddNodeMarkStep(this.pos, this.mark);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new _RemoveNodeMarkStep(pos.pos, this.mark);
  }
  toJSON() {
    return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");
    return new _RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("removeNodeMark", RemoveNodeMarkStep);
var ReplaceStep = class _ReplaceStep extends Step {
  /**
  The given `slice` should fit the 'gap' between `from` and
  `to`—the depths must line up, and the surrounding nodes must be
  able to be joined with the open sides of the slice. When
  `structure` is true, the step will fail if the content between
  from and to is not just a sequence of closing and then opening
  tokens (this is to guard against rebased replace steps
  overwriting something they weren't supposed to).
  */
  constructor(from4, to2, slice2, structure = false) {
    super();
    this.from = from4;
    this.to = to2;
    this.slice = slice2;
    this.structure = structure;
  }
  apply(doc4) {
    if (this.structure && contentBetween(doc4, this.from, this.to))
      return StepResult.fail("Structure replace would overwrite content");
    return StepResult.fromReplace(doc4, this.from, this.to, this.slice);
  }
  getMap() {
    return new StepMap([this.from, this.to - this.from, this.slice.size]);
  }
  invert(doc4) {
    return new _ReplaceStep(this.from, this.from + this.slice.size, doc4.slice(this.from, this.to));
  }
  map(mapping) {
    let from4 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1);
    if (from4.deletedAcross && to2.deletedAcross)
      return null;
    return new _ReplaceStep(from4.pos, Math.max(from4.pos, to2.pos), this.slice, this.structure);
  }
  merge(other) {
    if (!(other instanceof _ReplaceStep) || other.structure || this.structure)
      return null;
    if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {
      let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);
      return new _ReplaceStep(this.from, this.to + (other.to - other.from), slice2, this.structure);
    } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {
      let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);
      return new _ReplaceStep(other.from, this.to, slice2, this.structure);
    } else {
      return null;
    }
  }
  toJSON() {
    let json = { stepType: "replace", from: this.from, to: this.to };
    if (this.slice.size)
      json.slice = this.slice.toJSON();
    if (this.structure)
      json.structure = true;
    return json;
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for ReplaceStep.fromJSON");
    return new _ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);
  }
};
Step.jsonID("replace", ReplaceStep);
var ReplaceAroundStep = class _ReplaceAroundStep extends Step {
  /**
  Create a replace-around step with the given range and gap.
  `insert` should be the point in the slice into which the content
  of the gap should be moved. `structure` has the same meaning as
  it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.
  */
  constructor(from4, to2, gapFrom, gapTo, slice2, insert, structure = false) {
    super();
    this.from = from4;
    this.to = to2;
    this.gapFrom = gapFrom;
    this.gapTo = gapTo;
    this.slice = slice2;
    this.insert = insert;
    this.structure = structure;
  }
  apply(doc4) {
    if (this.structure && (contentBetween(doc4, this.from, this.gapFrom) || contentBetween(doc4, this.gapTo, this.to)))
      return StepResult.fail("Structure gap-replace would overwrite content");
    let gap = doc4.slice(this.gapFrom, this.gapTo);
    if (gap.openStart || gap.openEnd)
      return StepResult.fail("Gap is not a flat range");
    let inserted = this.slice.insertAt(this.insert, gap.content);
    if (!inserted)
      return StepResult.fail("Content does not fit in gap");
    return StepResult.fromReplace(doc4, this.from, this.to, inserted);
  }
  getMap() {
    return new StepMap([
      this.from,
      this.gapFrom - this.from,
      this.insert,
      this.gapTo,
      this.to - this.gapTo,
      this.slice.size - this.insert
    ]);
  }
  invert(doc4) {
    let gap = this.gapTo - this.gapFrom;
    return new _ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc4.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
  }
  map(mapping) {
    let from4 = mapping.mapResult(this.from, 1), to2 = mapping.mapResult(this.to, -1);
    let gapFrom = this.from == this.gapFrom ? from4.pos : mapping.map(this.gapFrom, -1);
    let gapTo = this.to == this.gapTo ? to2.pos : mapping.map(this.gapTo, 1);
    if (from4.deletedAcross && to2.deletedAcross || gapFrom < from4.pos || gapTo > to2.pos)
      return null;
    return new _ReplaceAroundStep(from4.pos, to2.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
  }
  toJSON() {
    let json = {
      stepType: "replaceAround",
      from: this.from,
      to: this.to,
      gapFrom: this.gapFrom,
      gapTo: this.gapTo,
      insert: this.insert
    };
    if (this.slice.size)
      json.slice = this.slice.toJSON();
    if (this.structure)
      json.structure = true;
    return json;
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number")
      throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
    return new _ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);
  }
};
Step.jsonID("replaceAround", ReplaceAroundStep);
function contentBetween(doc4, from4, to2) {
  let $from = doc4.resolve(from4), dist = to2 - from4, depth = $from.depth;
  while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {
    depth--;
    dist--;
  }
  if (dist > 0) {
    let next2 = $from.node(depth).maybeChild($from.indexAfter(depth));
    while (dist > 0) {
      if (!next2 || next2.isLeaf)
        return true;
      next2 = next2.firstChild;
      dist--;
    }
  }
  return false;
}
function addMark(tr4, from4, to2, mark2) {
  let removed = [], added = [];
  let removing, adding;
  tr4.doc.nodesBetween(from4, to2, (node2, pos, parent) => {
    if (!node2.isInline)
      return;
    let marks = node2.marks;
    if (!mark2.isInSet(marks) && parent.type.allowsMarkType(mark2.type)) {
      let start = Math.max(pos, from4), end = Math.min(pos + node2.nodeSize, to2);
      let newSet = mark2.addToSet(marks);
      for (let i3 = 0; i3 < marks.length; i3++) {
        if (!marks[i3].isInSet(newSet)) {
          if (removing && removing.to == start && removing.mark.eq(marks[i3]))
            removing.to = end;
          else
            removed.push(removing = new RemoveMarkStep(start, end, marks[i3]));
        }
      }
      if (adding && adding.to == start)
        adding.to = end;
      else
        added.push(adding = new AddMarkStep(start, end, mark2));
    }
  });
  removed.forEach((s2) => tr4.step(s2));
  added.forEach((s2) => tr4.step(s2));
}
function removeMark(tr4, from4, to2, mark2) {
  let matched = [], step = 0;
  tr4.doc.nodesBetween(from4, to2, (node2, pos) => {
    if (!node2.isInline)
      return;
    step++;
    let toRemove = null;
    if (mark2 instanceof MarkType) {
      let set = node2.marks, found2;
      while (found2 = mark2.isInSet(set)) {
        (toRemove || (toRemove = [])).push(found2);
        set = found2.removeFromSet(set);
      }
    } else if (mark2) {
      if (mark2.isInSet(node2.marks))
        toRemove = [mark2];
    } else {
      toRemove = node2.marks;
    }
    if (toRemove && toRemove.length) {
      let end = Math.min(pos + node2.nodeSize, to2);
      for (let i3 = 0; i3 < toRemove.length; i3++) {
        let style3 = toRemove[i3], found2;
        for (let j4 = 0; j4 < matched.length; j4++) {
          let m2 = matched[j4];
          if (m2.step == step - 1 && style3.eq(matched[j4].style))
            found2 = m2;
        }
        if (found2) {
          found2.to = end;
          found2.step = step;
        } else {
          matched.push({ style: style3, from: Math.max(pos, from4), to: end, step });
        }
      }
    }
  });
  matched.forEach((m2) => tr4.step(new RemoveMarkStep(m2.from, m2.to, m2.style)));
}
function clearIncompatible(tr4, pos, parentType, match2 = parentType.contentMatch, clearNewlines = true) {
  let node2 = tr4.doc.nodeAt(pos);
  let replSteps = [], cur = pos + 1;
  for (let i3 = 0; i3 < node2.childCount; i3++) {
    let child = node2.child(i3), end = cur + child.nodeSize;
    let allowed = match2.matchType(child.type);
    if (!allowed) {
      replSteps.push(new ReplaceStep(cur, end, Slice.empty));
    } else {
      match2 = allowed;
      for (let j4 = 0; j4 < child.marks.length; j4++)
        if (!parentType.allowsMarkType(child.marks[j4].type))
          tr4.step(new RemoveMarkStep(cur, end, child.marks[j4]));
      if (clearNewlines && child.isText && parentType.whitespace != "pre") {
        let m2, newline = /\r?\n|\r/g, slice2;
        while (m2 = newline.exec(child.text)) {
          if (!slice2)
            slice2 = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))), 0, 0);
          replSteps.push(new ReplaceStep(cur + m2.index, cur + m2.index + m2[0].length, slice2));
        }
      }
    }
    cur = end;
  }
  if (!match2.validEnd) {
    let fill = match2.fillBefore(Fragment.empty, true);
    tr4.replace(cur, cur, new Slice(fill, 0, 0));
  }
  for (let i3 = replSteps.length - 1; i3 >= 0; i3--)
    tr4.step(replSteps[i3]);
}
function canCut(node2, start, end) {
  return (start == 0 || node2.canReplace(start, node2.childCount)) && (end == node2.childCount || node2.canReplace(0, end));
}
function liftTarget(range) {
  let parent = range.parent;
  let content5 = parent.content.cutByIndex(range.startIndex, range.endIndex);
  for (let depth = range.depth, contentBefore = 0, contentAfter = 0; ; --depth) {
    let node2 = range.$from.node(depth);
    let index4 = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter;
    if (depth < range.depth && node2.canReplace(index4, endIndex, content5))
      return depth;
    if (depth == 0 || node2.type.spec.isolating || !canCut(node2, index4, endIndex))
      break;
    if (index4)
      contentBefore = 1;
    if (endIndex < node2.childCount)
      contentAfter = 1;
  }
  return null;
}
function lift(tr4, range, target) {
  let { $from, $to, depth } = range;
  let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);
  let start = gapStart, end = gapEnd;
  let before = Fragment.empty, openStart = 0;
  for (let d = depth, splitting = false; d > target; d--)
    if (splitting || $from.index(d) > 0) {
      splitting = true;
      before = Fragment.from($from.node(d).copy(before));
      openStart++;
    } else {
      start--;
    }
  let after = Fragment.empty, openEnd = 0;
  for (let d = depth, splitting = false; d > target; d--)
    if (splitting || $to.after(d + 1) < $to.end(d)) {
      splitting = true;
      after = Fragment.from($to.node(d).copy(after));
      openEnd++;
    } else {
      end++;
    }
  tr4.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));
}
function findWrapping(range, nodeType, attrs = null, innerRange = range) {
  let around = findWrappingOutside(range, nodeType);
  let inner = around && findWrappingInside(innerRange, nodeType);
  if (!inner)
    return null;
  return around.map(withAttrs).concat({ type: nodeType, attrs }).concat(inner.map(withAttrs));
}
function withAttrs(type) {
  return { type, attrs: null };
}
function findWrappingOutside(range, type) {
  let { parent, startIndex, endIndex } = range;
  let around = parent.contentMatchAt(startIndex).findWrapping(type);
  if (!around)
    return null;
  let outer = around.length ? around[0] : type;
  return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;
}
function findWrappingInside(range, type) {
  let { parent, startIndex, endIndex } = range;
  let inner = parent.child(startIndex);
  let inside = type.contentMatch.findWrapping(inner.type);
  if (!inside)
    return null;
  let lastType = inside.length ? inside[inside.length - 1] : type;
  let innerMatch = lastType.contentMatch;
  for (let i3 = startIndex; innerMatch && i3 < endIndex; i3++)
    innerMatch = innerMatch.matchType(parent.child(i3).type);
  if (!innerMatch || !innerMatch.validEnd)
    return null;
  return inside;
}
function wrap(tr4, range, wrappers) {
  let content5 = Fragment.empty;
  for (let i3 = wrappers.length - 1; i3 >= 0; i3--) {
    if (content5.size) {
      let match2 = wrappers[i3].type.contentMatch.matchFragment(content5);
      if (!match2 || !match2.validEnd)
        throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper");
    }
    content5 = Fragment.from(wrappers[i3].type.create(wrappers[i3].attrs, content5));
  }
  let start = range.start, end = range.end;
  tr4.step(new ReplaceAroundStep(start, end, start, end, new Slice(content5, 0, 0), wrappers.length, true));
}
function setBlockType(tr4, from4, to2, type, attrs) {
  if (!type.isTextblock)
    throw new RangeError("Type given to setBlockType should be a textblock");
  let mapFrom = tr4.steps.length;
  tr4.doc.nodesBetween(from4, to2, (node2, pos) => {
    let attrsHere = typeof attrs == "function" ? attrs(node2) : attrs;
    if (node2.isTextblock && !node2.hasMarkup(type, attrsHere) && canChangeType(tr4.doc, tr4.mapping.slice(mapFrom).map(pos), type)) {
      let convertNewlines = null;
      if (type.schema.linebreakReplacement) {
        let pre = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);
        if (pre && !supportLinebreak)
          convertNewlines = false;
        else if (!pre && supportLinebreak)
          convertNewlines = true;
      }
      if (convertNewlines === false)
        replaceLinebreaks(tr4, node2, pos, mapFrom);
      clearIncompatible(tr4, tr4.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null);
      let mapping = tr4.mapping.slice(mapFrom);
      let startM = mapping.map(pos, 1), endM = mapping.map(pos + node2.nodeSize, 1);
      tr4.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node2.marks)), 0, 0), 1, true));
      if (convertNewlines === true)
        replaceNewlines(tr4, node2, pos, mapFrom);
      return false;
    }
  });
}
function replaceNewlines(tr4, node2, pos, mapFrom) {
  node2.forEach((child, offset4) => {
    if (child.isText) {
      let m2, newline = /\r?\n|\r/g;
      while (m2 = newline.exec(child.text)) {
        let start = tr4.mapping.slice(mapFrom).map(pos + 1 + offset4 + m2.index);
        tr4.replaceWith(start, start + 1, node2.type.schema.linebreakReplacement.create());
      }
    }
  });
}
function replaceLinebreaks(tr4, node2, pos, mapFrom) {
  node2.forEach((child, offset4) => {
    if (child.type == child.type.schema.linebreakReplacement) {
      let start = tr4.mapping.slice(mapFrom).map(pos + 1 + offset4);
      tr4.replaceWith(start, start + 1, node2.type.schema.text("\n"));
    }
  });
}
function canChangeType(doc4, pos, type) {
  let $pos = doc4.resolve(pos), index4 = $pos.index();
  return $pos.parent.canReplaceWith(index4, index4 + 1, type);
}
function setNodeMarkup(tr4, pos, type, attrs, marks) {
  let node2 = tr4.doc.nodeAt(pos);
  if (!node2)
    throw new RangeError("No node at given position");
  if (!type)
    type = node2.type;
  let newNode = type.create(attrs, null, marks || node2.marks);
  if (node2.isLeaf)
    return tr4.replaceWith(pos, pos + node2.nodeSize, newNode);
  if (!type.validContent(node2.content))
    throw new RangeError("Invalid content for node type " + type.name);
  tr4.step(new ReplaceAroundStep(pos, pos + node2.nodeSize, pos + 1, pos + node2.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));
}
function canSplit(doc4, pos, depth = 1, typesAfter) {
  let $pos = doc4.resolve(pos), base4 = $pos.depth - depth;
  let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent;
  if (base4 < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))
    return false;
  for (let d = $pos.depth - 1, i3 = depth - 2; d > base4; d--, i3--) {
    let node2 = $pos.node(d), index5 = $pos.index(d);
    if (node2.type.spec.isolating)
      return false;
    let rest = node2.content.cutByIndex(index5, node2.childCount);
    let overrideChild = typesAfter && typesAfter[i3 + 1];
    if (overrideChild)
      rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));
    let after = typesAfter && typesAfter[i3] || node2;
    if (!node2.canReplace(index5 + 1, node2.childCount) || !after.type.validContent(rest))
      return false;
  }
  let index4 = $pos.indexAfter(base4);
  let baseType = typesAfter && typesAfter[0];
  return $pos.node(base4).canReplaceWith(index4, index4, baseType ? baseType.type : $pos.node(base4 + 1).type);
}
function split(tr4, pos, depth = 1, typesAfter) {
  let $pos = tr4.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;
  for (let d = $pos.depth, e2 = $pos.depth - depth, i3 = depth - 1; d > e2; d--, i3--) {
    before = Fragment.from($pos.node(d).copy(before));
    let typeAfter = typesAfter && typesAfter[i3];
    after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after));
  }
  tr4.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));
}
function canJoin(doc4, pos) {
  let $pos = doc4.resolve(pos), index4 = $pos.index();
  return joinable2($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index4, index4 + 1);
}
function canAppendWithSubstitutedLinebreaks(a3, b4) {
  if (!b4.content.size)
    a3.type.compatibleContent(b4.type);
  let match2 = a3.contentMatchAt(a3.childCount);
  let { linebreakReplacement } = a3.type.schema;
  for (let i3 = 0; i3 < b4.childCount; i3++) {
    let child = b4.child(i3);
    let type = child.type == linebreakReplacement ? a3.type.schema.nodes.text : child.type;
    match2 = match2.matchType(type);
    if (!match2)
      return false;
    if (!a3.type.allowsMarks(child.marks))
      return false;
  }
  return match2.validEnd;
}
function joinable2(a3, b4) {
  return !!(a3 && b4 && !a3.isLeaf && canAppendWithSubstitutedLinebreaks(a3, b4));
}
function joinPoint(doc4, pos, dir = -1) {
  let $pos = doc4.resolve(pos);
  for (let d = $pos.depth; ; d--) {
    let before, after, index4 = $pos.index(d);
    if (d == $pos.depth) {
      before = $pos.nodeBefore;
      after = $pos.nodeAfter;
    } else if (dir > 0) {
      before = $pos.node(d + 1);
      index4++;
      after = $pos.node(d).maybeChild(index4);
    } else {
      before = $pos.node(d).maybeChild(index4 - 1);
      after = $pos.node(d + 1);
    }
    if (before && !before.isTextblock && joinable2(before, after) && $pos.node(d).canReplace(index4, index4 + 1))
      return pos;
    if (d == 0)
      break;
    pos = dir < 0 ? $pos.before(d) : $pos.after(d);
  }
}
function join(tr4, pos, depth) {
  let convertNewlines = null;
  let { linebreakReplacement } = tr4.doc.type.schema;
  let $before = tr4.doc.resolve(pos - depth), beforeType = $before.node().type;
  if (linebreakReplacement && beforeType.inlineContent) {
    let pre = beforeType.whitespace == "pre";
    let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);
    if (pre && !supportLinebreak)
      convertNewlines = false;
    else if (!pre && supportLinebreak)
      convertNewlines = true;
  }
  let mapFrom = tr4.steps.length;
  if (convertNewlines === false) {
    let $after = tr4.doc.resolve(pos + depth);
    replaceLinebreaks(tr4, $after.node(), $after.before(), mapFrom);
  }
  if (beforeType.inlineContent)
    clearIncompatible(tr4, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);
  let mapping = tr4.mapping.slice(mapFrom), start = mapping.map(pos - depth);
  tr4.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));
  if (convertNewlines === true) {
    let $full = tr4.doc.resolve(start);
    replaceNewlines(tr4, $full.node(), $full.before(), tr4.steps.length);
  }
  return tr4;
}
function insertPoint(doc4, pos, nodeType) {
  let $pos = doc4.resolve(pos);
  if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))
    return pos;
  if ($pos.parentOffset == 0)
    for (let d = $pos.depth - 1; d >= 0; d--) {
      let index4 = $pos.index(d);
      if ($pos.node(d).canReplaceWith(index4, index4, nodeType))
        return $pos.before(d + 1);
      if (index4 > 0)
        return null;
    }
  if ($pos.parentOffset == $pos.parent.content.size)
    for (let d = $pos.depth - 1; d >= 0; d--) {
      let index4 = $pos.indexAfter(d);
      if ($pos.node(d).canReplaceWith(index4, index4, nodeType))
        return $pos.after(d + 1);
      if (index4 < $pos.node(d).childCount)
        return null;
    }
  return null;
}
function dropPoint(doc4, pos, slice2) {
  let $pos = doc4.resolve(pos);
  if (!slice2.content.size)
    return pos;
  let content5 = slice2.content;
  for (let i3 = 0; i3 < slice2.openStart; i3++)
    content5 = content5.firstChild.content;
  for (let pass = 1; pass <= (slice2.openStart == 0 && slice2.size ? 2 : 1); pass++) {
    for (let d = $pos.depth; d >= 0; d--) {
      let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1;
      let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0);
      let parent = $pos.node(d), fits = false;
      if (pass == 1) {
        fits = parent.canReplace(insertPos, insertPos, content5);
      } else {
        let wrapping = parent.contentMatchAt(insertPos).findWrapping(content5.firstChild.type);
        fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);
      }
      if (fits)
        return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1);
    }
  }
  return null;
}
function replaceStep(doc4, from4, to2 = from4, slice2 = Slice.empty) {
  if (from4 == to2 && !slice2.size)
    return null;
  let $from = doc4.resolve(from4), $to = doc4.resolve(to2);
  if (fitsTrivially($from, $to, slice2))
    return new ReplaceStep(from4, to2, slice2);
  return new Fitter($from, $to, slice2).fit();
}
function fitsTrivially($from, $to, slice2) {
  return !slice2.openStart && !slice2.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice2.content);
}
var Fitter = class {
  constructor($from, $to, unplaced) {
    this.$from = $from;
    this.$to = $to;
    this.unplaced = unplaced;
    this.frontier = [];
    this.placed = Fragment.empty;
    for (let i3 = 0; i3 <= $from.depth; i3++) {
      let node2 = $from.node(i3);
      this.frontier.push({
        type: node2.type,
        match: node2.contentMatchAt($from.indexAfter(i3))
      });
    }
    for (let i3 = $from.depth; i3 > 0; i3--)
      this.placed = Fragment.from($from.node(i3).copy(this.placed));
  }
  get depth() {
    return this.frontier.length - 1;
  }
  fit() {
    while (this.unplaced.size) {
      let fit = this.findFittable();
      if (fit)
        this.placeNodes(fit);
      else
        this.openMore() || this.dropNode();
    }
    let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;
    let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));
    if (!$to)
      return null;
    let content5 = this.placed, openStart = $from.depth, openEnd = $to.depth;
    while (openStart && openEnd && content5.childCount == 1) {
      content5 = content5.firstChild.content;
      openStart--;
      openEnd--;
    }
    let slice2 = new Slice(content5, openStart, openEnd);
    if (moveInline > -1)
      return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice2, placedSize);
    if (slice2.size || $from.pos != this.$to.pos)
      return new ReplaceStep($from.pos, $to.pos, slice2);
    return null;
  }
  // Find a position on the start spine of `this.unplaced` that has
  // content that can be moved somewhere on the frontier. Returns two
  // depths, one for the slice and one for the frontier.
  findFittable() {
    let startDepth = this.unplaced.openStart;
    for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) {
      let node2 = cur.firstChild;
      if (cur.childCount > 1)
        openEnd = 0;
      if (node2.type.spec.isolating && openEnd <= d) {
        startDepth = d;
        break;
      }
      cur = node2.content;
    }
    for (let pass = 1; pass <= 2; pass++) {
      for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {
        let fragment, parent = null;
        if (sliceDepth) {
          parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;
          fragment = parent.content;
        } else {
          fragment = this.unplaced.content;
        }
        let first2 = fragment.firstChild;
        for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {
          let { type, match: match2 } = this.frontier[frontierDepth], wrap5, inject = null;
          if (pass == 1 && (first2 ? match2.matchType(first2.type) || (inject = match2.fillBefore(Fragment.from(first2), false)) : parent && type.compatibleContent(parent.type)))
            return { sliceDepth, frontierDepth, parent, inject };
          else if (pass == 2 && first2 && (wrap5 = match2.findWrapping(first2.type)))
            return { sliceDepth, frontierDepth, parent, wrap: wrap5 };
          if (parent && match2.matchType(parent.type))
            break;
        }
      }
    }
  }
  openMore() {
    let { content: content5, openStart, openEnd } = this.unplaced;
    let inner = contentAt(content5, openStart);
    if (!inner.childCount || inner.firstChild.isLeaf)
      return false;
    this.unplaced = new Slice(content5, openStart + 1, Math.max(openEnd, inner.size + openStart >= content5.size - openEnd ? openStart + 1 : 0));
    return true;
  }
  dropNode() {
    let { content: content5, openStart, openEnd } = this.unplaced;
    let inner = contentAt(content5, openStart);
    if (inner.childCount <= 1 && openStart > 0) {
      let openAtEnd = content5.size - openStart <= openStart + inner.size;
      this.unplaced = new Slice(dropFromFragment(content5, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);
    } else {
      this.unplaced = new Slice(dropFromFragment(content5, openStart, 1), openStart, openEnd);
    }
  }
  // Move content from the unplaced slice at `sliceDepth` to the
  // frontier node at `frontierDepth`. Close that frontier node when
  // applicable.
  placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap: wrap5 }) {
    while (this.depth > frontierDepth)
      this.closeFrontierNode();
    if (wrap5)
      for (let i3 = 0; i3 < wrap5.length; i3++)
        this.openFrontierNode(wrap5[i3]);
    let slice2 = this.unplaced, fragment = parent ? parent.content : slice2.content;
    let openStart = slice2.openStart - sliceDepth;
    let taken = 0, add = [];
    let { match: match2, type } = this.frontier[frontierDepth];
    if (inject) {
      for (let i3 = 0; i3 < inject.childCount; i3++)
        add.push(inject.child(i3));
      match2 = match2.matchFragment(inject);
    }
    let openEndCount = fragment.size + sliceDepth - (slice2.content.size - slice2.openEnd);
    while (taken < fragment.childCount) {
      let next2 = fragment.child(taken), matches3 = match2.matchType(next2.type);
      if (!matches3)
        break;
      taken++;
      if (taken > 1 || openStart == 0 || next2.content.size) {
        match2 = matches3;
        add.push(closeNodeStart(next2.mark(type.allowedMarks(next2.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));
      }
    }
    let toEnd = taken == fragment.childCount;
    if (!toEnd)
      openEndCount = -1;
    this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));
    this.frontier[frontierDepth].match = match2;
    if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)
      this.closeFrontierNode();
    for (let i3 = 0, cur = fragment; i3 < openEndCount; i3++) {
      let node2 = cur.lastChild;
      this.frontier.push({ type: node2.type, match: node2.contentMatchAt(node2.childCount) });
      cur = node2.content;
    }
    this.unplaced = !toEnd ? new Slice(dropFromFragment(slice2.content, sliceDepth, taken), slice2.openStart, slice2.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(dropFromFragment(slice2.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice2.openEnd : sliceDepth - 1);
  }
  mustMoveInline() {
    if (!this.$to.parent.isTextblock)
      return -1;
    let top = this.frontier[this.depth], level;
    if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth)
      return -1;
    let { depth } = this.$to, after = this.$to.after(depth);
    while (depth > 1 && after == this.$to.end(--depth))
      ++after;
    return after;
  }
  findCloseLevel($to) {
    scan: for (let i3 = Math.min(this.depth, $to.depth); i3 >= 0; i3--) {
      let { match: match2, type } = this.frontier[i3];
      let dropInner = i3 < $to.depth && $to.end(i3 + 1) == $to.pos + ($to.depth - (i3 + 1));
      let fit = contentAfterFits($to, i3, type, match2, dropInner);
      if (!fit)
        continue;
      for (let d = i3 - 1; d >= 0; d--) {
        let { match: match3, type: type2 } = this.frontier[d];
        let matches3 = contentAfterFits($to, d, type2, match3, true);
        if (!matches3 || matches3.childCount)
          continue scan;
      }
      return { depth: i3, fit, move: dropInner ? $to.doc.resolve($to.after(i3 + 1)) : $to };
    }
  }
  close($to) {
    let close2 = this.findCloseLevel($to);
    if (!close2)
      return null;
    while (this.depth > close2.depth)
      this.closeFrontierNode();
    if (close2.fit.childCount)
      this.placed = addToFragment(this.placed, close2.depth, close2.fit);
    $to = close2.move;
    for (let d = close2.depth + 1; d <= $to.depth; d++) {
      let node2 = $to.node(d), add = node2.type.contentMatch.fillBefore(node2.content, true, $to.index(d));
      this.openFrontierNode(node2.type, node2.attrs, add);
    }
    return $to;
  }
  openFrontierNode(type, attrs = null, content5) {
    let top = this.frontier[this.depth];
    top.match = top.match.matchType(type);
    this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content5)));
    this.frontier.push({ type, match: type.contentMatch });
  }
  closeFrontierNode() {
    let open = this.frontier.pop();
    let add = open.match.fillBefore(Fragment.empty, true);
    if (add.childCount)
      this.placed = addToFragment(this.placed, this.frontier.length, add);
  }
};
function dropFromFragment(fragment, depth, count2) {
  if (depth == 0)
    return fragment.cutByIndex(count2, fragment.childCount);
  return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count2)));
}
function addToFragment(fragment, depth, content5) {
  if (depth == 0)
    return fragment.append(content5);
  return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content5)));
}
function contentAt(fragment, depth) {
  for (let i3 = 0; i3 < depth; i3++)
    fragment = fragment.firstChild.content;
  return fragment;
}
function closeNodeStart(node2, openStart, openEnd) {
  if (openStart <= 0)
    return node2;
  let frag = node2.content;
  if (openStart > 1)
    frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));
  if (openStart > 0) {
    frag = node2.type.contentMatch.fillBefore(frag).append(frag);
    if (openEnd <= 0)
      frag = frag.append(node2.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));
  }
  return node2.copy(frag);
}
function contentAfterFits($to, depth, type, match2, open) {
  let node2 = $to.node(depth), index4 = open ? $to.indexAfter(depth) : $to.index(depth);
  if (index4 == node2.childCount && !type.compatibleContent(node2.type))
    return null;
  let fit = match2.fillBefore(node2.content, true, index4);
  return fit && !invalidMarks(type, node2.content, index4) ? fit : null;
}
function invalidMarks(type, fragment, start) {
  for (let i3 = start; i3 < fragment.childCount; i3++)
    if (!type.allowsMarks(fragment.child(i3).marks))
      return true;
  return false;
}
function definesContent(type) {
  return type.spec.defining || type.spec.definingForContent;
}
function replaceRange(tr4, from4, to2, slice2) {
  if (!slice2.size)
    return tr4.deleteRange(from4, to2);
  let $from = tr4.doc.resolve(from4), $to = tr4.doc.resolve(to2);
  if (fitsTrivially($from, $to, slice2))
    return tr4.step(new ReplaceStep(from4, to2, slice2));
  let targetDepths = coveredDepths($from, $to);
  if (targetDepths[targetDepths.length - 1] == 0)
    targetDepths.pop();
  let preferredTarget = -($from.depth + 1);
  targetDepths.unshift(preferredTarget);
  for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) {
    let spec = $from.node(d).type.spec;
    if (spec.defining || spec.definingAsContext || spec.isolating)
      break;
    if (targetDepths.indexOf(d) > -1)
      preferredTarget = d;
    else if ($from.before(d) == pos)
      targetDepths.splice(1, 0, -d);
  }
  let preferredTargetIndex = targetDepths.indexOf(preferredTarget);
  let leftNodes = [], preferredDepth = slice2.openStart;
  for (let content5 = slice2.content, i3 = 0; ; i3++) {
    let node2 = content5.firstChild;
    leftNodes.push(node2);
    if (i3 == slice2.openStart)
      break;
    content5 = node2.content;
  }
  for (let d = preferredDepth - 1; d >= 0; d--) {
    let leftNode = leftNodes[d], def = definesContent(leftNode.type);
    if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))
      preferredDepth = d;
    else if (def || !leftNode.type.isTextblock)
      break;
  }
  for (let j4 = slice2.openStart; j4 >= 0; j4--) {
    let openDepth = (j4 + preferredDepth + 1) % (slice2.openStart + 1);
    let insert = leftNodes[openDepth];
    if (!insert)
      continue;
    for (let i3 = 0; i3 < targetDepths.length; i3++) {
      let targetDepth = targetDepths[(i3 + preferredTargetIndex) % targetDepths.length], expand = true;
      if (targetDepth < 0) {
        expand = false;
        targetDepth = -targetDepth;
      }
      let parent = $from.node(targetDepth - 1), index4 = $from.index(targetDepth - 1);
      if (parent.canReplaceWith(index4, index4, insert.type, insert.marks))
        return tr4.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to2, new Slice(closeFragment(slice2.content, 0, slice2.openStart, openDepth), openDepth, slice2.openEnd));
    }
  }
  let startSteps = tr4.steps.length;
  for (let i3 = targetDepths.length - 1; i3 >= 0; i3--) {
    tr4.replace(from4, to2, slice2);
    if (tr4.steps.length > startSteps)
      break;
    let depth = targetDepths[i3];
    if (depth < 0)
      continue;
    from4 = $from.before(depth);
    to2 = $to.after(depth);
  }
}
function closeFragment(fragment, depth, oldOpen, newOpen, parent) {
  if (depth < oldOpen) {
    let first2 = fragment.firstChild;
    fragment = fragment.replaceChild(0, first2.copy(closeFragment(first2.content, depth + 1, oldOpen, newOpen, first2)));
  }
  if (depth > newOpen) {
    let match2 = parent.contentMatchAt(0);
    let start = match2.fillBefore(fragment).append(fragment);
    fragment = start.append(match2.matchFragment(start).fillBefore(Fragment.empty, true));
  }
  return fragment;
}
function replaceRangeWith(tr4, from4, to2, node2) {
  if (!node2.isInline && from4 == to2 && tr4.doc.resolve(from4).parent.content.size) {
    let point5 = insertPoint(tr4.doc, from4, node2.type);
    if (point5 != null)
      from4 = to2 = point5;
  }
  tr4.replaceRange(from4, to2, new Slice(Fragment.from(node2), 0, 0));
}
function deleteRange(tr4, from4, to2) {
  let $from = tr4.doc.resolve(from4), $to = tr4.doc.resolve(to2);
  let covered = coveredDepths($from, $to);
  for (let i3 = 0; i3 < covered.length; i3++) {
    let depth = covered[i3], last2 = i3 == covered.length - 1;
    if (last2 && depth == 0 || $from.node(depth).type.contentMatch.validEnd)
      return tr4.delete($from.start(depth), $to.end(depth));
    if (depth > 0 && (last2 || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))
      return tr4.delete($from.before(depth), $to.after(depth));
  }
  for (let d = 1; d <= $from.depth && d <= $to.depth; d++) {
    if (from4 - $from.start(d) == $from.depth - d && to2 > $from.end(d) && $to.end(d) - to2 != $to.depth - d && $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1)))
      return tr4.delete($from.before(d), to2);
  }
  tr4.delete(from4, to2);
}
function coveredDepths($from, $to) {
  let result = [], minDepth = Math.min($from.depth, $to.depth);
  for (let d = minDepth; d >= 0; d--) {
    let start = $from.start(d);
    if (start < $from.pos - ($from.depth - d) || $to.end(d) > $to.pos + ($to.depth - d) || $from.node(d).type.spec.isolating || $to.node(d).type.spec.isolating)
      break;
    if (start == $to.start(d) || d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d && $to.start(d - 1) == start - 1)
      result.push(d);
  }
  return result;
}
var AttrStep = class _AttrStep extends Step {
  /**
  Construct an attribute step.
  */
  constructor(pos, attr2, value) {
    super();
    this.pos = pos;
    this.attr = attr2;
    this.value = value;
  }
  apply(doc4) {
    let node2 = doc4.nodeAt(this.pos);
    if (!node2)
      return StepResult.fail("No node at attribute step's position");
    let attrs = /* @__PURE__ */ Object.create(null);
    for (let name in node2.attrs)
      attrs[name] = node2.attrs[name];
    attrs[this.attr] = this.value;
    let updated = node2.type.create(attrs, null, node2.marks);
    return StepResult.fromReplace(doc4, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node2.isLeaf ? 0 : 1));
  }
  getMap() {
    return StepMap.empty;
  }
  invert(doc4) {
    return new _AttrStep(this.pos, this.attr, doc4.nodeAt(this.pos).attrs[this.attr]);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new _AttrStep(pos.pos, this.attr, this.value);
  }
  toJSON() {
    return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value };
  }
  static fromJSON(schema, json) {
    if (typeof json.pos != "number" || typeof json.attr != "string")
      throw new RangeError("Invalid input for AttrStep.fromJSON");
    return new _AttrStep(json.pos, json.attr, json.value);
  }
};
Step.jsonID("attr", AttrStep);
var DocAttrStep = class _DocAttrStep extends Step {
  /**
  Construct an attribute step.
  */
  constructor(attr2, value) {
    super();
    this.attr = attr2;
    this.value = value;
  }
  apply(doc4) {
    let attrs = /* @__PURE__ */ Object.create(null);
    for (let name in doc4.attrs)
      attrs[name] = doc4.attrs[name];
    attrs[this.attr] = this.value;
    let updated = doc4.type.create(attrs, doc4.content, doc4.marks);
    return StepResult.ok(updated);
  }
  getMap() {
    return StepMap.empty;
  }
  invert(doc4) {
    return new _DocAttrStep(this.attr, doc4.attrs[this.attr]);
  }
  map(mapping) {
    return this;
  }
  toJSON() {
    return { stepType: "docAttr", attr: this.attr, value: this.value };
  }
  static fromJSON(schema, json) {
    if (typeof json.attr != "string")
      throw new RangeError("Invalid input for DocAttrStep.fromJSON");
    return new _DocAttrStep(json.attr, json.value);
  }
};
Step.jsonID("docAttr", DocAttrStep);
var TransformError = class extends Error {
};
TransformError = function TransformError2(message) {
  let err = Error.call(this, message);
  err.__proto__ = TransformError2.prototype;
  return err;
};
TransformError.prototype = Object.create(Error.prototype);
TransformError.prototype.constructor = TransformError;
TransformError.prototype.name = "TransformError";
var Transform = class {
  /**
  Create a transform that starts with the given document.
  */
  constructor(doc4) {
    this.doc = doc4;
    this.steps = [];
    this.docs = [];
    this.mapping = new Mapping();
  }
  /**
  The starting document.
  */
  get before() {
    return this.docs.length ? this.docs[0] : this.doc;
  }
  /**
  Apply a new step in this transform, saving the result. Throws an
  error when the step fails.
  */
  step(step) {
    let result = this.maybeStep(step);
    if (result.failed)
      throw new TransformError(result.failed);
    return this;
  }
  /**
  Try to apply a step in this transformation, ignoring it if it
  fails. Returns the step result.
  */
  maybeStep(step) {
    let result = step.apply(this.doc);
    if (!result.failed)
      this.addStep(step, result.doc);
    return result;
  }
  /**
  True when the document has been changed (when there are any
  steps).
  */
  get docChanged() {
    return this.steps.length > 0;
  }
  /**
  @internal
  */
  addStep(step, doc4) {
    this.docs.push(this.doc);
    this.steps.push(step);
    this.mapping.appendMap(step.getMap());
    this.doc = doc4;
  }
  /**
  Replace the part of the document between `from` and `to` with the
  given `slice`.
  */
  replace(from4, to2 = from4, slice2 = Slice.empty) {
    let step = replaceStep(this.doc, from4, to2, slice2);
    if (step)
      this.step(step);
    return this;
  }
  /**
  Replace the given range with the given content, which may be a
  fragment, node, or array of nodes.
  */
  replaceWith(from4, to2, content5) {
    return this.replace(from4, to2, new Slice(Fragment.from(content5), 0, 0));
  }
  /**
  Delete the content between the given positions.
  */
  delete(from4, to2) {
    return this.replace(from4, to2, Slice.empty);
  }
  /**
  Insert the given content at the given position.
  */
  insert(pos, content5) {
    return this.replaceWith(pos, pos, content5);
  }
  /**
  Replace a range of the document with a given slice, using
  `from`, `to`, and the slice's
  [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather
  than fixed start and end points. This method may grow the
  replaced area or close open nodes in the slice in order to get a
  fit that is more in line with WYSIWYG expectations, by dropping
  fully covered parent nodes of the replaced region when they are
  marked [non-defining as
  context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an
  open parent node from the slice that _is_ marked as [defining
  its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).
  
  This is the method, for example, to handle paste. The similar
  [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more
  primitive tool which will _not_ move the start and end of its given
  range, and is useful in situations where you need more precise
  control over what happens.
  */
  replaceRange(from4, to2, slice2) {
    replaceRange(this, from4, to2, slice2);
    return this;
  }
  /**
  Replace the given range with a node, but use `from` and `to` as
  hints, rather than precise positions. When from and to are the same
  and are at the start or end of a parent node in which the given
  node doesn't fit, this method may _move_ them out towards a parent
  that does allow the given node to be placed. When the given range
  completely covers a parent node, this method may completely replace
  that parent node.
  */
  replaceRangeWith(from4, to2, node2) {
    replaceRangeWith(this, from4, to2, node2);
    return this;
  }
  /**
  Delete the given range, expanding it to cover fully covered
  parent nodes until a valid replace is found.
  */
  deleteRange(from4, to2) {
    deleteRange(this, from4, to2);
    return this;
  }
  /**
  Split the content in the given range off from its parent, if there
  is sibling content before or after it, and move it up the tree to
  the depth specified by `target`. You'll probably want to use
  [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make
  sure the lift is valid.
  */
  lift(range, target) {
    lift(this, range, target);
    return this;
  }
  /**
  Join the blocks around the given position. If depth is 2, their
  last and first siblings are also joined, and so on.
  */
  join(pos, depth = 1) {
    join(this, pos, depth);
    return this;
  }
  /**
  Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.
  The wrappers are assumed to be valid in this position, and should
  probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).
  */
  wrap(range, wrappers) {
    wrap(this, range, wrappers);
    return this;
  }
  /**
  Set the type of all textblocks (partly) between `from` and `to` to
  the given node type with the given attributes.
  */
  setBlockType(from4, to2 = from4, type, attrs = null) {
    setBlockType(this, from4, to2, type, attrs);
    return this;
  }
  /**
  Change the type, attributes, and/or marks of the node at `pos`.
  When `type` isn't given, the existing node type is preserved,
  */
  setNodeMarkup(pos, type, attrs = null, marks) {
    setNodeMarkup(this, pos, type, attrs, marks);
    return this;
  }
  /**
  Set a single attribute on a given node to a new value.
  The `pos` addresses the document content. Use `setDocAttribute`
  to set attributes on the document itself.
  */
  setNodeAttribute(pos, attr2, value) {
    this.step(new AttrStep(pos, attr2, value));
    return this;
  }
  /**
  Set a single attribute on the document to a new value.
  */
  setDocAttribute(attr2, value) {
    this.step(new DocAttrStep(attr2, value));
    return this;
  }
  /**
  Add a mark to the node at position `pos`.
  */
  addNodeMark(pos, mark2) {
    this.step(new AddNodeMarkStep(pos, mark2));
    return this;
  }
  /**
  Remove a mark (or all marks of the given type) from the node at
  position `pos`.
  */
  removeNodeMark(pos, mark2) {
    let node2 = this.doc.nodeAt(pos);
    if (!node2)
      throw new RangeError("No node at position " + pos);
    if (mark2 instanceof Mark) {
      if (mark2.isInSet(node2.marks))
        this.step(new RemoveNodeMarkStep(pos, mark2));
    } else {
      let set = node2.marks, found2, steps = [];
      while (found2 = mark2.isInSet(set)) {
        steps.push(new RemoveNodeMarkStep(pos, found2));
        set = found2.removeFromSet(set);
      }
      for (let i3 = steps.length - 1; i3 >= 0; i3--)
        this.step(steps[i3]);
    }
    return this;
  }
  /**
  Split the node at the given position, and optionally, if `depth` is
  greater than one, any number of nodes above that. By default, the
  parts split off will inherit the node type of the original node.
  This can be changed by passing an array of types and attributes to
  use after the split (with the outermost nodes coming first).
  */
  split(pos, depth = 1, typesAfter) {
    split(this, pos, depth, typesAfter);
    return this;
  }
  /**
  Add the given mark to the inline content between `from` and `to`.
  */
  addMark(from4, to2, mark2) {
    addMark(this, from4, to2, mark2);
    return this;
  }
  /**
  Remove marks from inline nodes between `from` and `to`. When
  `mark` is a single mark, remove precisely that mark. When it is
  a mark type, remove all marks of that type. When it is null,
  remove all marks of any type.
  */
  removeMark(from4, to2, mark2) {
    removeMark(this, from4, to2, mark2);
    return this;
  }
  /**
  Removes all marks and nodes from the content of the node at
  `pos` that don't match the given new parent node type. Accepts
  an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as
  third argument.
  */
  clearIncompatible(pos, parentType, match2) {
    clearIncompatible(this, pos, parentType, match2);
    return this;
  }
};

// ../../node_modules/.pnpm/prosemirror-state@1.4.4/node_modules/prosemirror-state/dist/index.js
var classesById = /* @__PURE__ */ Object.create(null);
var Selection = class {
  /**
  Initialize a selection with the head and anchor and ranges. If no
  ranges are given, constructs a single range across `$anchor` and
  `$head`.
  */
  constructor($anchor, $head, ranges) {
    this.$anchor = $anchor;
    this.$head = $head;
    this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];
  }
  /**
  The selection's anchor, as an unresolved position.
  */
  get anchor() {
    return this.$anchor.pos;
  }
  /**
  The selection's head.
  */
  get head() {
    return this.$head.pos;
  }
  /**
  The lower bound of the selection's main range.
  */
  get from() {
    return this.$from.pos;
  }
  /**
  The upper bound of the selection's main range.
  */
  get to() {
    return this.$to.pos;
  }
  /**
  The resolved lower  bound of the selection's main range.
  */
  get $from() {
    return this.ranges[0].$from;
  }
  /**
  The resolved upper bound of the selection's main range.
  */
  get $to() {
    return this.ranges[0].$to;
  }
  /**
  Indicates whether the selection contains any content.
  */
  get empty() {
    let ranges = this.ranges;
    for (let i3 = 0; i3 < ranges.length; i3++)
      if (ranges[i3].$from.pos != ranges[i3].$to.pos)
        return false;
    return true;
  }
  /**
  Get the content of this selection as a slice.
  */
  content() {
    return this.$from.doc.slice(this.from, this.to, true);
  }
  /**
  Replace the selection with a slice or, if no slice is given,
  delete the selection. Will append to the given transaction.
  */
  replace(tr4, content5 = Slice.empty) {
    let lastNode = content5.content.lastChild, lastParent = null;
    for (let i3 = 0; i3 < content5.openEnd; i3++) {
      lastParent = lastNode;
      lastNode = lastNode.lastChild;
    }
    let mapFrom = tr4.steps.length, ranges = this.ranges;
    for (let i3 = 0; i3 < ranges.length; i3++) {
      let { $from, $to } = ranges[i3], mapping = tr4.mapping.slice(mapFrom);
      tr4.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i3 ? Slice.empty : content5);
      if (i3 == 0)
        selectionToInsertionEnd(tr4, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);
    }
  }
  /**
  Replace the selection with the given node, appending the changes
  to the given transaction.
  */
  replaceWith(tr4, node2) {
    let mapFrom = tr4.steps.length, ranges = this.ranges;
    for (let i3 = 0; i3 < ranges.length; i3++) {
      let { $from, $to } = ranges[i3], mapping = tr4.mapping.slice(mapFrom);
      let from4 = mapping.map($from.pos), to2 = mapping.map($to.pos);
      if (i3) {
        tr4.deleteRange(from4, to2);
      } else {
        tr4.replaceRangeWith(from4, to2, node2);
        selectionToInsertionEnd(tr4, mapFrom, node2.isInline ? -1 : 1);
      }
    }
  }
  /**
  Find a valid cursor or leaf node selection starting at the given
  position and searching back if `dir` is negative, and forward if
  positive. When `textOnly` is true, only consider cursor
  selections. Will return null when no valid selection position is
  found.
  */
  static findFrom($pos, dir, textOnly = false) {
    let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);
    if (inner)
      return inner;
    for (let depth = $pos.depth - 1; depth >= 0; depth--) {
      let found2 = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);
      if (found2)
        return found2;
    }
    return null;
  }
  /**
  Find a valid cursor or leaf node selection near the given
  position. Searches forward first by default, but if `bias` is
  negative, it will search backwards first.
  */
  static near($pos, bias = 1) {
    return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));
  }
  /**
  Find the cursor or leaf node selection closest to the start of
  the given document. Will return an
  [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position
  exists.
  */
  static atStart(doc4) {
    return findSelectionIn(doc4, doc4, 0, 0, 1) || new AllSelection(doc4);
  }
  /**
  Find the cursor or leaf node selection closest to the end of the
  given document.
  */
  static atEnd(doc4) {
    return findSelectionIn(doc4, doc4, doc4.content.size, doc4.childCount, -1) || new AllSelection(doc4);
  }
  /**
  Deserialize the JSON representation of a selection. Must be
  implemented for custom classes (as a static class method).
  */
  static fromJSON(doc4, json) {
    if (!json || !json.type)
      throw new RangeError("Invalid input for Selection.fromJSON");
    let cls = classesById[json.type];
    if (!cls)
      throw new RangeError(`No selection type ${json.type} defined`);
    return cls.fromJSON(doc4, json);
  }
  /**
  To be able to deserialize selections from JSON, custom selection
  classes must register themselves with an ID string, so that they
  can be disambiguated. Try to pick something that's unlikely to
  clash with classes from other modules.
  */
  static jsonID(id2, selectionClass) {
    if (id2 in classesById)
      throw new RangeError("Duplicate use of selection JSON ID " + id2);
    classesById[id2] = selectionClass;
    selectionClass.prototype.jsonID = id2;
    return selectionClass;
  }
  /**
  Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,
  which is a value that can be mapped without having access to a
  current document, and later resolved to a real selection for a
  given document again. (This is used mostly by the history to
  track and restore old selections.) The default implementation of
  this method just converts the selection to a text selection and
  returns the bookmark for that.
  */
  getBookmark() {
    return TextSelection.between(this.$anchor, this.$head).getBookmark();
  }
};
Selection.prototype.visible = true;
var SelectionRange = class {
  /**
  Create a range.
  */
  constructor($from, $to) {
    this.$from = $from;
    this.$to = $to;
  }
};
var warnedAboutTextSelection = false;
function checkTextSelection($pos) {
  if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {
    warnedAboutTextSelection = true;
    console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")");
  }
}
var TextSelection = class _TextSelection extends Selection {
  /**
  Construct a text selection between the given points.
  */
  constructor($anchor, $head = $anchor) {
    checkTextSelection($anchor);
    checkTextSelection($head);
    super($anchor, $head);
  }
  /**
  Returns a resolved position if this is a cursor selection (an
  empty text selection), and null otherwise.
  */
  get $cursor() {
    return this.$anchor.pos == this.$head.pos ? this.$head : null;
  }
  map(doc4, mapping) {
    let $head = doc4.resolve(mapping.map(this.head));
    if (!$head.parent.inlineContent)
      return Selection.near($head);
    let $anchor = doc4.resolve(mapping.map(this.anchor));
    return new _TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);
  }
  replace(tr4, content5 = Slice.empty) {
    super.replace(tr4, content5);
    if (content5 == Slice.empty) {
      let marks = this.$from.marksAcross(this.$to);
      if (marks)
        tr4.ensureMarks(marks);
    }
  }
  eq(other) {
    return other instanceof _TextSelection && other.anchor == this.anchor && other.head == this.head;
  }
  getBookmark() {
    return new TextBookmark(this.anchor, this.head);
  }
  toJSON() {
    return { type: "text", anchor: this.anchor, head: this.head };
  }
  /**
  @internal
  */
  static fromJSON(doc4, json) {
    if (typeof json.anchor != "number" || typeof json.head != "number")
      throw new RangeError("Invalid input for TextSelection.fromJSON");
    return new _TextSelection(doc4.resolve(json.anchor), doc4.resolve(json.head));
  }
  /**
  Create a text selection from non-resolved positions.
  */
  static create(doc4, anchor, head2 = anchor) {
    let $anchor = doc4.resolve(anchor);
    return new this($anchor, head2 == anchor ? $anchor : doc4.resolve(head2));
  }
  /**
  Return a text selection that spans the given positions or, if
  they aren't text positions, find a text selection near them.
  `bias` determines whether the method searches forward (default)
  or backwards (negative number) first. Will fall back to calling
  [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document
  doesn't contain a valid text position.
  */
  static between($anchor, $head, bias) {
    let dPos = $anchor.pos - $head.pos;
    if (!bias || dPos)
      bias = dPos >= 0 ? 1 : -1;
    if (!$head.parent.inlineContent) {
      let found2 = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);
      if (found2)
        $head = found2.$head;
      else
        return Selection.near($head, bias);
    }
    if (!$anchor.parent.inlineContent) {
      if (dPos == 0) {
        $anchor = $head;
      } else {
        $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;
        if ($anchor.pos < $head.pos != dPos < 0)
          $anchor = $head;
      }
    }
    return new _TextSelection($anchor, $head);
  }
};
Selection.jsonID("text", TextSelection);
var TextBookmark = class _TextBookmark {
  constructor(anchor, head2) {
    this.anchor = anchor;
    this.head = head2;
  }
  map(mapping) {
    return new _TextBookmark(mapping.map(this.anchor), mapping.map(this.head));
  }
  resolve(doc4) {
    return TextSelection.between(doc4.resolve(this.anchor), doc4.resolve(this.head));
  }
};
var NodeSelection = class _NodeSelection extends Selection {
  /**
  Create a node selection. Does not verify the validity of its
  argument.
  */
  constructor($pos) {
    let node2 = $pos.nodeAfter;
    let $end = $pos.node(0).resolve($pos.pos + node2.nodeSize);
    super($pos, $end);
    this.node = node2;
  }
  map(doc4, mapping) {
    let { deleted, pos } = mapping.mapResult(this.anchor);
    let $pos = doc4.resolve(pos);
    if (deleted)
      return Selection.near($pos);
    return new _NodeSelection($pos);
  }
  content() {
    return new Slice(Fragment.from(this.node), 0, 0);
  }
  eq(other) {
    return other instanceof _NodeSelection && other.anchor == this.anchor;
  }
  toJSON() {
    return { type: "node", anchor: this.anchor };
  }
  getBookmark() {
    return new NodeBookmark(this.anchor);
  }
  /**
  @internal
  */
  static fromJSON(doc4, json) {
    if (typeof json.anchor != "number")
      throw new RangeError("Invalid input for NodeSelection.fromJSON");
    return new _NodeSelection(doc4.resolve(json.anchor));
  }
  /**
  Create a node selection from non-resolved positions.
  */
  static create(doc4, from4) {
    return new _NodeSelection(doc4.resolve(from4));
  }
  /**
  Determines whether the given node may be selected as a node
  selection.
  */
  static isSelectable(node2) {
    return !node2.isText && node2.type.spec.selectable !== false;
  }
};
NodeSelection.prototype.visible = false;
Selection.jsonID("node", NodeSelection);
var NodeBookmark = class _NodeBookmark {
  constructor(anchor) {
    this.anchor = anchor;
  }
  map(mapping) {
    let { deleted, pos } = mapping.mapResult(this.anchor);
    return deleted ? new TextBookmark(pos, pos) : new _NodeBookmark(pos);
  }
  resolve(doc4) {
    let $pos = doc4.resolve(this.anchor), node2 = $pos.nodeAfter;
    if (node2 && NodeSelection.isSelectable(node2))
      return new NodeSelection($pos);
    return Selection.near($pos);
  }
};
var AllSelection = class _AllSelection extends Selection {
  /**
  Create an all-selection over the given document.
  */
  constructor(doc4) {
    super(doc4.resolve(0), doc4.resolve(doc4.content.size));
  }
  replace(tr4, content5 = Slice.empty) {
    if (content5 == Slice.empty) {
      tr4.delete(0, tr4.doc.content.size);
      let sel = Selection.atStart(tr4.doc);
      if (!sel.eq(tr4.selection))
        tr4.setSelection(sel);
    } else {
      super.replace(tr4, content5);
    }
  }
  toJSON() {
    return { type: "all" };
  }
  /**
  @internal
  */
  static fromJSON(doc4) {
    return new _AllSelection(doc4);
  }
  map(doc4) {
    return new _AllSelection(doc4);
  }
  eq(other) {
    return other instanceof _AllSelection;
  }
  getBookmark() {
    return AllBookmark;
  }
};
Selection.jsonID("all", AllSelection);
var AllBookmark = {
  map() {
    return this;
  },
  resolve(doc4) {
    return new AllSelection(doc4);
  }
};
function findSelectionIn(doc4, node2, pos, index4, dir, text10 = false) {
  if (node2.inlineContent)
    return TextSelection.create(doc4, pos);
  for (let i3 = index4 - (dir > 0 ? 0 : 1); dir > 0 ? i3 < node2.childCount : i3 >= 0; i3 += dir) {
    let child = node2.child(i3);
    if (!child.isAtom) {
      let inner = findSelectionIn(doc4, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text10);
      if (inner)
        return inner;
    } else if (!text10 && NodeSelection.isSelectable(child)) {
      return NodeSelection.create(doc4, pos - (dir < 0 ? child.nodeSize : 0));
    }
    pos += child.nodeSize * dir;
  }
  return null;
}
function selectionToInsertionEnd(tr4, startLen, bias) {
  let last2 = tr4.steps.length - 1;
  if (last2 < startLen)
    return;
  let step = tr4.steps[last2];
  if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))
    return;
  let map7 = tr4.mapping.maps[last2], end;
  map7.forEach((_from, _to, _newFrom, newTo) => {
    if (end == null)
      end = newTo;
  });
  tr4.setSelection(Selection.near(tr4.doc.resolve(end), bias));
}
var UPDATED_SEL = 1;
var UPDATED_MARKS = 2;
var UPDATED_SCROLL = 4;
var Transaction = class extends Transform {
  /**
  @internal
  */
  constructor(state) {
    super(state.doc);
    this.curSelectionFor = 0;
    this.updated = 0;
    this.meta = /* @__PURE__ */ Object.create(null);
    this.time = Date.now();
    this.curSelection = state.selection;
    this.storedMarks = state.storedMarks;
  }
  /**
  The transaction's current selection. This defaults to the editor
  selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the
  transaction, but can be overwritten with
  [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).
  */
  get selection() {
    if (this.curSelectionFor < this.steps.length) {
      this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));
      this.curSelectionFor = this.steps.length;
    }
    return this.curSelection;
  }
  /**
  Update the transaction's current selection. Will determine the
  selection that the editor gets when the transaction is applied.
  */
  setSelection(selection) {
    if (selection.$from.doc != this.doc)
      throw new RangeError("Selection passed to setSelection must point at the current document");
    this.curSelection = selection;
    this.curSelectionFor = this.steps.length;
    this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;
    this.storedMarks = null;
    return this;
  }
  /**
  Whether the selection was explicitly updated by this transaction.
  */
  get selectionSet() {
    return (this.updated & UPDATED_SEL) > 0;
  }
  /**
  Set the current stored marks.
  */
  setStoredMarks(marks) {
    this.storedMarks = marks;
    this.updated |= UPDATED_MARKS;
    return this;
  }
  /**
  Make sure the current stored marks or, if that is null, the marks
  at the selection, match the given set of marks. Does nothing if
  this is already the case.
  */
  ensureMarks(marks) {
    if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))
      this.setStoredMarks(marks);
    return this;
  }
  /**
  Add a mark to the set of stored marks.
  */
  addStoredMark(mark2) {
    return this.ensureMarks(mark2.addToSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Remove a mark or mark type from the set of stored marks.
  */
  removeStoredMark(mark2) {
    return this.ensureMarks(mark2.removeFromSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Whether the stored marks were explicitly set for this transaction.
  */
  get storedMarksSet() {
    return (this.updated & UPDATED_MARKS) > 0;
  }
  /**
  @internal
  */
  addStep(step, doc4) {
    super.addStep(step, doc4);
    this.updated = this.updated & ~UPDATED_MARKS;
    this.storedMarks = null;
  }
  /**
  Update the timestamp for the transaction.
  */
  setTime(time) {
    this.time = time;
    return this;
  }
  /**
  Replace the current selection with the given slice.
  */
  replaceSelection(slice2) {
    this.selection.replace(this, slice2);
    return this;
  }
  /**
  Replace the selection with the given node. When `inheritMarks` is
  true and the content is inline, it inherits the marks from the
  place where it is inserted.
  */
  replaceSelectionWith(node2, inheritMarks = true) {
    let selection = this.selection;
    if (inheritMarks)
      node2 = node2.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark.none));
    selection.replaceWith(this, node2);
    return this;
  }
  /**
  Delete the selection.
  */
  deleteSelection() {
    this.selection.replace(this);
    return this;
  }
  /**
  Replace the given range, or the selection if no range is given,
  with a text node containing the given string.
  */
  insertText(text10, from4, to2) {
    let schema = this.doc.type.schema;
    if (from4 == null) {
      if (!text10)
        return this.deleteSelection();
      return this.replaceSelectionWith(schema.text(text10), true);
    } else {
      if (to2 == null)
        to2 = from4;
      if (!text10)
        return this.deleteRange(from4, to2);
      let marks = this.storedMarks;
      if (!marks) {
        let $from = this.doc.resolve(from4);
        marks = to2 == from4 ? $from.marks() : $from.marksAcross(this.doc.resolve(to2));
      }
      this.replaceRangeWith(from4, to2, schema.text(text10, marks));
      if (!this.selection.empty && this.selection.to == from4 + text10.length)
        this.setSelection(Selection.near(this.selection.$to));
      return this;
    }
  }
  /**
  Store a metadata property in this transaction, keyed either by
  name or by plugin.
  */
  setMeta(key2, value) {
    this.meta[typeof key2 == "string" ? key2 : key2.key] = value;
    return this;
  }
  /**
  Retrieve a metadata property for a given name or plugin.
  */
  getMeta(key2) {
    return this.meta[typeof key2 == "string" ? key2 : key2.key];
  }
  /**
  Returns true if this transaction doesn't contain any metadata,
  and can thus safely be extended.
  */
  get isGeneric() {
    for (let _2 in this.meta)
      return false;
    return true;
  }
  /**
  Indicate that the editor should scroll the selection into view
  when updated to the state produced by this transaction.
  */
  scrollIntoView() {
    this.updated |= UPDATED_SCROLL;
    return this;
  }
  /**
  True when this transaction has had `scrollIntoView` called on it.
  */
  get scrolledIntoView() {
    return (this.updated & UPDATED_SCROLL) > 0;
  }
};
function bind(f6, self2) {
  return !self2 || !f6 ? f6 : f6.bind(self2);
}
var FieldDesc = class {
  constructor(name, desc, self2) {
    this.name = name;
    this.init = bind(desc.init, self2);
    this.apply = bind(desc.apply, self2);
  }
};
var baseFields = [
  new FieldDesc("doc", {
    init(config) {
      return config.doc || config.schema.topNodeType.createAndFill();
    },
    apply(tr4) {
      return tr4.doc;
    }
  }),
  new FieldDesc("selection", {
    init(config, instance) {
      return config.selection || Selection.atStart(instance.doc);
    },
    apply(tr4) {
      return tr4.selection;
    }
  }),
  new FieldDesc("storedMarks", {
    init(config) {
      return config.storedMarks || null;
    },
    apply(tr4, _marks, _old, state) {
      return state.selection.$cursor ? tr4.storedMarks : null;
    }
  }),
  new FieldDesc("scrollToSelection", {
    init() {
      return 0;
    },
    apply(tr4, prev) {
      return tr4.scrolledIntoView ? prev + 1 : prev;
    }
  })
];
var Configuration = class {
  constructor(schema, plugins) {
    this.schema = schema;
    this.plugins = [];
    this.pluginsByKey = /* @__PURE__ */ Object.create(null);
    this.fields = baseFields.slice();
    if (plugins)
      plugins.forEach((plugin) => {
        if (this.pluginsByKey[plugin.key])
          throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")");
        this.plugins.push(plugin);
        this.pluginsByKey[plugin.key] = plugin;
        if (plugin.spec.state)
          this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));
      });
  }
};
var EditorState = class _EditorState {
  /**
  @internal
  */
  constructor(config) {
    this.config = config;
  }
  /**
  The schema of the state's document.
  */
  get schema() {
    return this.config.schema;
  }
  /**
  The plugins that are active in this state.
  */
  get plugins() {
    return this.config.plugins;
  }
  /**
  Apply the given transaction to produce a new state.
  */
  apply(tr4) {
    return this.applyTransaction(tr4).state;
  }
  /**
  @internal
  */
  filterTransaction(tr4, ignore3 = -1) {
    for (let i3 = 0; i3 < this.config.plugins.length; i3++)
      if (i3 != ignore3) {
        let plugin = this.config.plugins[i3];
        if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr4, this))
          return false;
      }
    return true;
  }
  /**
  Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that
  returns the precise transactions that were applied (which might
  be influenced by the [transaction
  hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of
  plugins) along with the new state.
  */
  applyTransaction(rootTr) {
    if (!this.filterTransaction(rootTr))
      return { state: this, transactions: [] };
    let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;
    for (; ; ) {
      let haveNew = false;
      for (let i3 = 0; i3 < this.config.plugins.length; i3++) {
        let plugin = this.config.plugins[i3];
        if (plugin.spec.appendTransaction) {
          let n = seen ? seen[i3].n : 0, oldState = seen ? seen[i3].state : this;
          let tr4 = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);
          if (tr4 && newState.filterTransaction(tr4, i3)) {
            tr4.setMeta("appendedTransaction", rootTr);
            if (!seen) {
              seen = [];
              for (let j4 = 0; j4 < this.config.plugins.length; j4++)
                seen.push(j4 < i3 ? { state: newState, n: trs.length } : { state: this, n: 0 });
            }
            trs.push(tr4);
            newState = newState.applyInner(tr4);
            haveNew = true;
          }
          if (seen)
            seen[i3] = { state: newState, n: trs.length };
        }
      }
      if (!haveNew)
        return { state: newState, transactions: trs };
    }
  }
  /**
  @internal
  */
  applyInner(tr4) {
    if (!tr4.before.eq(this.doc))
      throw new RangeError("Applying a mismatched transaction");
    let newInstance = new _EditorState(this.config), fields = this.config.fields;
    for (let i3 = 0; i3 < fields.length; i3++) {
      let field = fields[i3];
      newInstance[field.name] = field.apply(tr4, this[field.name], this, newInstance);
    }
    return newInstance;
  }
  /**
  Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.
  */
  get tr() {
    return new Transaction(this);
  }
  /**
  Create a new state.
  */
  static create(config) {
    let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);
    let instance = new _EditorState($config);
    for (let i3 = 0; i3 < $config.fields.length; i3++)
      instance[$config.fields[i3].name] = $config.fields[i3].init(config, instance);
    return instance;
  }
  /**
  Create a new state based on this one, but with an adjusted set
  of active plugins. State fields that exist in both sets of
  plugins are kept unchanged. Those that no longer exist are
  dropped, and those that are new are initialized using their
  [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new
  configuration object..
  */
  reconfigure(config) {
    let $config = new Configuration(this.schema, config.plugins);
    let fields = $config.fields, instance = new _EditorState($config);
    for (let i3 = 0; i3 < fields.length; i3++) {
      let name = fields[i3].name;
      instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i3].init(config, instance);
    }
    return instance;
  }
  /**
  Serialize this state to JSON. If you want to serialize the state
  of plugins, pass an object mapping property names to use in the
  resulting JSON object to plugin objects. The argument may also be
  a string or number, in which case it is ignored, to support the
  way `JSON.stringify` calls `toString` methods.
  */
  toJSON(pluginFields) {
    let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };
    if (this.storedMarks)
      result.storedMarks = this.storedMarks.map((m2) => m2.toJSON());
    if (pluginFields && typeof pluginFields == "object")
      for (let prop in pluginFields) {
        if (prop == "doc" || prop == "selection")
          throw new RangeError("The JSON fields `doc` and `selection` are reserved");
        let plugin = pluginFields[prop], state = plugin.spec.state;
        if (state && state.toJSON)
          result[prop] = state.toJSON.call(plugin, this[plugin.key]);
      }
    return result;
  }
  /**
  Deserialize a JSON representation of a state. `config` should
  have at least a `schema` field, and should contain array of
  plugins to initialize the state with. `pluginFields` can be used
  to deserialize the state of plugins, by associating plugin
  instances with the property names they use in the JSON object.
  */
  static fromJSON(config, json, pluginFields) {
    if (!json)
      throw new RangeError("Invalid input for EditorState.fromJSON");
    if (!config.schema)
      throw new RangeError("Required config field 'schema' missing");
    let $config = new Configuration(config.schema, config.plugins);
    let instance = new _EditorState($config);
    $config.fields.forEach((field) => {
      if (field.name == "doc") {
        instance.doc = Node2.fromJSON(config.schema, json.doc);
      } else if (field.name == "selection") {
        instance.selection = Selection.fromJSON(instance.doc, json.selection);
      } else if (field.name == "storedMarks") {
        if (json.storedMarks)
          instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);
      } else {
        if (pluginFields)
          for (let prop in pluginFields) {
            let plugin = pluginFields[prop], state = plugin.spec.state;
            if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) {
              instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);
              return;
            }
          }
        instance[field.name] = field.init(config, instance);
      }
    });
    return instance;
  }
};
function bindProps(obj, self2, target) {
  for (let prop in obj) {
    let val = obj[prop];
    if (val instanceof Function)
      val = val.bind(self2);
    else if (prop == "handleDOMEvents")
      val = bindProps(val, self2, {});
    target[prop] = val;
  }
  return target;
}
var Plugin = class {
  /**
  Create a plugin.
  */
  constructor(spec) {
    this.spec = spec;
    this.props = {};
    if (spec.props)
      bindProps(spec.props, this, this.props);
    this.key = spec.key ? spec.key.key : createKey("plugin");
  }
  /**
  Extract the plugin's state field from an editor state.
  */
  getState(state) {
    return state[this.key];
  }
};
var keys = /* @__PURE__ */ Object.create(null);
function createKey(name) {
  if (name in keys)
    return name + "$" + ++keys[name];
  keys[name] = 0;
  return name + "$";
}
var PluginKey = class {
  /**
  Create a plugin key.
  */
  constructor(name = "key") {
    this.key = createKey(name);
  }
  /**
  Get the active plugin with this key, if any, from an editor
  state.
  */
  get(state) {
    return state.config.pluginsByKey[this.key];
  }
  /**
  Get the plugin's state from an editor state.
  */
  getState(state) {
    return state[this.key];
  }
};

// ../../node_modules/.pnpm/prosemirror-view@1.41.4/node_modules/prosemirror-view/dist/index.js
var domIndex = function(node2) {
  for (var index4 = 0; ; index4++) {
    node2 = node2.previousSibling;
    if (!node2)
      return index4;
  }
};
var parentNode = function(node2) {
  let parent = node2.assignedSlot || node2.parentNode;
  return parent && parent.nodeType == 11 ? parent.host : parent;
};
var reusedRange = null;
var textRange = function(node2, from4, to2) {
  let range = reusedRange || (reusedRange = document.createRange());
  range.setEnd(node2, to2 == null ? node2.nodeValue.length : to2);
  range.setStart(node2, from4 || 0);
  return range;
};
var clearReusedRange = function() {
  reusedRange = null;
};
var isEquivalentPosition = function(node2, off, targetNode, targetOff) {
  return targetNode && (scanFor(node2, off, targetNode, targetOff, -1) || scanFor(node2, off, targetNode, targetOff, 1));
};
var atomElements = /^(img|br|input|textarea|hr)$/i;
function scanFor(node2, off, targetNode, targetOff, dir) {
  var _a2;
  for (; ; ) {
    if (node2 == targetNode && off == targetOff)
      return true;
    if (off == (dir < 0 ? 0 : nodeSize(node2))) {
      let parent = node2.parentNode;
      if (!parent || parent.nodeType != 1 || hasBlockDesc(node2) || atomElements.test(node2.nodeName) || node2.contentEditable == "false")
        return false;
      off = domIndex(node2) + (dir < 0 ? 0 : 1);
      node2 = parent;
    } else if (node2.nodeType == 1) {
      let child = node2.childNodes[off + (dir < 0 ? -1 : 0)];
      if (child.nodeType == 1 && child.contentEditable == "false") {
        if ((_a2 = child.pmViewDesc) === null || _a2 === void 0 ? void 0 : _a2.ignoreForSelection)
          off += dir;
        else
          return false;
      } else {
        node2 = child;
        off = dir < 0 ? nodeSize(node2) : 0;
      }
    } else {
      return false;
    }
  }
}
function nodeSize(node2) {
  return node2.nodeType == 3 ? node2.nodeValue.length : node2.childNodes.length;
}
function textNodeBefore$1(node2, offset4) {
  for (; ; ) {
    if (node2.nodeType == 3 && offset4)
      return node2;
    if (node2.nodeType == 1 && offset4 > 0) {
      if (node2.contentEditable == "false")
        return null;
      node2 = node2.childNodes[offset4 - 1];
      offset4 = nodeSize(node2);
    } else if (node2.parentNode && !hasBlockDesc(node2)) {
      offset4 = domIndex(node2);
      node2 = node2.parentNode;
    } else {
      return null;
    }
  }
}
function textNodeAfter$1(node2, offset4) {
  for (; ; ) {
    if (node2.nodeType == 3 && offset4 < node2.nodeValue.length)
      return node2;
    if (node2.nodeType == 1 && offset4 < node2.childNodes.length) {
      if (node2.contentEditable == "false")
        return null;
      node2 = node2.childNodes[offset4];
      offset4 = 0;
    } else if (node2.parentNode && !hasBlockDesc(node2)) {
      offset4 = domIndex(node2) + 1;
      node2 = node2.parentNode;
    } else {
      return null;
    }
  }
}
function isOnEdge(node2, offset4, parent) {
  for (let atStart = offset4 == 0, atEnd = offset4 == nodeSize(node2); atStart || atEnd; ) {
    if (node2 == parent)
      return true;
    let index4 = domIndex(node2);
    node2 = node2.parentNode;
    if (!node2)
      return false;
    atStart = atStart && index4 == 0;
    atEnd = atEnd && index4 == nodeSize(node2);
  }
}
function hasBlockDesc(dom) {
  let desc;
  for (let cur = dom; cur; cur = cur.parentNode)
    if (desc = cur.pmViewDesc)
      break;
  return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);
}
var selectionCollapsed = function(domSel) {
  return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);
};
function keyEvent(keyCode, key2) {
  let event = document.createEvent("Event");
  event.initEvent("keydown", true, true);
  event.keyCode = keyCode;
  event.key = event.code = key2;
  return event;
}
function deepActiveElement(doc4) {
  let elt = doc4.activeElement;
  while (elt && elt.shadowRoot)
    elt = elt.shadowRoot.activeElement;
  return elt;
}
function caretFromPoint(doc4, x5, y3) {
  if (doc4.caretPositionFromPoint) {
    try {
      let pos = doc4.caretPositionFromPoint(x5, y3);
      if (pos)
        return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };
    } catch (_2) {
    }
  }
  if (doc4.caretRangeFromPoint) {
    let range = doc4.caretRangeFromPoint(x5, y3);
    if (range)
      return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };
  }
}
var nav = typeof navigator != "undefined" ? navigator : null;
var doc2 = typeof document != "undefined" ? document : null;
var agent = nav && nav.userAgent || "";
var ie_edge = /Edge\/(\d+)/.exec(agent);
var ie_upto10 = /MSIE \d/.exec(agent);
var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent);
var ie = !!(ie_upto10 || ie_11up || ie_edge);
var ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;
var gecko = !ie && /gecko\/(\d+)/i.test(agent);
gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1];
var _chrome = !ie && /Chrome\/(\d+)/.exec(agent);
var chrome = !!_chrome;
var chrome_version = _chrome ? +_chrome[1] : 0;
var safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);
var ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);
var mac = ios || (nav ? /Mac/.test(nav.platform) : false);
var windows = nav ? /Win/.test(nav.platform) : false;
var android = /Android \d/.test(agent);
var webkit = !!doc2 && "webkitFontSmoothing" in doc2.documentElement.style;
var webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;
function windowRect(doc4) {
  let vp = doc4.defaultView && doc4.defaultView.visualViewport;
  if (vp)
    return {
      left: 0,
      right: vp.width,
      top: 0,
      bottom: vp.height
    };
  return {
    left: 0,
    right: doc4.documentElement.clientWidth,
    top: 0,
    bottom: doc4.documentElement.clientHeight
  };
}
function getSide(value, side) {
  return typeof value == "number" ? value : value[side];
}
function clientRect(node2) {
  let rect = node2.getBoundingClientRect();
  let scaleX = rect.width / node2.offsetWidth || 1;
  let scaleY = rect.height / node2.offsetHeight || 1;
  return {
    left: rect.left,
    right: rect.left + node2.clientWidth * scaleX,
    top: rect.top,
    bottom: rect.top + node2.clientHeight * scaleY
  };
}
function scrollRectIntoView(view, rect, startDOM) {
  let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5;
  let doc4 = view.dom.ownerDocument;
  for (let parent = startDOM || view.dom; ; ) {
    if (!parent)
      break;
    if (parent.nodeType != 1) {
      parent = parentNode(parent);
      continue;
    }
    let elt = parent;
    let atTop = elt == doc4.body;
    let bounding = atTop ? windowRect(doc4) : clientRect(elt);
    let moveX = 0, moveY = 0;
    if (rect.top < bounding.top + getSide(scrollThreshold, "top"))
      moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top"));
    else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom"))
      moveY = rect.bottom - rect.top > bounding.bottom - bounding.top ? rect.top + getSide(scrollMargin, "top") - bounding.top : rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom");
    if (rect.left < bounding.left + getSide(scrollThreshold, "left"))
      moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left"));
    else if (rect.right > bounding.right - getSide(scrollThreshold, "right"))
      moveX = rect.right - bounding.right + getSide(scrollMargin, "right");
    if (moveX || moveY) {
      if (atTop) {
        doc4.defaultView.scrollBy(moveX, moveY);
      } else {
        let startX = elt.scrollLeft, startY = elt.scrollTop;
        if (moveY)
          elt.scrollTop += moveY;
        if (moveX)
          elt.scrollLeft += moveX;
        let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY;
        rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };
      }
    }
    let pos = atTop ? "fixed" : getComputedStyle(parent).position;
    if (/^(fixed|sticky)$/.test(pos))
      break;
    parent = pos == "absolute" ? parent.offsetParent : parentNode(parent);
  }
}
function storeScrollPos(view) {
  let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);
  let refDOM, refTop;
  for (let x5 = (rect.left + rect.right) / 2, y3 = startY + 1; y3 < Math.min(innerHeight, rect.bottom); y3 += 5) {
    let dom = view.root.elementFromPoint(x5, y3);
    if (!dom || dom == view.dom || !view.dom.contains(dom))
      continue;
    let localRect = dom.getBoundingClientRect();
    if (localRect.top >= startY - 20) {
      refDOM = dom;
      refTop = localRect.top;
      break;
    }
  }
  return { refDOM, refTop, stack: scrollStack(view.dom) };
}
function scrollStack(dom) {
  let stack = [], doc4 = dom.ownerDocument;
  for (let cur = dom; cur; cur = parentNode(cur)) {
    stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });
    if (dom == doc4)
      break;
  }
  return stack;
}
function resetScrollPos({ refDOM, refTop, stack }) {
  let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;
  restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);
}
function restoreScrollStack(stack, dTop) {
  for (let i3 = 0; i3 < stack.length; i3++) {
    let { dom, top, left } = stack[i3];
    if (dom.scrollTop != top + dTop)
      dom.scrollTop = top + dTop;
    if (dom.scrollLeft != left)
      dom.scrollLeft = left;
  }
}
var preventScrollSupported = null;
function focusPreventScroll(dom) {
  if (dom.setActive)
    return dom.setActive();
  if (preventScrollSupported)
    return dom.focus(preventScrollSupported);
  let stored = scrollStack(dom);
  dom.focus(preventScrollSupported == null ? {
    get preventScroll() {
      preventScrollSupported = { preventScroll: true };
      return true;
    }
  } : void 0);
  if (!preventScrollSupported) {
    preventScrollSupported = false;
    restoreScrollStack(stored, 0);
  }
}
function findOffsetInNode(node2, coords) {
  let closest, dxClosest = 2e8, coordsClosest, offset4 = 0;
  let rowBot = coords.top, rowTop = coords.top;
  let firstBelow, coordsBelow;
  for (let child = node2.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {
    let rects;
    if (child.nodeType == 1)
      rects = child.getClientRects();
    else if (child.nodeType == 3)
      rects = textRange(child).getClientRects();
    else
      continue;
    for (let i3 = 0; i3 < rects.length; i3++) {
      let rect = rects[i3];
      if (rect.top <= rowBot && rect.bottom >= rowTop) {
        rowBot = Math.max(rect.bottom, rowBot);
        rowTop = Math.min(rect.top, rowTop);
        let dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0;
        if (dx < dxClosest) {
          closest = child;
          dxClosest = dx;
          coordsClosest = dx && closest.nodeType == 3 ? {
            left: rect.right < coords.left ? rect.right : rect.left,
            top: coords.top
          } : coords;
          if (child.nodeType == 1 && dx)
            offset4 = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);
          continue;
        }
      } else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {
        firstBelow = child;
        coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };
      }
      if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom))
        offset4 = childIndex + 1;
    }
  }
  if (!closest && firstBelow) {
    closest = firstBelow;
    coordsClosest = coordsBelow;
    dxClosest = 0;
  }
  if (closest && closest.nodeType == 3)
    return findOffsetInText(closest, coordsClosest);
  if (!closest || dxClosest && closest.nodeType == 1)
    return { node: node2, offset: offset4 };
  return findOffsetInNode(closest, coordsClosest);
}
function findOffsetInText(node2, coords) {
  let len = node2.nodeValue.length;
  let range = document.createRange(), result;
  for (let i3 = 0; i3 < len; i3++) {
    range.setEnd(node2, i3 + 1);
    range.setStart(node2, i3);
    let rect = singleRect(range, 1);
    if (rect.top == rect.bottom)
      continue;
    if (inRect(coords, rect)) {
      result = { node: node2, offset: i3 + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };
      break;
    }
  }
  range.detach();
  return result || { node: node2, offset: 0 };
}
function inRect(coords, rect) {
  return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;
}
function targetKludge(dom, coords) {
  let parent = dom.parentNode;
  if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)
    return parent;
  return dom;
}
function posFromElement(view, elt, coords) {
  let { node: node2, offset: offset4 } = findOffsetInNode(elt, coords), bias = -1;
  if (node2.nodeType == 1 && !node2.firstChild) {
    let rect = node2.getBoundingClientRect();
    bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;
  }
  return view.docView.posFromDOM(node2, offset4, bias);
}
function posFromCaret(view, node2, offset4, coords) {
  let outsideBlock = -1;
  for (let cur = node2, sawBlock = false; ; ) {
    if (cur == view.dom)
      break;
    let desc = view.docView.nearestDesc(cur, true), rect;
    if (!desc)
      return null;
    if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) && // Ignore elements with zero-size bounding rectangles
    ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {
      if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) {
        if (!sawBlock && rect.left > coords.left || rect.top > coords.top)
          outsideBlock = desc.posBefore;
        else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)
          outsideBlock = desc.posAfter;
        sawBlock = true;
      }
      if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {
        let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2 : coords.left < (rect.left + rect.right) / 2;
        return before ? desc.posBefore : desc.posAfter;
      }
    }
    cur = desc.dom.parentNode;
  }
  return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node2, offset4, -1);
}
function elementFromPoint(element7, coords, box) {
  let len = element7.childNodes.length;
  if (len && box.top < box.bottom) {
    for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i3 = startI; ; ) {
      let child = element7.childNodes[i3];
      if (child.nodeType == 1) {
        let rects = child.getClientRects();
        for (let j4 = 0; j4 < rects.length; j4++) {
          let rect = rects[j4];
          if (inRect(coords, rect))
            return elementFromPoint(child, coords, rect);
        }
      }
      if ((i3 = (i3 + 1) % len) == startI)
        break;
    }
  }
  return element7;
}
function posAtCoords(view, coords) {
  let doc4 = view.dom.ownerDocument, node2, offset4 = 0;
  let caret = caretFromPoint(doc4, coords.left, coords.top);
  if (caret)
    ({ node: node2, offset: offset4 } = caret);
  let elt = (view.root.elementFromPoint ? view.root : doc4).elementFromPoint(coords.left, coords.top);
  let pos;
  if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {
    let box = view.dom.getBoundingClientRect();
    if (!inRect(coords, box))
      return null;
    elt = elementFromPoint(view.dom, coords, box);
    if (!elt)
      return null;
  }
  if (safari) {
    for (let p4 = elt; node2 && p4; p4 = parentNode(p4))
      if (p4.draggable)
        node2 = void 0;
  }
  elt = targetKludge(elt, coords);
  if (node2) {
    if (gecko && node2.nodeType == 1) {
      offset4 = Math.min(offset4, node2.childNodes.length);
      if (offset4 < node2.childNodes.length) {
        let next2 = node2.childNodes[offset4], box;
        if (next2.nodeName == "IMG" && (box = next2.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top)
          offset4++;
      }
    }
    let prev;
    if (webkit && offset4 && node2.nodeType == 1 && (prev = node2.childNodes[offset4 - 1]).nodeType == 1 && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top)
      offset4--;
    if (node2 == view.dom && offset4 == node2.childNodes.length - 1 && node2.lastChild.nodeType == 1 && coords.top > node2.lastChild.getBoundingClientRect().bottom)
      pos = view.state.doc.content.size;
    else if (offset4 == 0 || node2.nodeType != 1 || node2.childNodes[offset4 - 1].nodeName != "BR")
      pos = posFromCaret(view, node2, offset4, coords);
  }
  if (pos == null)
    pos = posFromElement(view, elt, coords);
  let desc = view.docView.nearestDesc(elt, true);
  return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };
}
function nonZero(rect) {
  return rect.top < rect.bottom || rect.left < rect.right;
}
function singleRect(target, bias) {
  let rects = target.getClientRects();
  if (rects.length) {
    let first2 = rects[bias < 0 ? 0 : rects.length - 1];
    if (nonZero(first2))
      return first2;
  }
  return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect();
}
var BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
function coordsAtPos(view, pos, side) {
  let { node: node2, offset: offset4, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);
  let supportEmptyRange = webkit || gecko;
  if (node2.nodeType == 3) {
    if (supportEmptyRange && (BIDI.test(node2.nodeValue) || (side < 0 ? !offset4 : offset4 == node2.nodeValue.length))) {
      let rect = singleRect(textRange(node2, offset4, offset4), side);
      if (gecko && offset4 && /\s/.test(node2.nodeValue[offset4 - 1]) && offset4 < node2.nodeValue.length) {
        let rectBefore = singleRect(textRange(node2, offset4 - 1, offset4 - 1), -1);
        if (rectBefore.top == rect.top) {
          let rectAfter = singleRect(textRange(node2, offset4, offset4 + 1), -1);
          if (rectAfter.top != rect.top)
            return flattenV(rectAfter, rectAfter.left < rectBefore.left);
        }
      }
      return rect;
    } else {
      let from4 = offset4, to2 = offset4, takeSide = side < 0 ? 1 : -1;
      if (side < 0 && !offset4) {
        to2++;
        takeSide = -1;
      } else if (side >= 0 && offset4 == node2.nodeValue.length) {
        from4--;
        takeSide = 1;
      } else if (side < 0) {
        from4--;
      } else {
        to2++;
      }
      return flattenV(singleRect(textRange(node2, from4, to2), takeSide), takeSide < 0);
    }
  }
  let $dom = view.state.doc.resolve(pos - (atom || 0));
  if (!$dom.parent.inlineContent) {
    if (atom == null && offset4 && (side < 0 || offset4 == nodeSize(node2))) {
      let before = node2.childNodes[offset4 - 1];
      if (before.nodeType == 1)
        return flattenH(before.getBoundingClientRect(), false);
    }
    if (atom == null && offset4 < nodeSize(node2)) {
      let after = node2.childNodes[offset4];
      if (after.nodeType == 1)
        return flattenH(after.getBoundingClientRect(), true);
    }
    return flattenH(node2.getBoundingClientRect(), side >= 0);
  }
  if (atom == null && offset4 && (side < 0 || offset4 == nodeSize(node2))) {
    let before = node2.childNodes[offset4 - 1];
    let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1)) : before.nodeType == 1 && (before.nodeName != "BR" || !before.nextSibling) ? before : null;
    if (target)
      return flattenV(singleRect(target, 1), false);
  }
  if (atom == null && offset4 < nodeSize(node2)) {
    let after = node2.childNodes[offset4];
    while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)
      after = after.nextSibling;
    let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, supportEmptyRange ? 0 : 1) : after.nodeType == 1 ? after : null;
    if (target)
      return flattenV(singleRect(target, -1), true);
  }
  return flattenV(singleRect(node2.nodeType == 3 ? textRange(node2) : node2, -side), side >= 0);
}
function flattenV(rect, left) {
  if (rect.width == 0)
    return rect;
  let x5 = left ? rect.left : rect.right;
  return { top: rect.top, bottom: rect.bottom, left: x5, right: x5 };
}
function flattenH(rect, top) {
  if (rect.height == 0)
    return rect;
  let y3 = top ? rect.top : rect.bottom;
  return { top: y3, bottom: y3, left: rect.left, right: rect.right };
}
function withFlushedState(view, state, f6) {
  let viewState = view.state, active = view.root.activeElement;
  if (viewState != state)
    view.updateState(state);
  if (active != view.dom)
    view.focus();
  try {
    return f6();
  } finally {
    if (viewState != state)
      view.updateState(viewState);
    if (active != view.dom && active)
      active.focus();
  }
}
function endOfTextblockVertical(view, state, dir) {
  let sel = state.selection;
  let $pos = dir == "up" ? sel.$from : sel.$to;
  return withFlushedState(view, state, () => {
    let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1);
    for (; ; ) {
      let nearest = view.docView.nearestDesc(dom, true);
      if (!nearest)
        break;
      if (nearest.node.isBlock) {
        dom = nearest.contentDOM || nearest.dom;
        break;
      }
      dom = nearest.dom.parentNode;
    }
    let coords = coordsAtPos(view, $pos.pos, 1);
    for (let child = dom.firstChild; child; child = child.nextSibling) {
      let boxes;
      if (child.nodeType == 1)
        boxes = child.getClientRects();
      else if (child.nodeType == 3)
        boxes = textRange(child, 0, child.nodeValue.length).getClientRects();
      else
        continue;
      for (let i3 = 0; i3 < boxes.length; i3++) {
        let box = boxes[i3];
        if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))
          return false;
      }
    }
    return true;
  });
}
var maybeRTL = /[\u0590-\u08ac]/;
function endOfTextblockHorizontal(view, state, dir) {
  let { $head } = state.selection;
  if (!$head.parent.isTextblock)
    return false;
  let offset4 = $head.parentOffset, atStart = !offset4, atEnd = offset4 == $head.parent.content.size;
  let sel = view.domSelection();
  if (!sel)
    return $head.pos == $head.start() || $head.pos == $head.end();
  if (!maybeRTL.test($head.parent.textContent) || !sel.modify)
    return dir == "left" || dir == "backward" ? atStart : atEnd;
  return withFlushedState(view, state, () => {
    let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();
    let oldBidiLevel = sel.caretBidiLevel;
    sel.modify("move", dir, "character");
    let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;
    let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();
    let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) || oldNode == newNode && oldOff == newOff;
    try {
      sel.collapse(anchorNode, anchorOffset);
      if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)
        sel.extend(oldNode, oldOff);
    } catch (_2) {
    }
    if (oldBidiLevel != null)
      sel.caretBidiLevel = oldBidiLevel;
    return result;
  });
}
var cachedState = null;
var cachedDir = null;
var cachedResult = false;
function endOfTextblock(view, state, dir) {
  if (cachedState == state && cachedDir == dir)
    return cachedResult;
  cachedState = state;
  cachedDir = dir;
  return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir);
}
var NOT_DIRTY = 0;
var CHILD_DIRTY = 1;
var CONTENT_DIRTY = 2;
var NODE_DIRTY = 3;
var ViewDesc = class {
  constructor(parent, children, dom, contentDOM) {
    this.parent = parent;
    this.children = children;
    this.dom = dom;
    this.contentDOM = contentDOM;
    this.dirty = NOT_DIRTY;
    dom.pmViewDesc = this;
  }
  // Used to check whether a given description corresponds to a
  // widget/mark/node.
  matchesWidget(widget) {
    return false;
  }
  matchesMark(mark2) {
    return false;
  }
  matchesNode(node2, outerDeco, innerDeco) {
    return false;
  }
  matchesHack(nodeName) {
    return false;
  }
  // When parsing in-editor content (in domchange.js), we allow
  // descriptions to determine the parse rules that should be used to
  // parse them.
  parseRule() {
    return null;
  }
  // Used by the editor's event handler to ignore events that come
  // from certain descs.
  stopEvent(event) {
    return false;
  }
  // The size of the content represented by this desc.
  get size() {
    let size5 = 0;
    for (let i3 = 0; i3 < this.children.length; i3++)
      size5 += this.children[i3].size;
    return size5;
  }
  // For block nodes, this represents the space taken up by their
  // start/end tokens.
  get border() {
    return 0;
  }
  destroy() {
    this.parent = void 0;
    if (this.dom.pmViewDesc == this)
      this.dom.pmViewDesc = void 0;
    for (let i3 = 0; i3 < this.children.length; i3++)
      this.children[i3].destroy();
  }
  posBeforeChild(child) {
    for (let i3 = 0, pos = this.posAtStart; ; i3++) {
      let cur = this.children[i3];
      if (cur == child)
        return pos;
      pos += cur.size;
    }
  }
  get posBefore() {
    return this.parent.posBeforeChild(this);
  }
  get posAtStart() {
    return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;
  }
  get posAfter() {
    return this.posBefore + this.size;
  }
  get posAtEnd() {
    return this.posAtStart + this.size - 2 * this.border;
  }
  localPosFromDOM(dom, offset4, bias) {
    if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {
      if (bias < 0) {
        let domBefore, desc;
        if (dom == this.contentDOM) {
          domBefore = dom.childNodes[offset4 - 1];
        } else {
          while (dom.parentNode != this.contentDOM)
            dom = dom.parentNode;
          domBefore = dom.previousSibling;
        }
        while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))
          domBefore = domBefore.previousSibling;
        return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;
      } else {
        let domAfter, desc;
        if (dom == this.contentDOM) {
          domAfter = dom.childNodes[offset4];
        } else {
          while (dom.parentNode != this.contentDOM)
            dom = dom.parentNode;
          domAfter = dom.nextSibling;
        }
        while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))
          domAfter = domAfter.nextSibling;
        return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;
      }
    }
    let atEnd;
    if (dom == this.dom && this.contentDOM) {
      atEnd = offset4 > domIndex(this.contentDOM);
    } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {
      atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;
    } else if (this.dom.firstChild) {
      if (offset4 == 0)
        for (let search3 = dom; ; search3 = search3.parentNode) {
          if (search3 == this.dom) {
            atEnd = false;
            break;
          }
          if (search3.previousSibling)
            break;
        }
      if (atEnd == null && offset4 == dom.childNodes.length)
        for (let search3 = dom; ; search3 = search3.parentNode) {
          if (search3 == this.dom) {
            atEnd = true;
            break;
          }
          if (search3.nextSibling)
            break;
        }
    }
    return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;
  }
  nearestDesc(dom, onlyNodes = false) {
    for (let first2 = true, cur = dom; cur; cur = cur.parentNode) {
      let desc = this.getDesc(cur), nodeDOM;
      if (desc && (!onlyNodes || desc.node)) {
        if (first2 && (nodeDOM = desc.nodeDOM) && !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom))
          first2 = false;
        else
          return desc;
      }
    }
  }
  getDesc(dom) {
    let desc = dom.pmViewDesc;
    for (let cur = desc; cur; cur = cur.parent)
      if (cur == this)
        return desc;
  }
  posFromDOM(dom, offset4, bias) {
    for (let scan = dom; scan; scan = scan.parentNode) {
      let desc = this.getDesc(scan);
      if (desc)
        return desc.localPosFromDOM(dom, offset4, bias);
    }
    return -1;
  }
  // Find the desc for the node after the given pos, if any. (When a
  // parent node overrode rendering, there might not be one.)
  descAt(pos) {
    for (let i3 = 0, offset4 = 0; i3 < this.children.length; i3++) {
      let child = this.children[i3], end = offset4 + child.size;
      if (offset4 == pos && end != offset4) {
        while (!child.border && child.children.length) {
          for (let i4 = 0; i4 < child.children.length; i4++) {
            let inner = child.children[i4];
            if (inner.size) {
              child = inner;
              break;
            }
          }
        }
        return child;
      }
      if (pos < end)
        return child.descAt(pos - offset4 - child.border);
      offset4 = end;
    }
  }
  domFromPos(pos, side) {
    if (!this.contentDOM)
      return { node: this.dom, offset: 0, atom: pos + 1 };
    let i3 = 0, offset4 = 0;
    for (let curPos = 0; i3 < this.children.length; i3++) {
      let child = this.children[i3], end = curPos + child.size;
      if (end > pos || child instanceof TrailingHackViewDesc) {
        offset4 = pos - curPos;
        break;
      }
      curPos = end;
    }
    if (offset4)
      return this.children[i3].domFromPos(offset4 - this.children[i3].border, side);
    for (let prev; i3 && !(prev = this.children[i3 - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i3--) {
    }
    if (side <= 0) {
      let prev, enter2 = true;
      for (; ; i3--, enter2 = false) {
        prev = i3 ? this.children[i3 - 1] : null;
        if (!prev || prev.dom.parentNode == this.contentDOM)
          break;
      }
      if (prev && side && enter2 && !prev.border && !prev.domAtom)
        return prev.domFromPos(prev.size, side);
      return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };
    } else {
      let next2, enter2 = true;
      for (; ; i3++, enter2 = false) {
        next2 = i3 < this.children.length ? this.children[i3] : null;
        if (!next2 || next2.dom.parentNode == this.contentDOM)
          break;
      }
      if (next2 && enter2 && !next2.border && !next2.domAtom)
        return next2.domFromPos(0, side);
      return { node: this.contentDOM, offset: next2 ? domIndex(next2.dom) : this.contentDOM.childNodes.length };
    }
  }
  // Used to find a DOM range in a single parent for a given changed
  // range.
  parseRange(from4, to2, base4 = 0) {
    if (this.children.length == 0)
      return { node: this.contentDOM, from: from4, to: to2, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };
    let fromOffset = -1, toOffset = -1;
    for (let offset4 = base4, i3 = 0; ; i3++) {
      let child = this.children[i3], end = offset4 + child.size;
      if (fromOffset == -1 && from4 <= end) {
        let childBase = offset4 + child.border;
        if (from4 >= childBase && to2 <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM))
          return child.parseRange(from4, to2, childBase);
        from4 = offset4;
        for (let j4 = i3; j4 > 0; j4--) {
          let prev = this.children[j4 - 1];
          if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {
            fromOffset = domIndex(prev.dom) + 1;
            break;
          }
          from4 -= prev.size;
        }
        if (fromOffset == -1)
          fromOffset = 0;
      }
      if (fromOffset > -1 && (end > to2 || i3 == this.children.length - 1)) {
        to2 = end;
        for (let j4 = i3 + 1; j4 < this.children.length; j4++) {
          let next2 = this.children[j4];
          if (next2.size && next2.dom.parentNode == this.contentDOM && !next2.emptyChildAt(-1)) {
            toOffset = domIndex(next2.dom);
            break;
          }
          to2 += next2.size;
        }
        if (toOffset == -1)
          toOffset = this.contentDOM.childNodes.length;
        break;
      }
      offset4 = end;
    }
    return { node: this.contentDOM, from: from4, to: to2, fromOffset, toOffset };
  }
  emptyChildAt(side) {
    if (this.border || !this.contentDOM || !this.children.length)
      return false;
    let child = this.children[side < 0 ? 0 : this.children.length - 1];
    return child.size == 0 || child.emptyChildAt(side);
  }
  domAfterPos(pos) {
    let { node: node2, offset: offset4 } = this.domFromPos(pos, 0);
    if (node2.nodeType != 1 || offset4 == node2.childNodes.length)
      throw new RangeError("No node after pos " + pos);
    return node2.childNodes[offset4];
  }
  // View descs are responsible for setting any selection that falls
  // entirely inside of them, so that custom implementations can do
  // custom things with the selection. Note that this falls apart when
  // a selection starts in such a node and ends in another, in which
  // case we just use whatever domFromPos produces as a best effort.
  setSelection(anchor, head2, view, force = false) {
    let from4 = Math.min(anchor, head2), to2 = Math.max(anchor, head2);
    for (let i3 = 0, offset4 = 0; i3 < this.children.length; i3++) {
      let child = this.children[i3], end = offset4 + child.size;
      if (from4 > offset4 && to2 < end)
        return child.setSelection(anchor - offset4 - child.border, head2 - offset4 - child.border, view, force);
      offset4 = end;
    }
    let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);
    let headDOM = head2 == anchor ? anchorDOM : this.domFromPos(head2, head2 ? -1 : 1);
    let domSel = view.root.getSelection();
    let selRange = view.domSelectionRange();
    let brKludge = false;
    if ((gecko || safari) && anchor == head2) {
      let { node: node2, offset: offset4 } = anchorDOM;
      if (node2.nodeType == 3) {
        brKludge = !!(offset4 && node2.nodeValue[offset4 - 1] == "\n");
        if (brKludge && offset4 == node2.nodeValue.length) {
          for (let scan = node2, after; scan; scan = scan.parentNode) {
            if (after = scan.nextSibling) {
              if (after.nodeName == "BR")
                anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };
              break;
            }
            let desc = scan.pmViewDesc;
            if (desc && desc.node && desc.node.isBlock)
              break;
          }
        }
      } else {
        let prev = node2.childNodes[offset4 - 1];
        brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false");
      }
    }
    if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) {
      let after = selRange.focusNode.childNodes[selRange.focusOffset];
      if (after && after.contentEditable == "false")
        force = true;
    }
    if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))
      return;
    let domSelExtended = false;
    if ((domSel.extend || anchor == head2) && !(brKludge && gecko)) {
      domSel.collapse(anchorDOM.node, anchorDOM.offset);
      try {
        if (anchor != head2)
          domSel.extend(headDOM.node, headDOM.offset);
        domSelExtended = true;
      } catch (_2) {
      }
    }
    if (!domSelExtended) {
      if (anchor > head2) {
        let tmp = anchorDOM;
        anchorDOM = headDOM;
        headDOM = tmp;
      }
      let range = document.createRange();
      range.setEnd(headDOM.node, headDOM.offset);
      range.setStart(anchorDOM.node, anchorDOM.offset);
      domSel.removeAllRanges();
      domSel.addRange(range);
    }
  }
  ignoreMutation(mutation) {
    return !this.contentDOM && mutation.type != "selection";
  }
  get contentLost() {
    return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);
  }
  // Remove a subtree of the element tree that has been touched
  // by a DOM change, so that the next update will redraw it.
  markDirty(from4, to2) {
    for (let offset4 = 0, i3 = 0; i3 < this.children.length; i3++) {
      let child = this.children[i3], end = offset4 + child.size;
      if (offset4 == end ? from4 <= end && to2 >= offset4 : from4 < end && to2 > offset4) {
        let startInside = offset4 + child.border, endInside = end - child.border;
        if (from4 >= startInside && to2 <= endInside) {
          this.dirty = from4 == offset4 || to2 == end ? CONTENT_DIRTY : CHILD_DIRTY;
          if (from4 == startInside && to2 == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM))
            child.dirty = NODE_DIRTY;
          else
            child.markDirty(from4 - startInside, to2 - startInside);
          return;
        } else {
          child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length ? CONTENT_DIRTY : NODE_DIRTY;
        }
      }
      offset4 = end;
    }
    this.dirty = CONTENT_DIRTY;
  }
  markParentsDirty() {
    let level = 1;
    for (let node2 = this.parent; node2; node2 = node2.parent, level++) {
      let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;
      if (node2.dirty < dirty)
        node2.dirty = dirty;
    }
  }
  get domAtom() {
    return false;
  }
  get ignoreForCoords() {
    return false;
  }
  get ignoreForSelection() {
    return false;
  }
  isText(text10) {
    return false;
  }
};
var WidgetViewDesc = class extends ViewDesc {
  constructor(parent, widget, view, pos) {
    let self2, dom = widget.type.toDOM;
    if (typeof dom == "function")
      dom = dom(view, () => {
        if (!self2)
          return pos;
        if (self2.parent)
          return self2.parent.posBeforeChild(self2);
      });
    if (!widget.type.spec.raw) {
      if (dom.nodeType != 1) {
        let wrap5 = document.createElement("span");
        wrap5.appendChild(dom);
        dom = wrap5;
      }
      dom.contentEditable = "false";
      dom.classList.add("ProseMirror-widget");
    }
    super(parent, [], dom, null);
    this.widget = widget;
    this.widget = widget;
    self2 = this;
  }
  matchesWidget(widget) {
    return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);
  }
  parseRule() {
    return { ignore: true };
  }
  stopEvent(event) {
    let stop = this.widget.spec.stopEvent;
    return stop ? stop(event) : false;
  }
  ignoreMutation(mutation) {
    return mutation.type != "selection" || this.widget.spec.ignoreSelection;
  }
  destroy() {
    this.widget.type.destroy(this.dom);
    super.destroy();
  }
  get domAtom() {
    return true;
  }
  get ignoreForSelection() {
    return !!this.widget.type.spec.relaxedSide;
  }
  get side() {
    return this.widget.type.side;
  }
};
var CompositionViewDesc = class extends ViewDesc {
  constructor(parent, dom, textDOM, text10) {
    super(parent, [], dom, null);
    this.textDOM = textDOM;
    this.text = text10;
  }
  get size() {
    return this.text.length;
  }
  localPosFromDOM(dom, offset4) {
    if (dom != this.textDOM)
      return this.posAtStart + (offset4 ? this.size : 0);
    return this.posAtStart + offset4;
  }
  domFromPos(pos) {
    return { node: this.textDOM, offset: pos };
  }
  ignoreMutation(mut) {
    return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue;
  }
};
var MarkViewDesc = class _MarkViewDesc extends ViewDesc {
  constructor(parent, mark2, dom, contentDOM, spec) {
    super(parent, [], dom, contentDOM);
    this.mark = mark2;
    this.spec = spec;
  }
  static create(parent, mark2, inline4, view) {
    let custom = view.nodeViews[mark2.type.name];
    let spec = custom && custom(mark2, view, inline4);
    if (!spec || !spec.dom)
      spec = DOMSerializer.renderSpec(document, mark2.type.spec.toDOM(mark2, inline4), null, mark2.attrs);
    return new _MarkViewDesc(parent, mark2, spec.dom, spec.contentDOM || spec.dom, spec);
  }
  parseRule() {
    if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView)
      return null;
    return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };
  }
  matchesMark(mark2) {
    return this.dirty != NODE_DIRTY && this.mark.eq(mark2);
  }
  markDirty(from4, to2) {
    super.markDirty(from4, to2);
    if (this.dirty != NOT_DIRTY) {
      let parent = this.parent;
      while (!parent.node)
        parent = parent.parent;
      if (parent.dirty < this.dirty)
        parent.dirty = this.dirty;
      this.dirty = NOT_DIRTY;
    }
  }
  slice(from4, to2, view) {
    let copy3 = _MarkViewDesc.create(this.parent, this.mark, true, view);
    let nodes = this.children, size5 = this.size;
    if (to2 < size5)
      nodes = replaceNodes(nodes, to2, size5, view);
    if (from4 > 0)
      nodes = replaceNodes(nodes, 0, from4, view);
    for (let i3 = 0; i3 < nodes.length; i3++)
      nodes[i3].parent = copy3;
    copy3.children = nodes;
    return copy3;
  }
  ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
  }
  destroy() {
    if (this.spec.destroy)
      this.spec.destroy();
    super.destroy();
  }
};
var NodeViewDesc = class _NodeViewDesc extends ViewDesc {
  constructor(parent, node2, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {
    super(parent, [], dom, contentDOM);
    this.node = node2;
    this.outerDeco = outerDeco;
    this.innerDeco = innerDeco;
    this.nodeDOM = nodeDOM;
  }
  // By default, a node is rendered using the `toDOM` method from the
  // node type spec. But client code can use the `nodeViews` spec to
  // supply a custom node view, which can influence various aspects of
  // the way the node works.
  //
  // (Using subclassing for this was intentionally decided against,
  // since it'd require exposing a whole slew of finicky
  // implementation details to the user code that they probably will
  // never need.)
  static create(parent, node2, outerDeco, innerDeco, view, pos) {
    let custom = view.nodeViews[node2.type.name], descObj;
    let spec = custom && custom(node2, view, () => {
      if (!descObj)
        return pos;
      if (descObj.parent)
        return descObj.parent.posBeforeChild(descObj);
    }, outerDeco, innerDeco);
    let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;
    if (node2.isText) {
      if (!dom)
        dom = document.createTextNode(node2.text);
      else if (dom.nodeType != 3)
        throw new RangeError("Text must be rendered as a DOM text node");
    } else if (!dom) {
      let spec2 = DOMSerializer.renderSpec(document, node2.type.spec.toDOM(node2), null, node2.attrs);
      ({ dom, contentDOM } = spec2);
    }
    if (!contentDOM && !node2.isText && dom.nodeName != "BR") {
      if (!dom.hasAttribute("contenteditable"))
        dom.contentEditable = "false";
      if (node2.type.spec.draggable)
        dom.draggable = true;
    }
    let nodeDOM = dom;
    dom = applyOuterDeco(dom, outerDeco, node2);
    if (spec)
      return descObj = new CustomNodeViewDesc(parent, node2, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1);
    else if (node2.isText)
      return new TextViewDesc(parent, node2, outerDeco, innerDeco, dom, nodeDOM, view);
    else
      return new _NodeViewDesc(parent, node2, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1);
  }
  parseRule() {
    if (this.node.type.spec.reparseInView)
      return null;
    let rule = { node: this.node.type.name, attrs: this.node.attrs };
    if (this.node.type.whitespace == "pre")
      rule.preserveWhitespace = "full";
    if (!this.contentDOM) {
      rule.getContent = () => this.node.content;
    } else if (!this.contentLost) {
      rule.contentElement = this.contentDOM;
    } else {
      for (let i3 = this.children.length - 1; i3 >= 0; i3--) {
        let child = this.children[i3];
        if (this.dom.contains(child.dom.parentNode)) {
          rule.contentElement = child.dom.parentNode;
          break;
        }
      }
      if (!rule.contentElement)
        rule.getContent = () => Fragment.empty;
    }
    return rule;
  }
  matchesNode(node2, outerDeco, innerDeco) {
    return this.dirty == NOT_DIRTY && node2.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);
  }
  get size() {
    return this.node.nodeSize;
  }
  get border() {
    return this.node.isLeaf ? 0 : 1;
  }
  // Syncs `this.children` to match `this.node.content` and the local
  // decorations, possibly introducing nesting for marks. Then, in a
  // separate step, syncs the DOM inside `this.contentDOM` to
  // `this.children`.
  updateChildren(view, pos) {
    let inline4 = this.node.inlineContent, off = pos;
    let composition = view.composing ? this.localCompositionInfo(view, pos) : null;
    let localComposition = composition && composition.pos > -1 ? composition : null;
    let compositionInChild = composition && composition.pos < 0;
    let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);
    iterDeco(this.node, this.innerDeco, (widget, i3, insideNode) => {
      if (widget.spec.marks)
        updater.syncToMarks(widget.spec.marks, inline4, view);
      else if (widget.type.side >= 0 && !insideNode)
        updater.syncToMarks(i3 == this.node.childCount ? Mark.none : this.node.child(i3).marks, inline4, view);
      updater.placeWidget(widget, view, off);
    }, (child, outerDeco, innerDeco, i3) => {
      updater.syncToMarks(child.marks, inline4, view);
      let compIndex;
      if (updater.findNodeMatch(child, outerDeco, innerDeco, i3)) ;
      else if (compositionInChild && view.state.selection.from > off && view.state.selection.to < off + child.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;
      else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i3, off)) ;
      else {
        updater.addNode(child, outerDeco, innerDeco, view, off);
      }
      off += child.nodeSize;
    });
    updater.syncToMarks([], inline4, view);
    if (this.node.isTextblock)
      updater.addTextblockHacks();
    updater.destroyRest();
    if (updater.changed || this.dirty == CONTENT_DIRTY) {
      if (localComposition)
        this.protectLocalComposition(view, localComposition);
      renderDescs(this.contentDOM, this.children, view);
      if (ios)
        iosHacks(this.dom);
    }
  }
  localCompositionInfo(view, pos) {
    let { from: from4, to: to2 } = view.state.selection;
    if (!(view.state.selection instanceof TextSelection) || from4 < pos || to2 > pos + this.node.content.size)
      return null;
    let textNode = view.input.compositionNode;
    if (!textNode || !this.dom.contains(textNode.parentNode))
      return null;
    if (this.node.inlineContent) {
      let text10 = textNode.nodeValue;
      let textPos = findTextInFragment(this.node.content, text10, from4 - pos, to2 - pos);
      return textPos < 0 ? null : { node: textNode, pos: textPos, text: text10 };
    } else {
      return { node: textNode, pos: -1, text: "" };
    }
  }
  protectLocalComposition(view, { node: node2, pos, text: text10 }) {
    if (this.getDesc(node2))
      return;
    let topNode = node2;
    for (; ; topNode = topNode.parentNode) {
      if (topNode.parentNode == this.contentDOM)
        break;
      while (topNode.previousSibling)
        topNode.parentNode.removeChild(topNode.previousSibling);
      while (topNode.nextSibling)
        topNode.parentNode.removeChild(topNode.nextSibling);
      if (topNode.pmViewDesc)
        topNode.pmViewDesc = void 0;
    }
    let desc = new CompositionViewDesc(this, topNode, node2, text10);
    view.input.compositionNodes.push(desc);
    this.children = replaceNodes(this.children, pos, pos + text10.length, view, desc);
  }
  // If this desc must be updated to match the given node decoration,
  // do so and return true.
  update(node2, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || !node2.sameMarkup(this.node))
      return false;
    this.updateInner(node2, outerDeco, innerDeco, view);
    return true;
  }
  updateInner(node2, outerDeco, innerDeco, view) {
    this.updateOuterDeco(outerDeco);
    this.node = node2;
    this.innerDeco = innerDeco;
    if (this.contentDOM)
      this.updateChildren(view, this.posAtStart);
    this.dirty = NOT_DIRTY;
  }
  updateOuterDeco(outerDeco) {
    if (sameOuterDeco(outerDeco, this.outerDeco))
      return;
    let needsWrap = this.nodeDOM.nodeType != 1;
    let oldDOM = this.dom;
    this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));
    if (this.dom != oldDOM) {
      oldDOM.pmViewDesc = void 0;
      this.dom.pmViewDesc = this;
    }
    this.outerDeco = outerDeco;
  }
  // Mark this node as being the selected node.
  selectNode() {
    if (this.nodeDOM.nodeType == 1) {
      this.nodeDOM.classList.add("ProseMirror-selectednode");
      if (this.contentDOM || !this.node.type.spec.draggable)
        this.nodeDOM.draggable = true;
    }
  }
  // Remove selected node marking from this node.
  deselectNode() {
    if (this.nodeDOM.nodeType == 1) {
      this.nodeDOM.classList.remove("ProseMirror-selectednode");
      if (this.contentDOM || !this.node.type.spec.draggable)
        this.nodeDOM.removeAttribute("draggable");
    }
  }
  get domAtom() {
    return this.node.isAtom;
  }
};
function docViewDesc(doc4, outerDeco, innerDeco, dom, view) {
  applyOuterDeco(dom, outerDeco, doc4);
  let docView = new NodeViewDesc(void 0, doc4, outerDeco, innerDeco, dom, dom, dom, view, 0);
  if (docView.contentDOM)
    docView.updateChildren(view, 0);
  return docView;
}
var TextViewDesc = class _TextViewDesc extends NodeViewDesc {
  constructor(parent, node2, outerDeco, innerDeco, dom, nodeDOM, view) {
    super(parent, node2, outerDeco, innerDeco, dom, null, nodeDOM, view, 0);
  }
  parseRule() {
    let skip = this.nodeDOM.parentNode;
    while (skip && skip != this.dom && !skip.pmIsDeco)
      skip = skip.parentNode;
    return { skip: skip || true };
  }
  update(node2, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node2.sameMarkup(this.node))
      return false;
    this.updateOuterDeco(outerDeco);
    if ((this.dirty != NOT_DIRTY || node2.text != this.node.text) && node2.text != this.nodeDOM.nodeValue) {
      this.nodeDOM.nodeValue = node2.text;
      if (view.trackWrites == this.nodeDOM)
        view.trackWrites = null;
    }
    this.node = node2;
    this.dirty = NOT_DIRTY;
    return true;
  }
  inParent() {
    let parentDOM = this.parent.contentDOM;
    for (let n = this.nodeDOM; n; n = n.parentNode)
      if (n == parentDOM)
        return true;
    return false;
  }
  domFromPos(pos) {
    return { node: this.nodeDOM, offset: pos };
  }
  localPosFromDOM(dom, offset4, bias) {
    if (dom == this.nodeDOM)
      return this.posAtStart + Math.min(offset4, this.node.text.length);
    return super.localPosFromDOM(dom, offset4, bias);
  }
  ignoreMutation(mutation) {
    return mutation.type != "characterData" && mutation.type != "selection";
  }
  slice(from4, to2, view) {
    let node2 = this.node.cut(from4, to2), dom = document.createTextNode(node2.text);
    return new _TextViewDesc(this.parent, node2, this.outerDeco, this.innerDeco, dom, dom, view);
  }
  markDirty(from4, to2) {
    super.markDirty(from4, to2);
    if (this.dom != this.nodeDOM && (from4 == 0 || to2 == this.nodeDOM.nodeValue.length))
      this.dirty = NODE_DIRTY;
  }
  get domAtom() {
    return false;
  }
  isText(text10) {
    return this.node.text == text10;
  }
};
var TrailingHackViewDesc = class extends ViewDesc {
  parseRule() {
    return { ignore: true };
  }
  matchesHack(nodeName) {
    return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName;
  }
  get domAtom() {
    return true;
  }
  get ignoreForCoords() {
    return this.dom.nodeName == "IMG";
  }
};
var CustomNodeViewDesc = class extends NodeViewDesc {
  constructor(parent, node2, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {
    super(parent, node2, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);
    this.spec = spec;
  }
  // A custom `update` method gets to decide whether the update goes
  // through. If it does, and there's a `contentDOM` node, our logic
  // updates the children.
  update(node2, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY)
      return false;
    if (this.spec.update && (this.node.type == node2.type || this.spec.multiType)) {
      let result = this.spec.update(node2, outerDeco, innerDeco);
      if (result)
        this.updateInner(node2, outerDeco, innerDeco, view);
      return result;
    } else if (!this.contentDOM && !node2.isLeaf) {
      return false;
    } else {
      return super.update(node2, outerDeco, innerDeco, view);
    }
  }
  selectNode() {
    this.spec.selectNode ? this.spec.selectNode() : super.selectNode();
  }
  deselectNode() {
    this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();
  }
  setSelection(anchor, head2, view, force) {
    this.spec.setSelection ? this.spec.setSelection(anchor, head2, view.root) : super.setSelection(anchor, head2, view, force);
  }
  destroy() {
    if (this.spec.destroy)
      this.spec.destroy();
    super.destroy();
  }
  stopEvent(event) {
    return this.spec.stopEvent ? this.spec.stopEvent(event) : false;
  }
  ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
  }
};
function renderDescs(parentDOM, descs, view) {
  let dom = parentDOM.firstChild, written = false;
  for (let i3 = 0; i3 < descs.length; i3++) {
    let desc = descs[i3], childDOM = desc.dom;
    if (childDOM.parentNode == parentDOM) {
      while (childDOM != dom) {
        dom = rm(dom);
        written = true;
      }
      dom = dom.nextSibling;
    } else {
      written = true;
      parentDOM.insertBefore(childDOM, dom);
    }
    if (desc instanceof MarkViewDesc) {
      let pos = dom ? dom.previousSibling : parentDOM.lastChild;
      renderDescs(desc.contentDOM, desc.children, view);
      dom = pos ? pos.nextSibling : parentDOM.firstChild;
    }
  }
  while (dom) {
    dom = rm(dom);
    written = true;
  }
  if (written && view.trackWrites == parentDOM)
    view.trackWrites = null;
}
var OuterDecoLevel = function(nodeName) {
  if (nodeName)
    this.nodeName = nodeName;
};
OuterDecoLevel.prototype = /* @__PURE__ */ Object.create(null);
var noDeco = [new OuterDecoLevel()];
function computeOuterDeco(outerDeco, node2, needsWrap) {
  if (outerDeco.length == 0)
    return noDeco;
  let top = needsWrap ? noDeco[0] : new OuterDecoLevel(), result = [top];
  for (let i3 = 0; i3 < outerDeco.length; i3++) {
    let attrs = outerDeco[i3].type.attrs;
    if (!attrs)
      continue;
    if (attrs.nodeName)
      result.push(top = new OuterDecoLevel(attrs.nodeName));
    for (let name in attrs) {
      let val = attrs[name];
      if (val == null)
        continue;
      if (needsWrap && result.length == 1)
        result.push(top = new OuterDecoLevel(node2.isInline ? "span" : "div"));
      if (name == "class")
        top.class = (top.class ? top.class + " " : "") + val;
      else if (name == "style")
        top.style = (top.style ? top.style + ";" : "") + val;
      else if (name != "nodeName")
        top[name] = val;
    }
  }
  return result;
}
function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {
  if (prevComputed == noDeco && curComputed == noDeco)
    return nodeDOM;
  let curDOM = nodeDOM;
  for (let i3 = 0; i3 < curComputed.length; i3++) {
    let deco = curComputed[i3], prev = prevComputed[i3];
    if (i3) {
      let parent;
      if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {
        curDOM = parent;
      } else {
        parent = document.createElement(deco.nodeName);
        parent.pmIsDeco = true;
        parent.appendChild(curDOM);
        prev = noDeco[0];
        curDOM = parent;
      }
    }
    patchAttributes(curDOM, prev || noDeco[0], deco);
  }
  return curDOM;
}
function patchAttributes(dom, prev, cur) {
  for (let name in prev)
    if (name != "class" && name != "style" && name != "nodeName" && !(name in cur))
      dom.removeAttribute(name);
  for (let name in cur)
    if (name != "class" && name != "style" && name != "nodeName" && cur[name] != prev[name])
      dom.setAttribute(name, cur[name]);
  if (prev.class != cur.class) {
    let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : [];
    let curList = cur.class ? cur.class.split(" ").filter(Boolean) : [];
    for (let i3 = 0; i3 < prevList.length; i3++)
      if (curList.indexOf(prevList[i3]) == -1)
        dom.classList.remove(prevList[i3]);
    for (let i3 = 0; i3 < curList.length; i3++)
      if (prevList.indexOf(curList[i3]) == -1)
        dom.classList.add(curList[i3]);
    if (dom.classList.length == 0)
      dom.removeAttribute("class");
  }
  if (prev.style != cur.style) {
    if (prev.style) {
      let prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m2;
      while (m2 = prop.exec(prev.style))
        dom.style.removeProperty(m2[1]);
    }
    if (cur.style)
      dom.style.cssText += cur.style;
  }
}
function applyOuterDeco(dom, deco, node2) {
  return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node2, dom.nodeType != 1));
}
function sameOuterDeco(a3, b4) {
  if (a3.length != b4.length)
    return false;
  for (let i3 = 0; i3 < a3.length; i3++)
    if (!a3[i3].type.eq(b4[i3].type))
      return false;
  return true;
}
function rm(dom) {
  let next2 = dom.nextSibling;
  dom.parentNode.removeChild(dom);
  return next2;
}
var ViewTreeUpdater = class {
  constructor(top, lock, view) {
    this.lock = lock;
    this.view = view;
    this.index = 0;
    this.stack = [];
    this.changed = false;
    this.top = top;
    this.preMatch = preMatch(top.node.content, top);
  }
  // Destroy and remove the children between the given indices in
  // `this.top`.
  destroyBetween(start, end) {
    if (start == end)
      return;
    for (let i3 = start; i3 < end; i3++)
      this.top.children[i3].destroy();
    this.top.children.splice(start, end - start);
    this.changed = true;
  }
  // Destroy all remaining children in `this.top`.
  destroyRest() {
    this.destroyBetween(this.index, this.top.children.length);
  }
  // Sync the current stack of mark descs with the given array of
  // marks, reusing existing mark descs when possible.
  syncToMarks(marks, inline4, view) {
    let keep = 0, depth = this.stack.length >> 1;
    let maxKeep = Math.min(depth, marks.length);
    while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)
      keep++;
    while (keep < depth) {
      this.destroyRest();
      this.top.dirty = NOT_DIRTY;
      this.index = this.stack.pop();
      this.top = this.stack.pop();
      depth--;
    }
    while (depth < marks.length) {
      this.stack.push(this.top, this.index + 1);
      let found2 = -1;
      for (let i3 = this.index; i3 < Math.min(this.index + 3, this.top.children.length); i3++) {
        let next2 = this.top.children[i3];
        if (next2.matchesMark(marks[depth]) && !this.isLocked(next2.dom)) {
          found2 = i3;
          break;
        }
      }
      if (found2 > -1) {
        if (found2 > this.index) {
          this.changed = true;
          this.destroyBetween(this.index, found2);
        }
        this.top = this.top.children[this.index];
      } else {
        let markDesc = MarkViewDesc.create(this.top, marks[depth], inline4, view);
        this.top.children.splice(this.index, 0, markDesc);
        this.top = markDesc;
        this.changed = true;
      }
      this.index = 0;
      depth++;
    }
  }
  // Try to find a node desc matching the given data. Skip over it and
  // return true when successful.
  findNodeMatch(node2, outerDeco, innerDeco, index4) {
    let found2 = -1, targetDesc;
    if (index4 >= this.preMatch.index && (targetDesc = this.preMatch.matches[index4 - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node2, outerDeco, innerDeco)) {
      found2 = this.top.children.indexOf(targetDesc, this.index);
    } else {
      for (let i3 = this.index, e2 = Math.min(this.top.children.length, i3 + 5); i3 < e2; i3++) {
        let child = this.top.children[i3];
        if (child.matchesNode(node2, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {
          found2 = i3;
          break;
        }
      }
    }
    if (found2 < 0)
      return false;
    this.destroyBetween(this.index, found2);
    this.index++;
    return true;
  }
  updateNodeAt(node2, outerDeco, innerDeco, index4, view) {
    let child = this.top.children[index4];
    if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)
      child.dirty = CONTENT_DIRTY;
    if (!child.update(node2, outerDeco, innerDeco, view))
      return false;
    this.destroyBetween(this.index, index4);
    this.index++;
    return true;
  }
  findIndexWithChild(domNode) {
    for (; ; ) {
      let parent = domNode.parentNode;
      if (!parent)
        return -1;
      if (parent == this.top.contentDOM) {
        let desc = domNode.pmViewDesc;
        if (desc)
          for (let i3 = this.index; i3 < this.top.children.length; i3++) {
            if (this.top.children[i3] == desc)
              return i3;
          }
        return -1;
      }
      domNode = parent;
    }
  }
  // Try to update the next node, if any, to the given data. Checks
  // pre-matches to avoid overwriting nodes that could still be used.
  updateNextNode(node2, outerDeco, innerDeco, view, index4, pos) {
    for (let i3 = this.index; i3 < this.top.children.length; i3++) {
      let next2 = this.top.children[i3];
      if (next2 instanceof NodeViewDesc) {
        let preMatch2 = this.preMatch.matched.get(next2);
        if (preMatch2 != null && preMatch2 != index4)
          return false;
        let nextDOM = next2.dom, updated;
        let locked = this.isLocked(nextDOM) && !(node2.isText && next2.node && next2.node.isText && next2.nodeDOM.nodeValue == node2.text && next2.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next2.outerDeco));
        if (!locked && next2.update(node2, outerDeco, innerDeco, view)) {
          this.destroyBetween(this.index, i3);
          if (next2.dom != nextDOM)
            this.changed = true;
          this.index++;
          return true;
        } else if (!locked && (updated = this.recreateWrapper(next2, node2, outerDeco, innerDeco, view, pos))) {
          this.destroyBetween(this.index, i3);
          this.top.children[this.index] = updated;
          if (updated.contentDOM) {
            updated.dirty = CONTENT_DIRTY;
            updated.updateChildren(view, pos + 1);
            updated.dirty = NOT_DIRTY;
          }
          this.changed = true;
          this.index++;
          return true;
        }
        break;
      }
    }
    return false;
  }
  // When a node with content is replaced by a different node with
  // identical content, move over its children.
  recreateWrapper(next2, node2, outerDeco, innerDeco, view, pos) {
    if (next2.dirty || node2.isAtom || !next2.children.length || !next2.node.content.eq(node2.content) || !sameOuterDeco(outerDeco, next2.outerDeco) || !innerDeco.eq(next2.innerDeco))
      return null;
    let wrapper = NodeViewDesc.create(this.top, node2, outerDeco, innerDeco, view, pos);
    if (wrapper.contentDOM) {
      wrapper.children = next2.children;
      next2.children = [];
      for (let ch of wrapper.children)
        ch.parent = wrapper;
    }
    next2.destroy();
    return wrapper;
  }
  // Insert the node as a newly created node desc.
  addNode(node2, outerDeco, innerDeco, view, pos) {
    let desc = NodeViewDesc.create(this.top, node2, outerDeco, innerDeco, view, pos);
    if (desc.contentDOM)
      desc.updateChildren(view, pos + 1);
    this.top.children.splice(this.index++, 0, desc);
    this.changed = true;
  }
  placeWidget(widget, view, pos) {
    let next2 = this.index < this.top.children.length ? this.top.children[this.index] : null;
    if (next2 && next2.matchesWidget(widget) && (widget == next2.widget || !next2.widget.type.toDOM.parentNode)) {
      this.index++;
    } else {
      let desc = new WidgetViewDesc(this.top, widget, view, pos);
      this.top.children.splice(this.index++, 0, desc);
      this.changed = true;
    }
  }
  // Make sure a textblock looks and behaves correctly in
  // contentEditable.
  addTextblockHacks() {
    let lastChild = this.top.children[this.index - 1], parent = this.top;
    while (lastChild instanceof MarkViewDesc) {
      parent = lastChild;
      lastChild = parent.children[parent.children.length - 1];
    }
    if (!lastChild || // Empty textblock
    !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) {
      if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == "false")
        this.addHackNode("IMG", parent);
      this.addHackNode("BR", this.top);
    }
  }
  addHackNode(nodeName, parent) {
    if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {
      this.index++;
    } else {
      let dom = document.createElement(nodeName);
      if (nodeName == "IMG") {
        dom.className = "ProseMirror-separator";
        dom.alt = "";
      }
      if (nodeName == "BR")
        dom.className = "ProseMirror-trailingBreak";
      let hack = new TrailingHackViewDesc(this.top, [], dom, null);
      if (parent != this.top)
        parent.children.push(hack);
      else
        parent.children.splice(this.index++, 0, hack);
      this.changed = true;
    }
  }
  isLocked(node2) {
    return this.lock && (node2 == this.lock || node2.nodeType == 1 && node2.contains(this.lock.parentNode));
  }
};
function preMatch(frag, parentDesc) {
  let curDesc = parentDesc, descI = curDesc.children.length;
  let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches3 = [];
  outer: while (fI > 0) {
    let desc;
    for (; ; ) {
      if (descI) {
        let next2 = curDesc.children[descI - 1];
        if (next2 instanceof MarkViewDesc) {
          curDesc = next2;
          descI = next2.children.length;
        } else {
          desc = next2;
          descI--;
          break;
        }
      } else if (curDesc == parentDesc) {
        break outer;
      } else {
        descI = curDesc.parent.children.indexOf(curDesc);
        curDesc = curDesc.parent;
      }
    }
    let node2 = desc.node;
    if (!node2)
      continue;
    if (node2 != frag.child(fI - 1))
      break;
    --fI;
    matched.set(desc, fI);
    matches3.push(desc);
  }
  return { index: fI, matched, matches: matches3.reverse() };
}
function compareSide(a3, b4) {
  return a3.type.side - b4.type.side;
}
function iterDeco(parent, deco, onWidget, onNode) {
  let locals = deco.locals(parent), offset4 = 0;
  if (locals.length == 0) {
    for (let i3 = 0; i3 < parent.childCount; i3++) {
      let child = parent.child(i3);
      onNode(child, locals, deco.forChild(offset4, child), i3);
      offset4 += child.nodeSize;
    }
    return;
  }
  let decoIndex = 0, active = [], restNode = null;
  for (let parentIndex = 0; ; ) {
    let widget, widgets;
    while (decoIndex < locals.length && locals[decoIndex].to == offset4) {
      let next2 = locals[decoIndex++];
      if (next2.widget) {
        if (!widget)
          widget = next2;
        else
          (widgets || (widgets = [widget])).push(next2);
      }
    }
    if (widget) {
      if (widgets) {
        widgets.sort(compareSide);
        for (let i3 = 0; i3 < widgets.length; i3++)
          onWidget(widgets[i3], parentIndex, !!restNode);
      } else {
        onWidget(widget, parentIndex, !!restNode);
      }
    }
    let child, index4;
    if (restNode) {
      index4 = -1;
      child = restNode;
      restNode = null;
    } else if (parentIndex < parent.childCount) {
      index4 = parentIndex;
      child = parent.child(parentIndex++);
    } else {
      break;
    }
    for (let i3 = 0; i3 < active.length; i3++)
      if (active[i3].to <= offset4)
        active.splice(i3--, 1);
    while (decoIndex < locals.length && locals[decoIndex].from <= offset4 && locals[decoIndex].to > offset4)
      active.push(locals[decoIndex++]);
    let end = offset4 + child.nodeSize;
    if (child.isText) {
      let cutAt = end;
      if (decoIndex < locals.length && locals[decoIndex].from < cutAt)
        cutAt = locals[decoIndex].from;
      for (let i3 = 0; i3 < active.length; i3++)
        if (active[i3].to < cutAt)
          cutAt = active[i3].to;
      if (cutAt < end) {
        restNode = child.cut(cutAt - offset4);
        child = child.cut(0, cutAt - offset4);
        end = cutAt;
        index4 = -1;
      }
    } else {
      while (decoIndex < locals.length && locals[decoIndex].to < end)
        decoIndex++;
    }
    let outerDeco = child.isInline && !child.isLeaf ? active.filter((d) => !d.inline) : active.slice();
    onNode(child, outerDeco, deco.forChild(offset4, child), index4);
    offset4 = end;
  }
}
function iosHacks(dom) {
  if (dom.nodeName == "UL" || dom.nodeName == "OL") {
    let oldCSS = dom.style.cssText;
    dom.style.cssText = oldCSS + "; list-style: square !important";
    window.getComputedStyle(dom).listStyle;
    dom.style.cssText = oldCSS;
  }
}
function findTextInFragment(frag, text10, from4, to2) {
  for (let i3 = 0, pos = 0; i3 < frag.childCount && pos <= to2; ) {
    let child = frag.child(i3++), childStart = pos;
    pos += child.nodeSize;
    if (!child.isText)
      continue;
    let str = child.text;
    while (i3 < frag.childCount) {
      let next2 = frag.child(i3++);
      pos += next2.nodeSize;
      if (!next2.isText)
        break;
      str += next2.text;
    }
    if (pos >= from4) {
      if (pos >= to2 && str.slice(to2 - text10.length - childStart, to2 - childStart) == text10)
        return to2 - text10.length;
      let found2 = childStart < to2 ? str.lastIndexOf(text10, to2 - childStart - 1) : -1;
      if (found2 >= 0 && found2 + text10.length + childStart >= from4)
        return childStart + found2;
      if (from4 == to2 && str.length >= to2 + text10.length - childStart && str.slice(to2 - childStart, to2 - childStart + text10.length) == text10)
        return to2;
    }
  }
  return -1;
}
function replaceNodes(nodes, from4, to2, view, replacement) {
  let result = [];
  for (let i3 = 0, off = 0; i3 < nodes.length; i3++) {
    let child = nodes[i3], start = off, end = off += child.size;
    if (start >= to2 || end <= from4) {
      result.push(child);
    } else {
      if (start < from4)
        result.push(child.slice(0, from4 - start, view));
      if (replacement) {
        result.push(replacement);
        replacement = void 0;
      }
      if (end > to2)
        result.push(child.slice(to2 - start, child.size, view));
    }
  }
  return result;
}
function selectionFromDOM(view, origin = null) {
  let domSel = view.domSelectionRange(), doc4 = view.state.doc;
  if (!domSel.focusNode)
    return null;
  let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;
  let head2 = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);
  if (head2 < 0)
    return null;
  let $head = doc4.resolve(head2), anchor, selection;
  if (selectionCollapsed(domSel)) {
    anchor = head2;
    while (nearestDesc && !nearestDesc.node)
      nearestDesc = nearestDesc.parent;
    let nearestDescNode = nearestDesc.node;
    if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {
      let pos = nearestDesc.posBefore;
      selection = new NodeSelection(head2 == pos ? $head : doc4.resolve(pos));
    }
  } else {
    if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {
      let min3 = head2, max3 = head2;
      for (let i3 = 0; i3 < domSel.rangeCount; i3++) {
        let range = domSel.getRangeAt(i3);
        min3 = Math.min(min3, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));
        max3 = Math.max(max3, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));
      }
      if (min3 < 0)
        return null;
      [anchor, head2] = max3 == view.state.selection.anchor ? [max3, min3] : [min3, max3];
      $head = doc4.resolve(head2);
    } else {
      anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);
    }
    if (anchor < 0)
      return null;
  }
  let $anchor = doc4.resolve(anchor);
  if (!selection) {
    let bias = origin == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1;
    selection = selectionBetween(view, $anchor, $head, bias);
  }
  return selection;
}
function editorOwnsSelection(view) {
  return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);
}
function selectionToDOM(view, force = false) {
  let sel = view.state.selection;
  syncNodeSelection(view, sel);
  if (!editorOwnsSelection(view))
    return;
  if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) {
    let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;
    if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) {
      view.input.mouseDown.delayedSelectionSync = true;
      view.domObserver.setCurSelection();
      return;
    }
  }
  view.domObserver.disconnectSelection();
  if (view.cursorWrapper) {
    selectCursorWrapper(view);
  } else {
    let { anchor, head: head2 } = sel, resetEditableFrom, resetEditableTo;
    if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {
      if (!sel.$from.parent.inlineContent)
        resetEditableFrom = temporarilyEditableNear(view, sel.from);
      if (!sel.empty && !sel.$from.parent.inlineContent)
        resetEditableTo = temporarilyEditableNear(view, sel.to);
    }
    view.docView.setSelection(anchor, head2, view, force);
    if (brokenSelectBetweenUneditable) {
      if (resetEditableFrom)
        resetEditable(resetEditableFrom);
      if (resetEditableTo)
        resetEditable(resetEditableTo);
    }
    if (sel.visible) {
      view.dom.classList.remove("ProseMirror-hideselection");
    } else {
      view.dom.classList.add("ProseMirror-hideselection");
      if ("onselectionchange" in document)
        removeClassOnSelectionChange(view);
    }
  }
  view.domObserver.setCurSelection();
  view.domObserver.connectSelection();
}
var brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;
function temporarilyEditableNear(view, pos) {
  let { node: node2, offset: offset4 } = view.docView.domFromPos(pos, 0);
  let after = offset4 < node2.childNodes.length ? node2.childNodes[offset4] : null;
  let before = offset4 ? node2.childNodes[offset4 - 1] : null;
  if (safari && after && after.contentEditable == "false")
    return setEditable(after);
  if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) {
    if (after)
      return setEditable(after);
    else if (before)
      return setEditable(before);
  }
}
function setEditable(element7) {
  element7.contentEditable = "true";
  if (safari && element7.draggable) {
    element7.draggable = false;
    element7.wasDraggable = true;
  }
  return element7;
}
function resetEditable(element7) {
  element7.contentEditable = "false";
  if (element7.wasDraggable) {
    element7.draggable = true;
    element7.wasDraggable = null;
  }
}
function removeClassOnSelectionChange(view) {
  let doc4 = view.dom.ownerDocument;
  doc4.removeEventListener("selectionchange", view.input.hideSelectionGuard);
  let domSel = view.domSelectionRange();
  let node2 = domSel.anchorNode, offset4 = domSel.anchorOffset;
  doc4.addEventListener("selectionchange", view.input.hideSelectionGuard = () => {
    if (domSel.anchorNode != node2 || domSel.anchorOffset != offset4) {
      doc4.removeEventListener("selectionchange", view.input.hideSelectionGuard);
      setTimeout(() => {
        if (!editorOwnsSelection(view) || view.state.selection.visible)
          view.dom.classList.remove("ProseMirror-hideselection");
      }, 20);
    }
  });
}
function selectCursorWrapper(view) {
  let domSel = view.domSelection();
  if (!domSel)
    return;
  let node2 = view.cursorWrapper.dom, img2 = node2.nodeName == "IMG";
  if (img2)
    domSel.collapse(node2.parentNode, domIndex(node2) + 1);
  else
    domSel.collapse(node2, 0);
  if (!img2 && !view.state.selection.visible && ie && ie_version <= 11) {
    node2.disabled = true;
    node2.disabled = false;
  }
}
function syncNodeSelection(view, sel) {
  if (sel instanceof NodeSelection) {
    let desc = view.docView.descAt(sel.from);
    if (desc != view.lastSelectedViewDesc) {
      clearNodeSelection(view);
      if (desc)
        desc.selectNode();
      view.lastSelectedViewDesc = desc;
    }
  } else {
    clearNodeSelection(view);
  }
}
function clearNodeSelection(view) {
  if (view.lastSelectedViewDesc) {
    if (view.lastSelectedViewDesc.parent)
      view.lastSelectedViewDesc.deselectNode();
    view.lastSelectedViewDesc = void 0;
  }
}
function selectionBetween(view, $anchor, $head, bias) {
  return view.someProp("createSelectionBetween", (f6) => f6(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias);
}
function hasFocusAndSelection(view) {
  if (view.editable && !view.hasFocus())
    return false;
  return hasSelection(view);
}
function hasSelection(view) {
  let sel = view.domSelectionRange();
  if (!sel.anchorNode)
    return false;
  try {
    return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode));
  } catch (_2) {
    return false;
  }
}
function anchorInRightPlace(view) {
  let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);
  let domSel = view.domSelectionRange();
  return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);
}
function moveSelectionBlock(state, dir) {
  let { $anchor, $head } = state.selection;
  let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);
  let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;
  return $start && Selection.findFrom($start, dir);
}
function apply(view, sel) {
  view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());
  return true;
}
function selectHorizontally(view, dir, mods) {
  let sel = view.state.selection;
  if (sel instanceof TextSelection) {
    if (mods.indexOf("s") > -1) {
      let { $head } = sel, node2 = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;
      if (!node2 || node2.isText || !node2.isLeaf)
        return false;
      let $newHead = view.state.doc.resolve($head.pos + node2.nodeSize * (dir < 0 ? -1 : 1));
      return apply(view, new TextSelection(sel.$anchor, $newHead));
    } else if (!sel.empty) {
      return false;
    } else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) {
      let next2 = moveSelectionBlock(view.state, dir);
      if (next2 && next2 instanceof NodeSelection)
        return apply(view, next2);
      return false;
    } else if (!(mac && mods.indexOf("m") > -1)) {
      let $head = sel.$head, node2 = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;
      if (!node2 || node2.isText)
        return false;
      let nodePos = dir < 0 ? $head.pos - node2.nodeSize : $head.pos;
      if (!(node2.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))
        return false;
      if (NodeSelection.isSelectable(node2)) {
        return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node2.nodeSize) : $head));
      } else if (webkit) {
        return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node2.nodeSize)));
      } else {
        return false;
      }
    }
  } else if (sel instanceof NodeSelection && sel.node.isInline) {
    return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));
  } else {
    let next2 = moveSelectionBlock(view.state, dir);
    if (next2)
      return apply(view, next2);
    return false;
  }
}
function nodeLen(node2) {
  return node2.nodeType == 3 ? node2.nodeValue.length : node2.childNodes.length;
}
function isIgnorable(dom, dir) {
  let desc = dom.pmViewDesc;
  return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR");
}
function skipIgnoredNodes(view, dir) {
  return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);
}
function skipIgnoredNodesBefore(view) {
  let sel = view.domSelectionRange();
  let node2 = sel.focusNode, offset4 = sel.focusOffset;
  if (!node2)
    return;
  let moveNode, moveOffset, force = false;
  if (gecko && node2.nodeType == 1 && offset4 < nodeLen(node2) && isIgnorable(node2.childNodes[offset4], -1))
    force = true;
  for (; ; ) {
    if (offset4 > 0) {
      if (node2.nodeType != 1) {
        break;
      } else {
        let before = node2.childNodes[offset4 - 1];
        if (isIgnorable(before, -1)) {
          moveNode = node2;
          moveOffset = --offset4;
        } else if (before.nodeType == 3) {
          node2 = before;
          offset4 = node2.nodeValue.length;
        } else
          break;
      }
    } else if (isBlockNode(node2)) {
      break;
    } else {
      let prev = node2.previousSibling;
      while (prev && isIgnorable(prev, -1)) {
        moveNode = node2.parentNode;
        moveOffset = domIndex(prev);
        prev = prev.previousSibling;
      }
      if (!prev) {
        node2 = node2.parentNode;
        if (node2 == view.dom)
          break;
        offset4 = 0;
      } else {
        node2 = prev;
        offset4 = nodeLen(node2);
      }
    }
  }
  if (force)
    setSelFocus(view, node2, offset4);
  else if (moveNode)
    setSelFocus(view, moveNode, moveOffset);
}
function skipIgnoredNodesAfter(view) {
  let sel = view.domSelectionRange();
  let node2 = sel.focusNode, offset4 = sel.focusOffset;
  if (!node2)
    return;
  let len = nodeLen(node2);
  let moveNode, moveOffset;
  for (; ; ) {
    if (offset4 < len) {
      if (node2.nodeType != 1)
        break;
      let after = node2.childNodes[offset4];
      if (isIgnorable(after, 1)) {
        moveNode = node2;
        moveOffset = ++offset4;
      } else
        break;
    } else if (isBlockNode(node2)) {
      break;
    } else {
      let next2 = node2.nextSibling;
      while (next2 && isIgnorable(next2, 1)) {
        moveNode = next2.parentNode;
        moveOffset = domIndex(next2) + 1;
        next2 = next2.nextSibling;
      }
      if (!next2) {
        node2 = node2.parentNode;
        if (node2 == view.dom)
          break;
        offset4 = len = 0;
      } else {
        node2 = next2;
        offset4 = 0;
        len = nodeLen(node2);
      }
    }
  }
  if (moveNode)
    setSelFocus(view, moveNode, moveOffset);
}
function isBlockNode(dom) {
  let desc = dom.pmViewDesc;
  return desc && desc.node && desc.node.isBlock;
}
function textNodeAfter(node2, offset4) {
  while (node2 && offset4 == node2.childNodes.length && !hasBlockDesc(node2)) {
    offset4 = domIndex(node2) + 1;
    node2 = node2.parentNode;
  }
  while (node2 && offset4 < node2.childNodes.length) {
    let next2 = node2.childNodes[offset4];
    if (next2.nodeType == 3)
      return next2;
    if (next2.nodeType == 1 && next2.contentEditable == "false")
      break;
    node2 = next2;
    offset4 = 0;
  }
}
function textNodeBefore(node2, offset4) {
  while (node2 && !offset4 && !hasBlockDesc(node2)) {
    offset4 = domIndex(node2);
    node2 = node2.parentNode;
  }
  while (node2 && offset4) {
    let next2 = node2.childNodes[offset4 - 1];
    if (next2.nodeType == 3)
      return next2;
    if (next2.nodeType == 1 && next2.contentEditable == "false")
      break;
    node2 = next2;
    offset4 = node2.childNodes.length;
  }
}
function setSelFocus(view, node2, offset4) {
  if (node2.nodeType != 3) {
    let before, after;
    if (after = textNodeAfter(node2, offset4)) {
      node2 = after;
      offset4 = 0;
    } else if (before = textNodeBefore(node2, offset4)) {
      node2 = before;
      offset4 = before.nodeValue.length;
    }
  }
  let sel = view.domSelection();
  if (!sel)
    return;
  if (selectionCollapsed(sel)) {
    let range = document.createRange();
    range.setEnd(node2, offset4);
    range.setStart(node2, offset4);
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (sel.extend) {
    sel.extend(node2, offset4);
  }
  view.domObserver.setCurSelection();
  let { state } = view;
  setTimeout(() => {
    if (view.state == state)
      selectionToDOM(view);
  }, 50);
}
function findDirection(view, pos) {
  let $pos = view.state.doc.resolve(pos);
  if (!(chrome || windows) && $pos.parent.inlineContent) {
    let coords = view.coordsAtPos(pos);
    if (pos > $pos.start()) {
      let before = view.coordsAtPos(pos - 1);
      let mid = (before.top + before.bottom) / 2;
      if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)
        return before.left < coords.left ? "ltr" : "rtl";
    }
    if (pos < $pos.end()) {
      let after = view.coordsAtPos(pos + 1);
      let mid = (after.top + after.bottom) / 2;
      if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)
        return after.left > coords.left ? "ltr" : "rtl";
    }
  }
  let computed = getComputedStyle(view.dom).direction;
  return computed == "rtl" ? "rtl" : "ltr";
}
function selectVertically(view, dir, mods) {
  let sel = view.state.selection;
  if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1)
    return false;
  if (mac && mods.indexOf("m") > -1)
    return false;
  let { $from, $to } = sel;
  if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) {
    let next2 = moveSelectionBlock(view.state, dir);
    if (next2 && next2 instanceof NodeSelection)
      return apply(view, next2);
  }
  if (!$from.parent.inlineContent) {
    let side = dir < 0 ? $from : $to;
    let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);
    return beyond ? apply(view, beyond) : false;
  }
  return false;
}
function stopNativeHorizontalDelete(view, dir) {
  if (!(view.state.selection instanceof TextSelection))
    return true;
  let { $head, $anchor, empty: empty4 } = view.state.selection;
  if (!$head.sameParent($anchor))
    return true;
  if (!empty4)
    return false;
  if (view.endOfTextblock(dir > 0 ? "forward" : "backward"))
    return true;
  let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);
  if (nextNode && !nextNode.isText) {
    let tr4 = view.state.tr;
    if (dir < 0)
      tr4.delete($head.pos - nextNode.nodeSize, $head.pos);
    else
      tr4.delete($head.pos, $head.pos + nextNode.nodeSize);
    view.dispatch(tr4);
    return true;
  }
  return false;
}
function switchEditable(view, node2, state) {
  view.domObserver.stop();
  node2.contentEditable = state;
  view.domObserver.start();
}
function safariDownArrowBug(view) {
  if (!safari || view.state.selection.$head.parentOffset > 0)
    return false;
  let { focusNode, focusOffset } = view.domSelectionRange();
  if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") {
    let child = focusNode.firstChild;
    switchEditable(view, child, "true");
    setTimeout(() => switchEditable(view, child, "false"), 20);
  }
  return false;
}
function getMods(event) {
  let result = "";
  if (event.ctrlKey)
    result += "c";
  if (event.metaKey)
    result += "m";
  if (event.altKey)
    result += "a";
  if (event.shiftKey)
    result += "s";
  return result;
}
function captureKeyDown(view, event) {
  let code5 = event.keyCode, mods = getMods(event);
  if (code5 == 8 || mac && code5 == 72 && mods == "c") {
    return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);
  } else if (code5 == 46 && !event.shiftKey || mac && code5 == 68 && mods == "c") {
    return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);
  } else if (code5 == 13 || code5 == 27) {
    return true;
  } else if (code5 == 37 || mac && code5 == 66 && mods == "c") {
    let dir = code5 == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1;
    return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
  } else if (code5 == 39 || mac && code5 == 70 && mods == "c") {
    let dir = code5 == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1;
    return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
  } else if (code5 == 38 || mac && code5 == 80 && mods == "c") {
    return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);
  } else if (code5 == 40 || mac && code5 == 78 && mods == "c") {
    return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);
  } else if (mods == (mac ? "m" : "c") && (code5 == 66 || code5 == 73 || code5 == 89 || code5 == 90)) {
    return true;
  }
  return false;
}
function serializeForClipboard(view, slice2) {
  view.someProp("transformCopied", (f6) => {
    slice2 = f6(slice2, view);
  });
  let context = [], { content: content5, openStart, openEnd } = slice2;
  while (openStart > 1 && openEnd > 1 && content5.childCount == 1 && content5.firstChild.childCount == 1) {
    openStart--;
    openEnd--;
    let node2 = content5.firstChild;
    context.push(node2.type.name, node2.attrs != node2.type.defaultAttrs ? node2.attrs : null);
    content5 = node2.content;
  }
  let serializer2 = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema);
  let doc4 = detachedDoc(), wrap5 = doc4.createElement("div");
  wrap5.appendChild(serializer2.serializeFragment(content5, { document: doc4 }));
  let firstChild = wrap5.firstChild, needsWrap, wrappers = 0;
  while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {
    for (let i3 = needsWrap.length - 1; i3 >= 0; i3--) {
      let wrapper = doc4.createElement(needsWrap[i3]);
      while (wrap5.firstChild)
        wrapper.appendChild(wrap5.firstChild);
      wrap5.appendChild(wrapper);
      wrappers++;
    }
    firstChild = wrap5.firstChild;
  }
  if (firstChild && firstChild.nodeType == 1)
    firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`);
  let text10 = view.someProp("clipboardTextSerializer", (f6) => f6(slice2, view)) || slice2.content.textBetween(0, slice2.content.size, "\n\n");
  return { dom: wrap5, text: text10, slice: slice2 };
}
function parseFromClipboard(view, text10, html7, plainText, $context) {
  let inCode = $context.parent.type.spec.code;
  let dom, slice2;
  if (!html7 && !text10)
    return null;
  let asText = !!text10 && (plainText || inCode || !html7);
  if (asText) {
    view.someProp("transformPastedText", (f6) => {
      text10 = f6(text10, inCode || plainText, view);
    });
    if (inCode) {
      slice2 = new Slice(Fragment.from(view.state.schema.text(text10.replace(/\r\n?/g, "\n"))), 0, 0);
      view.someProp("transformPasted", (f6) => {
        slice2 = f6(slice2, view, true);
      });
      return slice2;
    }
    let parsed = view.someProp("clipboardTextParser", (f6) => f6(text10, $context, plainText, view));
    if (parsed) {
      slice2 = parsed;
    } else {
      let marks = $context.marks();
      let { schema } = view.state, serializer2 = DOMSerializer.fromSchema(schema);
      dom = document.createElement("div");
      text10.split(/(?:\r\n?|\n)+/).forEach((block) => {
        let p4 = dom.appendChild(document.createElement("p"));
        if (block)
          p4.appendChild(serializer2.serializeNode(schema.text(block, marks)));
      });
    }
  } else {
    view.someProp("transformPastedHTML", (f6) => {
      html7 = f6(html7, view);
    });
    dom = readHTML(html7);
    if (webkit)
      restoreReplacedSpaces(dom);
  }
  let contextNode = dom && dom.querySelector("[data-pm-slice]");
  let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || "");
  if (sliceData && sliceData[3])
    for (let i3 = +sliceData[3]; i3 > 0; i3--) {
      let child = dom.firstChild;
      while (child && child.nodeType != 1)
        child = child.nextSibling;
      if (!child)
        break;
      dom = child;
    }
  if (!slice2) {
    let parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser2.fromSchema(view.state.schema);
    slice2 = parser.parseSlice(dom, {
      preserveWhitespace: !!(asText || sliceData),
      context: $context,
      ruleFromNode(dom2) {
        if (dom2.nodeName == "BR" && !dom2.nextSibling && dom2.parentNode && !inlineParents.test(dom2.parentNode.nodeName))
          return { ignore: true };
        return null;
      }
    });
  }
  if (sliceData) {
    slice2 = addContext(closeSlice(slice2, +sliceData[1], +sliceData[2]), sliceData[4]);
  } else {
    slice2 = Slice.maxOpen(normalizeSiblings(slice2.content, $context), true);
    if (slice2.openStart || slice2.openEnd) {
      let openStart = 0, openEnd = 0;
      for (let node2 = slice2.content.firstChild; openStart < slice2.openStart && !node2.type.spec.isolating; openStart++, node2 = node2.firstChild) {
      }
      for (let node2 = slice2.content.lastChild; openEnd < slice2.openEnd && !node2.type.spec.isolating; openEnd++, node2 = node2.lastChild) {
      }
      slice2 = closeSlice(slice2, openStart, openEnd);
    }
  }
  view.someProp("transformPasted", (f6) => {
    slice2 = f6(slice2, view, asText);
  });
  return slice2;
}
var inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;
function normalizeSiblings(fragment, $context) {
  if (fragment.childCount < 2)
    return fragment;
  for (let d = $context.depth; d >= 0; d--) {
    let parent = $context.node(d);
    let match2 = parent.contentMatchAt($context.index(d));
    let lastWrap, result = [];
    fragment.forEach((node2) => {
      if (!result)
        return;
      let wrap5 = match2.findWrapping(node2.type), inLast;
      if (!wrap5)
        return result = null;
      if (inLast = result.length && lastWrap.length && addToSibling(wrap5, lastWrap, node2, result[result.length - 1], 0)) {
        result[result.length - 1] = inLast;
      } else {
        if (result.length)
          result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);
        let wrapped = withWrappers(node2, wrap5);
        result.push(wrapped);
        match2 = match2.matchType(wrapped.type);
        lastWrap = wrap5;
      }
    });
    if (result)
      return Fragment.from(result);
  }
  return fragment;
}
function withWrappers(node2, wrap5, from4 = 0) {
  for (let i3 = wrap5.length - 1; i3 >= from4; i3--)
    node2 = wrap5[i3].create(null, Fragment.from(node2));
  return node2;
}
function addToSibling(wrap5, lastWrap, node2, sibling, depth) {
  if (depth < wrap5.length && depth < lastWrap.length && wrap5[depth] == lastWrap[depth]) {
    let inner = addToSibling(wrap5, lastWrap, node2, sibling.lastChild, depth + 1);
    if (inner)
      return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner));
    let match2 = sibling.contentMatchAt(sibling.childCount);
    if (match2.matchType(depth == wrap5.length - 1 ? node2.type : wrap5[depth + 1]))
      return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node2, wrap5, depth + 1))));
  }
}
function closeRight(node2, depth) {
  if (depth == 0)
    return node2;
  let fragment = node2.content.replaceChild(node2.childCount - 1, closeRight(node2.lastChild, depth - 1));
  let fill = node2.contentMatchAt(node2.childCount).fillBefore(Fragment.empty, true);
  return node2.copy(fragment.append(fill));
}
function closeRange(fragment, side, from4, to2, depth, openEnd) {
  let node2 = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node2.content;
  if (fragment.childCount > 1)
    openEnd = 0;
  if (depth < to2 - 1)
    inner = closeRange(inner, side, from4, to2, depth + 1, openEnd);
  if (depth >= from4)
    inner = side < 0 ? node2.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node2.contentMatchAt(node2.childCount).fillBefore(Fragment.empty, true));
  return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node2.copy(inner));
}
function closeSlice(slice2, openStart, openEnd) {
  if (openStart < slice2.openStart)
    slice2 = new Slice(closeRange(slice2.content, -1, openStart, slice2.openStart, 0, slice2.openEnd), openStart, slice2.openEnd);
  if (openEnd < slice2.openEnd)
    slice2 = new Slice(closeRange(slice2.content, 1, openEnd, slice2.openEnd, 0, 0), slice2.openStart, openEnd);
  return slice2;
}
var wrapMap = {
  thead: ["table"],
  tbody: ["table"],
  tfoot: ["table"],
  caption: ["table"],
  colgroup: ["table"],
  col: ["table", "colgroup"],
  tr: ["table", "tbody"],
  td: ["table", "tbody", "tr"],
  th: ["table", "tbody", "tr"]
};
var _detachedDoc = null;
function detachedDoc() {
  return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title"));
}
var _policy = null;
function maybeWrapTrusted(html7) {
  let trustedTypes = window.trustedTypes;
  if (!trustedTypes)
    return html7;
  if (!_policy)
    _policy = trustedTypes.defaultPolicy || trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: (s2) => s2 });
  return _policy.createHTML(html7);
}
function readHTML(html7) {
  let metas = /^(\s*<meta [^>]*>)*/.exec(html7);
  if (metas)
    html7 = html7.slice(metas[0].length);
  let elt = detachedDoc().createElement("div");
  let firstTag = /<([a-z][^>\s]+)/i.exec(html7), wrap5;
  if (wrap5 = firstTag && wrapMap[firstTag[1].toLowerCase()])
    html7 = wrap5.map((n) => "<" + n + ">").join("") + html7 + wrap5.map((n) => "</" + n + ">").reverse().join("");
  elt.innerHTML = maybeWrapTrusted(html7);
  if (wrap5)
    for (let i3 = 0; i3 < wrap5.length; i3++)
      elt = elt.querySelector(wrap5[i3]) || elt;
  return elt;
}
function restoreReplacedSpaces(dom) {
  let nodes = dom.querySelectorAll(chrome ? "span:not([class]):not([style])" : "span.Apple-converted-space");
  for (let i3 = 0; i3 < nodes.length; i3++) {
    let node2 = nodes[i3];
    if (node2.childNodes.length == 1 && node2.textContent == " " && node2.parentNode)
      node2.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node2);
  }
}
function addContext(slice2, context) {
  if (!slice2.size)
    return slice2;
  let schema = slice2.content.firstChild.type.schema, array;
  try {
    array = JSON.parse(context);
  } catch (e2) {
    return slice2;
  }
  let { content: content5, openStart, openEnd } = slice2;
  for (let i3 = array.length - 2; i3 >= 0; i3 -= 2) {
    let type = schema.nodes[array[i3]];
    if (!type || type.hasRequiredAttrs())
      break;
    content5 = Fragment.from(type.create(array[i3 + 1], content5));
    openStart++;
    openEnd++;
  }
  return new Slice(content5, openStart, openEnd);
}
var handlers = {};
var editHandlers = {};
var passiveHandlers = { touchstart: true, touchmove: true };
var InputState = class {
  constructor() {
    this.shiftKey = false;
    this.mouseDown = null;
    this.lastKeyCode = null;
    this.lastKeyCodeTime = 0;
    this.lastClick = { time: 0, x: 0, y: 0, type: "", button: 0 };
    this.lastSelectionOrigin = null;
    this.lastSelectionTime = 0;
    this.lastIOSEnter = 0;
    this.lastIOSEnterFallbackTimeout = -1;
    this.lastFocus = 0;
    this.lastTouch = 0;
    this.lastChromeDelete = 0;
    this.composing = false;
    this.compositionNode = null;
    this.composingTimeout = -1;
    this.compositionNodes = [];
    this.compositionEndedAt = -2e8;
    this.compositionID = 1;
    this.compositionPendingChanges = 0;
    this.domChangeCount = 0;
    this.eventHandlers = /* @__PURE__ */ Object.create(null);
    this.hideSelectionGuard = null;
  }
};
function initInput(view) {
  for (let event in handlers) {
    let handler = handlers[event];
    view.dom.addEventListener(event, view.input.eventHandlers[event] = (event2) => {
      if (eventBelongsToView(view, event2) && !runCustomHandler(view, event2) && (view.editable || !(event2.type in editHandlers)))
        handler(view, event2);
    }, passiveHandlers[event] ? { passive: true } : void 0);
  }
  if (safari)
    view.dom.addEventListener("input", () => null);
  ensureListeners(view);
}
function setSelectionOrigin(view, origin) {
  view.input.lastSelectionOrigin = origin;
  view.input.lastSelectionTime = Date.now();
}
function destroyInput(view) {
  view.domObserver.stop();
  for (let type in view.input.eventHandlers)
    view.dom.removeEventListener(type, view.input.eventHandlers[type]);
  clearTimeout(view.input.composingTimeout);
  clearTimeout(view.input.lastIOSEnterFallbackTimeout);
}
function ensureListeners(view) {
  view.someProp("handleDOMEvents", (currentHandlers) => {
    for (let type in currentHandlers)
      if (!view.input.eventHandlers[type])
        view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event));
  });
}
function runCustomHandler(view, event) {
  return view.someProp("handleDOMEvents", (handlers4) => {
    let handler = handlers4[event.type];
    return handler ? handler(view, event) || event.defaultPrevented : false;
  });
}
function eventBelongsToView(view, event) {
  if (!event.bubbles)
    return true;
  if (event.defaultPrevented)
    return false;
  for (let node2 = event.target; node2 != view.dom; node2 = node2.parentNode)
    if (!node2 || node2.nodeType == 11 || node2.pmViewDesc && node2.pmViewDesc.stopEvent(event))
      return false;
  return true;
}
function dispatchEvent(view, event) {
  if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers)))
    handlers[event.type](view, event);
}
editHandlers.keydown = (view, _event) => {
  let event = _event;
  view.input.shiftKey = event.keyCode == 16 || event.shiftKey;
  if (inOrNearComposition(view, event))
    return;
  view.input.lastKeyCode = event.keyCode;
  view.input.lastKeyCodeTime = Date.now();
  if (android && chrome && event.keyCode == 13)
    return;
  if (event.keyCode != 229)
    view.domObserver.forceFlush();
  if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {
    let now = Date.now();
    view.input.lastIOSEnter = now;
    view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {
      if (view.input.lastIOSEnter == now) {
        view.someProp("handleKeyDown", (f6) => f6(view, keyEvent(13, "Enter")));
        view.input.lastIOSEnter = 0;
      }
    }, 200);
  } else if (view.someProp("handleKeyDown", (f6) => f6(view, event)) || captureKeyDown(view, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "key");
  }
};
editHandlers.keyup = (view, event) => {
  if (event.keyCode == 16)
    view.input.shiftKey = false;
};
editHandlers.keypress = (view, _event) => {
  let event = _event;
  if (inOrNearComposition(view, event) || !event.charCode || event.ctrlKey && !event.altKey || mac && event.metaKey)
    return;
  if (view.someProp("handleKeyPress", (f6) => f6(view, event))) {
    event.preventDefault();
    return;
  }
  let sel = view.state.selection;
  if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {
    let text10 = String.fromCharCode(event.charCode);
    let deflt = () => view.state.tr.insertText(text10).scrollIntoView();
    if (!/[\r\n]/.test(text10) && !view.someProp("handleTextInput", (f6) => f6(view, sel.$from.pos, sel.$to.pos, text10, deflt)))
      view.dispatch(deflt());
    event.preventDefault();
  }
};
function eventCoords(event) {
  return { left: event.clientX, top: event.clientY };
}
function isNear(event, click) {
  let dx = click.x - event.clientX, dy = click.y - event.clientY;
  return dx * dx + dy * dy < 100;
}
function runHandlerOnContext(view, propName, pos, inside, event) {
  if (inside == -1)
    return false;
  let $pos = view.state.doc.resolve(inside);
  for (let i3 = $pos.depth + 1; i3 > 0; i3--) {
    if (view.someProp(propName, (f6) => i3 > $pos.depth ? f6(view, pos, $pos.nodeAfter, $pos.before(i3), event, true) : f6(view, pos, $pos.node(i3), $pos.before(i3), event, false)))
      return true;
  }
  return false;
}
function updateSelection(view, selection, origin) {
  if (!view.focused)
    view.focus();
  if (view.state.selection.eq(selection))
    return;
  let tr4 = view.state.tr.setSelection(selection);
  if (origin == "pointer")
    tr4.setMeta("pointer", true);
  view.dispatch(tr4);
}
function selectClickedLeaf(view, inside) {
  if (inside == -1)
    return false;
  let $pos = view.state.doc.resolve(inside), node2 = $pos.nodeAfter;
  if (node2 && node2.isAtom && NodeSelection.isSelectable(node2)) {
    updateSelection(view, new NodeSelection($pos), "pointer");
    return true;
  }
  return false;
}
function selectClickedNode(view, inside) {
  if (inside == -1)
    return false;
  let sel = view.state.selection, selectedNode, selectAt;
  if (sel instanceof NodeSelection)
    selectedNode = sel.node;
  let $pos = view.state.doc.resolve(inside);
  for (let i3 = $pos.depth + 1; i3 > 0; i3--) {
    let node2 = i3 > $pos.depth ? $pos.nodeAfter : $pos.node(i3);
    if (NodeSelection.isSelectable(node2)) {
      if (selectedNode && sel.$from.depth > 0 && i3 >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)
        selectAt = $pos.before(sel.$from.depth);
      else
        selectAt = $pos.before(i3);
      break;
    }
  }
  if (selectAt != null) {
    updateSelection(view, NodeSelection.create(view.state.doc, selectAt), "pointer");
    return true;
  } else {
    return false;
  }
}
function handleSingleClick(view, pos, inside, event, selectNode) {
  return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f6) => f6(view, pos, event)) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));
}
function handleDoubleClick(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f6) => f6(view, pos, event));
}
function handleTripleClick(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f6) => f6(view, pos, event)) || defaultTripleClick(view, inside, event);
}
function defaultTripleClick(view, inside, event) {
  if (event.button != 0)
    return false;
  let doc4 = view.state.doc;
  if (inside == -1) {
    if (doc4.inlineContent) {
      updateSelection(view, TextSelection.create(doc4, 0, doc4.content.size), "pointer");
      return true;
    }
    return false;
  }
  let $pos = doc4.resolve(inside);
  for (let i3 = $pos.depth + 1; i3 > 0; i3--) {
    let node2 = i3 > $pos.depth ? $pos.nodeAfter : $pos.node(i3);
    let nodePos = $pos.before(i3);
    if (node2.inlineContent)
      updateSelection(view, TextSelection.create(doc4, nodePos + 1, nodePos + 1 + node2.content.size), "pointer");
    else if (NodeSelection.isSelectable(node2))
      updateSelection(view, NodeSelection.create(doc4, nodePos), "pointer");
    else
      continue;
    return true;
  }
}
function forceDOMFlush(view) {
  return endComposition(view);
}
var selectNodeModifier = mac ? "metaKey" : "ctrlKey";
handlers.mousedown = (view, _event) => {
  let event = _event;
  view.input.shiftKey = event.shiftKey;
  let flushed = forceDOMFlush(view);
  let now = Date.now(), type = "singleClick";
  if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] && view.input.lastClick.button == event.button) {
    if (view.input.lastClick.type == "singleClick")
      type = "doubleClick";
    else if (view.input.lastClick.type == "doubleClick")
      type = "tripleClick";
  }
  view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button };
  let pos = view.posAtCoords(eventCoords(event));
  if (!pos)
    return;
  if (type == "singleClick") {
    if (view.input.mouseDown)
      view.input.mouseDown.done();
    view.input.mouseDown = new MouseDown(view, pos, event, !!flushed);
  } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "pointer");
  }
};
var MouseDown = class {
  constructor(view, pos, event, flushed) {
    this.view = view;
    this.pos = pos;
    this.event = event;
    this.flushed = flushed;
    this.delayedSelectionSync = false;
    this.mightDrag = null;
    this.startDoc = view.state.doc;
    this.selectNode = !!event[selectNodeModifier];
    this.allowDefault = event.shiftKey;
    let targetNode, targetPos;
    if (pos.inside > -1) {
      targetNode = view.state.doc.nodeAt(pos.inside);
      targetPos = pos.inside;
    } else {
      let $pos = view.state.doc.resolve(pos.pos);
      targetNode = $pos.parent;
      targetPos = $pos.depth ? $pos.before() : 0;
    }
    const target = flushed ? null : event.target;
    const targetDesc = target ? view.docView.nearestDesc(target, true) : null;
    this.target = targetDesc && targetDesc.nodeDOM.nodeType == 1 ? targetDesc.nodeDOM : null;
    let { selection } = view.state;
    if (event.button == 0 && targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)
      this.mightDrag = {
        node: targetNode,
        pos: targetPos,
        addAttr: !!(this.target && !this.target.draggable),
        setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable"))
      };
    if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {
      this.view.domObserver.stop();
      if (this.mightDrag.addAttr)
        this.target.draggable = true;
      if (this.mightDrag.setUneditable)
        setTimeout(() => {
          if (this.view.input.mouseDown == this)
            this.target.setAttribute("contentEditable", "false");
        }, 20);
      this.view.domObserver.start();
    }
    view.root.addEventListener("mouseup", this.up = this.up.bind(this));
    view.root.addEventListener("mousemove", this.move = this.move.bind(this));
    setSelectionOrigin(view, "pointer");
  }
  done() {
    this.view.root.removeEventListener("mouseup", this.up);
    this.view.root.removeEventListener("mousemove", this.move);
    if (this.mightDrag && this.target) {
      this.view.domObserver.stop();
      if (this.mightDrag.addAttr)
        this.target.removeAttribute("draggable");
      if (this.mightDrag.setUneditable)
        this.target.removeAttribute("contentEditable");
      this.view.domObserver.start();
    }
    if (this.delayedSelectionSync)
      setTimeout(() => selectionToDOM(this.view));
    this.view.input.mouseDown = null;
  }
  up(event) {
    this.done();
    if (!this.view.dom.contains(event.target))
      return;
    let pos = this.pos;
    if (this.view.state.doc != this.startDoc)
      pos = this.view.posAtCoords(eventCoords(event));
    this.updateAllowDefault(event);
    if (this.allowDefault || !pos) {
      setSelectionOrigin(this.view, "pointer");
    } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {
      event.preventDefault();
    } else if (event.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements
    safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a
    // cursor, but still report that the node is selected
    // when asked through getSelection. You'll then get a
    // situation where clicking at the point where that
    // (hidden) cursor is doesn't change the selection, and
    // thus doesn't get a reaction from ProseMirror. This
    // works around that.
    chrome && !this.view.state.selection.visible && Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2)) {
      updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), "pointer");
      event.preventDefault();
    } else {
      setSelectionOrigin(this.view, "pointer");
    }
  }
  move(event) {
    this.updateAllowDefault(event);
    setSelectionOrigin(this.view, "pointer");
    if (event.buttons == 0)
      this.done();
  }
  updateAllowDefault(event) {
    if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4))
      this.allowDefault = true;
  }
};
handlers.touchstart = (view) => {
  view.input.lastTouch = Date.now();
  forceDOMFlush(view);
  setSelectionOrigin(view, "pointer");
};
handlers.touchmove = (view) => {
  view.input.lastTouch = Date.now();
  setSelectionOrigin(view, "pointer");
};
handlers.contextmenu = (view) => forceDOMFlush(view);
function inOrNearComposition(view, event) {
  if (view.composing)
    return true;
  if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) {
    view.input.compositionEndedAt = -2e8;
    return true;
  }
  return false;
}
var timeoutComposition = android ? 5e3 : -1;
editHandlers.compositionstart = editHandlers.compositionupdate = (view) => {
  if (!view.composing) {
    view.domObserver.flush();
    let { state } = view, $pos = state.selection.$to;
    if (state.selection instanceof TextSelection && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m2) => m2.type.spec.inclusive === false) || chrome && windows && selectionBeforeUneditable(view))) {
      view.markCursor = view.state.storedMarks || $pos.marks();
      endComposition(view, true);
      view.markCursor = null;
    } else {
      endComposition(view, !state.selection.empty);
      if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {
        let sel = view.domSelectionRange();
        for (let node2 = sel.focusNode, offset4 = sel.focusOffset; node2 && node2.nodeType == 1 && offset4 != 0; ) {
          let before = offset4 < 0 ? node2.lastChild : node2.childNodes[offset4 - 1];
          if (!before)
            break;
          if (before.nodeType == 3) {
            let sel2 = view.domSelection();
            if (sel2)
              sel2.collapse(before, before.nodeValue.length);
            break;
          } else {
            node2 = before;
            offset4 = -1;
          }
        }
      }
    }
    view.input.composing = true;
  }
  scheduleComposeEnd(view, timeoutComposition);
};
function selectionBeforeUneditable(view) {
  let { focusNode, focusOffset } = view.domSelectionRange();
  if (!focusNode || focusNode.nodeType != 1 || focusOffset >= focusNode.childNodes.length)
    return false;
  let next2 = focusNode.childNodes[focusOffset];
  return next2.nodeType == 1 && next2.contentEditable == "false";
}
editHandlers.compositionend = (view, event) => {
  if (view.composing) {
    view.input.composing = false;
    view.input.compositionEndedAt = event.timeStamp;
    view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;
    view.input.compositionNode = null;
    if (view.input.compositionPendingChanges)
      Promise.resolve().then(() => view.domObserver.flush());
    view.input.compositionID++;
    scheduleComposeEnd(view, 20);
  }
};
function scheduleComposeEnd(view, delay) {
  clearTimeout(view.input.composingTimeout);
  if (delay > -1)
    view.input.composingTimeout = setTimeout(() => endComposition(view), delay);
}
function clearComposition(view) {
  if (view.composing) {
    view.input.composing = false;
    view.input.compositionEndedAt = timestampFromCustomEvent();
  }
  while (view.input.compositionNodes.length > 0)
    view.input.compositionNodes.pop().markParentsDirty();
}
function findCompositionNode(view) {
  let sel = view.domSelectionRange();
  if (!sel.focusNode)
    return null;
  let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);
  let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);
  if (textBefore && textAfter && textBefore != textAfter) {
    let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;
    if (textBefore == lastChanged || textAfter == lastChanged)
      return lastChanged;
    if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {
      return textAfter;
    } else if (view.input.compositionNode == textAfter) {
      let descBefore = textBefore.pmViewDesc;
      if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))
        return textAfter;
    }
  }
  return textBefore || textAfter;
}
function timestampFromCustomEvent() {
  let event = document.createEvent("Event");
  event.initEvent("event", true, true);
  return event.timeStamp;
}
function endComposition(view, restarting = false) {
  if (android && view.domObserver.flushingSoon >= 0)
    return;
  view.domObserver.forceFlush();
  clearComposition(view);
  if (restarting || view.docView && view.docView.dirty) {
    let sel = selectionFromDOM(view), cur = view.state.selection;
    if (sel && !sel.eq(cur))
      view.dispatch(view.state.tr.setSelection(sel));
    else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent)
      view.dispatch(view.state.tr.deleteSelection());
    else
      view.updateState(view.state);
    return true;
  }
  return false;
}
function captureCopy(view, dom) {
  if (!view.dom.parentNode)
    return;
  let wrap5 = view.dom.parentNode.appendChild(document.createElement("div"));
  wrap5.appendChild(dom);
  wrap5.style.cssText = "position: fixed; left: -10000px; top: 10px";
  let sel = getSelection(), range = document.createRange();
  range.selectNodeContents(dom);
  view.dom.blur();
  sel.removeAllRanges();
  sel.addRange(range);
  setTimeout(() => {
    if (wrap5.parentNode)
      wrap5.parentNode.removeChild(wrap5);
    view.focus();
  }, 50);
}
var brokenClipboardAPI = ie && ie_version < 15 || ios && webkit_version < 604;
handlers.copy = editHandlers.cut = (view, _event) => {
  let event = _event;
  let sel = view.state.selection, cut2 = event.type == "cut";
  if (sel.empty)
    return;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  let slice2 = sel.content(), { dom, text: text10 } = serializeForClipboard(view, slice2);
  if (data) {
    event.preventDefault();
    data.clearData();
    data.setData("text/html", dom.innerHTML);
    data.setData("text/plain", text10);
  } else {
    captureCopy(view, dom);
  }
  if (cut2)
    view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut"));
};
function sliceSingleNode(slice2) {
  return slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1 ? slice2.content.firstChild : null;
}
function capturePaste(view, event) {
  if (!view.dom.parentNode)
    return;
  let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;
  let target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div"));
  if (!plainText)
    target.contentEditable = "true";
  target.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target.focus();
  let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
  setTimeout(() => {
    view.focus();
    if (target.parentNode)
      target.parentNode.removeChild(target);
    if (plainText)
      doPaste(view, target.value, null, plain, event);
    else
      doPaste(view, target.textContent, target.innerHTML, plain, event);
  }, 50);
}
function doPaste(view, text10, html7, preferPlain, event) {
  let slice2 = parseFromClipboard(view, text10, html7, preferPlain, view.state.selection.$from);
  if (view.someProp("handlePaste", (f6) => f6(view, event, slice2 || Slice.empty)))
    return true;
  if (!slice2)
    return false;
  let singleNode = sliceSingleNode(slice2);
  let tr4 = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice2);
  view.dispatch(tr4.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste"));
  return true;
}
function getText(clipboardData) {
  let text10 = clipboardData.getData("text/plain") || clipboardData.getData("Text");
  if (text10)
    return text10;
  let uris = clipboardData.getData("text/uri-list");
  return uris ? uris.replace(/\r?\n/g, " ") : "";
}
editHandlers.paste = (view, _event) => {
  let event = _event;
  if (view.composing && !android)
    return;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
  if (data && doPaste(view, getText(data), data.getData("text/html"), plain, event))
    event.preventDefault();
  else
    capturePaste(view, event);
};
var Dragging = class {
  constructor(slice2, move, node2) {
    this.slice = slice2;
    this.move = move;
    this.node = node2;
  }
};
var dragCopyModifier = mac ? "altKey" : "ctrlKey";
function dragMoves(view, event) {
  let moves = view.someProp("dragCopies", (test) => !test(event));
  return moves != null ? moves : !event[dragCopyModifier];
}
handlers.dragstart = (view, _event) => {
  let event = _event;
  let mouseDown = view.input.mouseDown;
  if (mouseDown)
    mouseDown.done();
  if (!event.dataTransfer)
    return;
  let sel = view.state.selection;
  let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));
  let node2;
  if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;
  else if (mouseDown && mouseDown.mightDrag) {
    node2 = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);
  } else if (event.target && event.target.nodeType == 1) {
    let desc = view.docView.nearestDesc(event.target, true);
    if (desc && desc.node.type.spec.draggable && desc != view.docView)
      node2 = NodeSelection.create(view.state.doc, desc.posBefore);
  }
  let draggedSlice = (node2 || view.state.selection).content();
  let { dom, text: text10, slice: slice2 } = serializeForClipboard(view, draggedSlice);
  if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)
    event.dataTransfer.clearData();
  event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML);
  event.dataTransfer.effectAllowed = "copyMove";
  if (!brokenClipboardAPI)
    event.dataTransfer.setData("text/plain", text10);
  view.dragging = new Dragging(slice2, dragMoves(view, event), node2);
};
handlers.dragend = (view) => {
  let dragging = view.dragging;
  window.setTimeout(() => {
    if (view.dragging == dragging)
      view.dragging = null;
  }, 50);
};
editHandlers.dragover = editHandlers.dragenter = (_2, e2) => e2.preventDefault();
editHandlers.drop = (view, event) => {
  try {
    handleDrop(view, event, view.dragging);
  } finally {
    view.dragging = null;
  }
};
function handleDrop(view, event, dragging) {
  if (!event.dataTransfer)
    return;
  let eventPos = view.posAtCoords(eventCoords(event));
  if (!eventPos)
    return;
  let $mouse = view.state.doc.resolve(eventPos.pos);
  let slice2 = dragging && dragging.slice;
  if (slice2) {
    view.someProp("transformPasted", (f6) => {
      slice2 = f6(slice2, view, false);
    });
  } else {
    slice2 = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse);
  }
  let move = !!(dragging && dragMoves(view, event));
  if (view.someProp("handleDrop", (f6) => f6(view, event, slice2 || Slice.empty, move))) {
    event.preventDefault();
    return;
  }
  if (!slice2)
    return;
  event.preventDefault();
  let insertPos = slice2 ? dropPoint(view.state.doc, $mouse.pos, slice2) : $mouse.pos;
  if (insertPos == null)
    insertPos = $mouse.pos;
  let tr4 = view.state.tr;
  if (move) {
    let { node: node2 } = dragging;
    if (node2)
      node2.replace(tr4);
    else
      tr4.deleteSelection();
  }
  let pos = tr4.mapping.map(insertPos);
  let isNode3 = slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1;
  let beforeInsert = tr4.doc;
  if (isNode3)
    tr4.replaceRangeWith(pos, pos, slice2.content.firstChild);
  else
    tr4.replaceRange(pos, pos, slice2);
  if (tr4.doc.eq(beforeInsert))
    return;
  let $pos = tr4.doc.resolve(pos);
  if (isNode3 && NodeSelection.isSelectable(slice2.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice2.content.firstChild)) {
    tr4.setSelection(new NodeSelection($pos));
  } else {
    let end = tr4.mapping.map(insertPos);
    tr4.mapping.maps[tr4.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);
    tr4.setSelection(selectionBetween(view, $pos, tr4.doc.resolve(end)));
  }
  view.focus();
  view.dispatch(tr4.setMeta("uiEvent", "drop"));
}
handlers.focus = (view) => {
  view.input.lastFocus = Date.now();
  if (!view.focused) {
    view.domObserver.stop();
    view.dom.classList.add("ProseMirror-focused");
    view.domObserver.start();
    view.focused = true;
    setTimeout(() => {
      if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))
        selectionToDOM(view);
    }, 20);
  }
};
handlers.blur = (view, _event) => {
  let event = _event;
  if (view.focused) {
    view.domObserver.stop();
    view.dom.classList.remove("ProseMirror-focused");
    view.domObserver.start();
    if (event.relatedTarget && view.dom.contains(event.relatedTarget))
      view.domObserver.currentSelection.clear();
    view.focused = false;
  }
};
handlers.beforeinput = (view, _event) => {
  let event = _event;
  if (chrome && android && event.inputType == "deleteContentBackward") {
    view.domObserver.flushSoon();
    let { domChangeCount } = view.input;
    setTimeout(() => {
      if (view.input.domChangeCount != domChangeCount)
        return;
      view.dom.blur();
      view.focus();
      if (view.someProp("handleKeyDown", (f6) => f6(view, keyEvent(8, "Backspace"))))
        return;
      let { $cursor } = view.state.selection;
      if ($cursor && $cursor.pos > 0)
        view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());
    }, 50);
  }
};
for (let prop in editHandlers)
  handlers[prop] = editHandlers[prop];
function compareObjs(a3, b4) {
  if (a3 == b4)
    return true;
  for (let p4 in a3)
    if (a3[p4] !== b4[p4])
      return false;
  for (let p4 in b4)
    if (!(p4 in a3))
      return false;
  return true;
}
var WidgetType = class _WidgetType {
  constructor(toDOM, spec) {
    this.toDOM = toDOM;
    this.spec = spec || noSpec;
    this.side = this.spec.side || 0;
  }
  map(mapping, span, offset4, oldOffset) {
    let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);
    return deleted ? null : new Decoration(pos - offset4, pos - offset4, this);
  }
  valid() {
    return true;
  }
  eq(other) {
    return this == other || other instanceof _WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec));
  }
  destroy(node2) {
    if (this.spec.destroy)
      this.spec.destroy(node2);
  }
};
var InlineType = class _InlineType {
  constructor(attrs, spec) {
    this.attrs = attrs;
    this.spec = spec || noSpec;
  }
  map(mapping, span, offset4, oldOffset) {
    let from4 = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset4;
    let to2 = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset4;
    return from4 >= to2 ? null : new Decoration(from4, to2, this);
  }
  valid(_2, span) {
    return span.from < span.to;
  }
  eq(other) {
    return this == other || other instanceof _InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
  }
  static is(span) {
    return span.type instanceof _InlineType;
  }
  destroy() {
  }
};
var NodeType2 = class _NodeType {
  constructor(attrs, spec) {
    this.attrs = attrs;
    this.spec = spec || noSpec;
  }
  map(mapping, span, offset4, oldOffset) {
    let from4 = mapping.mapResult(span.from + oldOffset, 1);
    if (from4.deleted)
      return null;
    let to2 = mapping.mapResult(span.to + oldOffset, -1);
    if (to2.deleted || to2.pos <= from4.pos)
      return null;
    return new Decoration(from4.pos - offset4, to2.pos - offset4, this);
  }
  valid(node2, span) {
    let { index: index4, offset: offset4 } = node2.content.findIndex(span.from), child;
    return offset4 == span.from && !(child = node2.child(index4)).isText && offset4 + child.nodeSize == span.to;
  }
  eq(other) {
    return this == other || other instanceof _NodeType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
  }
  destroy() {
  }
};
var Decoration = class _Decoration {
  /**
  @internal
  */
  constructor(from4, to2, type) {
    this.from = from4;
    this.to = to2;
    this.type = type;
  }
  /**
  @internal
  */
  copy(from4, to2) {
    return new _Decoration(from4, to2, this.type);
  }
  /**
  @internal
  */
  eq(other, offset4 = 0) {
    return this.type.eq(other.type) && this.from + offset4 == other.from && this.to + offset4 == other.to;
  }
  /**
  @internal
  */
  map(mapping, offset4, oldOffset) {
    return this.type.map(mapping, this, offset4, oldOffset);
  }
  /**
  Creates a widget decoration, which is a DOM node that's shown in
  the document at the given position. It is recommended that you
  delay rendering the widget by passing a function that will be
  called when the widget is actually drawn in a view, but you can
  also directly pass a DOM node. `getPos` can be used to find the
  widget's current document position.
  */
  static widget(pos, toDOM, spec) {
    return new _Decoration(pos, pos, new WidgetType(toDOM, spec));
  }
  /**
  Creates an inline decoration, which adds the given attributes to
  each inline node between `from` and `to`.
  */
  static inline(from4, to2, attrs, spec) {
    return new _Decoration(from4, to2, new InlineType(attrs, spec));
  }
  /**
  Creates a node decoration. `from` and `to` should point precisely
  before and after a node in the document. That node, and only that
  node, will receive the given attributes.
  */
  static node(from4, to2, attrs, spec) {
    return new _Decoration(from4, to2, new NodeType2(attrs, spec));
  }
  /**
  The spec provided when creating this decoration. Can be useful
  if you've stored extra information in that object.
  */
  get spec() {
    return this.type.spec;
  }
  /**
  @internal
  */
  get inline() {
    return this.type instanceof InlineType;
  }
  /**
  @internal
  */
  get widget() {
    return this.type instanceof WidgetType;
  }
};
var none = [];
var noSpec = {};
var DecorationSet = class _DecorationSet {
  /**
  @internal
  */
  constructor(local, children) {
    this.local = local.length ? local : none;
    this.children = children.length ? children : none;
  }
  /**
  Create a set of decorations, using the structure of the given
  document. This will consume (modify) the `decorations` array, so
  you must make a copy if you want need to preserve that.
  */
  static create(doc4, decorations) {
    return decorations.length ? buildTree(decorations, doc4, 0, noSpec) : empty;
  }
  /**
  Find all decorations in this set which touch the given range
  (including decorations that start or end directly at the
  boundaries) and match the given predicate on their spec. When
  `start` and `end` are omitted, all decorations in the set are
  considered. When `predicate` isn't given, all decorations are
  assumed to match.
  */
  find(start, end, predicate) {
    let result = [];
    this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);
    return result;
  }
  findInner(start, end, result, offset4, predicate) {
    for (let i3 = 0; i3 < this.local.length; i3++) {
      let span = this.local[i3];
      if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))
        result.push(span.copy(span.from + offset4, span.to + offset4));
    }
    for (let i3 = 0; i3 < this.children.length; i3 += 3) {
      if (this.children[i3] < end && this.children[i3 + 1] > start) {
        let childOff = this.children[i3] + 1;
        this.children[i3 + 2].findInner(start - childOff, end - childOff, result, offset4 + childOff, predicate);
      }
    }
  }
  /**
  Map the set of decorations in response to a change in the
  document.
  */
  map(mapping, doc4, options2) {
    if (this == empty || mapping.maps.length == 0)
      return this;
    return this.mapInner(mapping, doc4, 0, 0, options2 || noSpec);
  }
  /**
  @internal
  */
  mapInner(mapping, node2, offset4, oldOffset, options2) {
    let newLocal;
    for (let i3 = 0; i3 < this.local.length; i3++) {
      let mapped = this.local[i3].map(mapping, offset4, oldOffset);
      if (mapped && mapped.type.valid(node2, mapped))
        (newLocal || (newLocal = [])).push(mapped);
      else if (options2.onRemove)
        options2.onRemove(this.local[i3].spec);
    }
    if (this.children.length)
      return mapChildren(this.children, newLocal || [], mapping, node2, offset4, oldOffset, options2);
    else
      return newLocal ? new _DecorationSet(newLocal.sort(byPos), none) : empty;
  }
  /**
  Add the given array of decorations to the ones in the set,
  producing a new set. Consumes the `decorations` array. Needs
  access to the current document to create the appropriate tree
  structure.
  */
  add(doc4, decorations) {
    if (!decorations.length)
      return this;
    if (this == empty)
      return _DecorationSet.create(doc4, decorations);
    return this.addInner(doc4, decorations, 0);
  }
  addInner(doc4, decorations, offset4) {
    let children, childIndex = 0;
    doc4.forEach((childNode, childOffset) => {
      let baseOffset = childOffset + offset4, found2;
      if (!(found2 = takeSpansForNode(decorations, childNode, baseOffset)))
        return;
      if (!children)
        children = this.children.slice();
      while (childIndex < children.length && children[childIndex] < childOffset)
        childIndex += 3;
      if (children[childIndex] == childOffset)
        children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found2, baseOffset + 1);
      else
        children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found2, childNode, baseOffset + 1, noSpec));
      childIndex += 3;
    });
    let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset4);
    for (let i3 = 0; i3 < local.length; i3++)
      if (!local[i3].type.valid(doc4, local[i3]))
        local.splice(i3--, 1);
    return new _DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);
  }
  /**
  Create a new set that contains the decorations in this set, minus
  the ones in the given array.
  */
  remove(decorations) {
    if (decorations.length == 0 || this == empty)
      return this;
    return this.removeInner(decorations, 0);
  }
  removeInner(decorations, offset4) {
    let children = this.children, local = this.local;
    for (let i3 = 0; i3 < children.length; i3 += 3) {
      let found2;
      let from4 = children[i3] + offset4, to2 = children[i3 + 1] + offset4;
      for (let j4 = 0, span; j4 < decorations.length; j4++)
        if (span = decorations[j4]) {
          if (span.from > from4 && span.to < to2) {
            decorations[j4] = null;
            (found2 || (found2 = [])).push(span);
          }
        }
      if (!found2)
        continue;
      if (children == this.children)
        children = this.children.slice();
      let removed = children[i3 + 2].removeInner(found2, from4 + 1);
      if (removed != empty) {
        children[i3 + 2] = removed;
      } else {
        children.splice(i3, 3);
        i3 -= 3;
      }
    }
    if (local.length) {
      for (let i3 = 0, span; i3 < decorations.length; i3++)
        if (span = decorations[i3]) {
          for (let j4 = 0; j4 < local.length; j4++)
            if (local[j4].eq(span, offset4)) {
              if (local == this.local)
                local = this.local.slice();
              local.splice(j4--, 1);
            }
        }
    }
    if (children == this.children && local == this.local)
      return this;
    return local.length || children.length ? new _DecorationSet(local, children) : empty;
  }
  forChild(offset4, node2) {
    if (this == empty)
      return this;
    if (node2.isLeaf)
      return _DecorationSet.empty;
    let child, local;
    for (let i3 = 0; i3 < this.children.length; i3 += 3)
      if (this.children[i3] >= offset4) {
        if (this.children[i3] == offset4)
          child = this.children[i3 + 2];
        break;
      }
    let start = offset4 + 1, end = start + node2.content.size;
    for (let i3 = 0; i3 < this.local.length; i3++) {
      let dec = this.local[i3];
      if (dec.from < end && dec.to > start && dec.type instanceof InlineType) {
        let from4 = Math.max(start, dec.from) - start, to2 = Math.min(end, dec.to) - start;
        if (from4 < to2)
          (local || (local = [])).push(dec.copy(from4, to2));
      }
    }
    if (local) {
      let localSet = new _DecorationSet(local.sort(byPos), none);
      return child ? new DecorationGroup([localSet, child]) : localSet;
    }
    return child || empty;
  }
  /**
  @internal
  */
  eq(other) {
    if (this == other)
      return true;
    if (!(other instanceof _DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length)
      return false;
    for (let i3 = 0; i3 < this.local.length; i3++)
      if (!this.local[i3].eq(other.local[i3]))
        return false;
    for (let i3 = 0; i3 < this.children.length; i3 += 3)
      if (this.children[i3] != other.children[i3] || this.children[i3 + 1] != other.children[i3 + 1] || !this.children[i3 + 2].eq(other.children[i3 + 2]))
        return false;
    return true;
  }
  /**
  @internal
  */
  locals(node2) {
    return removeOverlap(this.localsInner(node2));
  }
  /**
  @internal
  */
  localsInner(node2) {
    if (this == empty)
      return none;
    if (node2.inlineContent || !this.local.some(InlineType.is))
      return this.local;
    let result = [];
    for (let i3 = 0; i3 < this.local.length; i3++) {
      if (!(this.local[i3].type instanceof InlineType))
        result.push(this.local[i3]);
    }
    return result;
  }
  forEachSet(f6) {
    f6(this);
  }
};
DecorationSet.empty = new DecorationSet([], []);
DecorationSet.removeOverlap = removeOverlap;
var empty = DecorationSet.empty;
var DecorationGroup = class _DecorationGroup {
  constructor(members) {
    this.members = members;
  }
  map(mapping, doc4) {
    const mappedDecos = this.members.map((member) => member.map(mapping, doc4, noSpec));
    return _DecorationGroup.from(mappedDecos);
  }
  forChild(offset4, child) {
    if (child.isLeaf)
      return DecorationSet.empty;
    let found2 = [];
    for (let i3 = 0; i3 < this.members.length; i3++) {
      let result = this.members[i3].forChild(offset4, child);
      if (result == empty)
        continue;
      if (result instanceof _DecorationGroup)
        found2 = found2.concat(result.members);
      else
        found2.push(result);
    }
    return _DecorationGroup.from(found2);
  }
  eq(other) {
    if (!(other instanceof _DecorationGroup) || other.members.length != this.members.length)
      return false;
    for (let i3 = 0; i3 < this.members.length; i3++)
      if (!this.members[i3].eq(other.members[i3]))
        return false;
    return true;
  }
  locals(node2) {
    let result, sorted = true;
    for (let i3 = 0; i3 < this.members.length; i3++) {
      let locals = this.members[i3].localsInner(node2);
      if (!locals.length)
        continue;
      if (!result) {
        result = locals;
      } else {
        if (sorted) {
          result = result.slice();
          sorted = false;
        }
        for (let j4 = 0; j4 < locals.length; j4++)
          result.push(locals[j4]);
      }
    }
    return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;
  }
  // Create a group for the given array of decoration sets, or return
  // a single set when possible.
  static from(members) {
    switch (members.length) {
      case 0:
        return empty;
      case 1:
        return members[0];
      default:
        return new _DecorationGroup(members.every((m2) => m2 instanceof DecorationSet) ? members : members.reduce((r4, m2) => r4.concat(m2 instanceof DecorationSet ? m2 : m2.members), []));
    }
  }
  forEachSet(f6) {
    for (let i3 = 0; i3 < this.members.length; i3++)
      this.members[i3].forEachSet(f6);
  }
};
function mapChildren(oldChildren, newLocal, mapping, node2, offset4, oldOffset, options2) {
  let children = oldChildren.slice();
  for (let i3 = 0, baseOffset = oldOffset; i3 < mapping.maps.length; i3++) {
    let moved = 0;
    mapping.maps[i3].forEach((oldStart, oldEnd, newStart, newEnd) => {
      let dSize = newEnd - newStart - (oldEnd - oldStart);
      for (let i4 = 0; i4 < children.length; i4 += 3) {
        let end = children[i4 + 1];
        if (end < 0 || oldStart > end + baseOffset - moved)
          continue;
        let start = children[i4] + baseOffset - moved;
        if (oldEnd >= start) {
          children[i4 + 1] = oldStart <= start ? -2 : -1;
        } else if (oldStart >= baseOffset && dSize) {
          children[i4] += dSize;
          children[i4 + 1] += dSize;
        }
      }
      moved += dSize;
    });
    baseOffset = mapping.maps[i3].map(baseOffset, -1);
  }
  let mustRebuild = false;
  for (let i3 = 0; i3 < children.length; i3 += 3)
    if (children[i3 + 1] < 0) {
      if (children[i3 + 1] == -2) {
        mustRebuild = true;
        children[i3 + 1] = -1;
        continue;
      }
      let from4 = mapping.map(oldChildren[i3] + oldOffset), fromLocal = from4 - offset4;
      if (fromLocal < 0 || fromLocal >= node2.content.size) {
        mustRebuild = true;
        continue;
      }
      let to2 = mapping.map(oldChildren[i3 + 1] + oldOffset, -1), toLocal = to2 - offset4;
      let { index: index4, offset: childOffset } = node2.content.findIndex(fromLocal);
      let childNode = node2.maybeChild(index4);
      if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {
        let mapped = children[i3 + 2].mapInner(mapping, childNode, from4 + 1, oldChildren[i3] + oldOffset + 1, options2);
        if (mapped != empty) {
          children[i3] = fromLocal;
          children[i3 + 1] = toLocal;
          children[i3 + 2] = mapped;
        } else {
          children[i3 + 1] = -2;
          mustRebuild = true;
        }
      } else {
        mustRebuild = true;
      }
    }
  if (mustRebuild) {
    let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset4, oldOffset, options2);
    let built = buildTree(decorations, node2, 0, options2);
    newLocal = built.local;
    for (let i3 = 0; i3 < children.length; i3 += 3)
      if (children[i3 + 1] < 0) {
        children.splice(i3, 3);
        i3 -= 3;
      }
    for (let i3 = 0, j4 = 0; i3 < built.children.length; i3 += 3) {
      let from4 = built.children[i3];
      while (j4 < children.length && children[j4] < from4)
        j4 += 3;
      children.splice(j4, 0, built.children[i3], built.children[i3 + 1], built.children[i3 + 2]);
    }
  }
  return new DecorationSet(newLocal.sort(byPos), children);
}
function moveSpans(spans, offset4) {
  if (!offset4 || !spans.length)
    return spans;
  let result = [];
  for (let i3 = 0; i3 < spans.length; i3++) {
    let span = spans[i3];
    result.push(new Decoration(span.from + offset4, span.to + offset4, span.type));
  }
  return result;
}
function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset4, oldOffset, options2) {
  function gather(set, oldOffset2) {
    for (let i3 = 0; i3 < set.local.length; i3++) {
      let mapped = set.local[i3].map(mapping, offset4, oldOffset2);
      if (mapped)
        decorations.push(mapped);
      else if (options2.onRemove)
        options2.onRemove(set.local[i3].spec);
    }
    for (let i3 = 0; i3 < set.children.length; i3 += 3)
      gather(set.children[i3 + 2], set.children[i3] + oldOffset2 + 1);
  }
  for (let i3 = 0; i3 < children.length; i3 += 3)
    if (children[i3 + 1] == -1)
      gather(children[i3 + 2], oldChildren[i3] + oldOffset + 1);
  return decorations;
}
function takeSpansForNode(spans, node2, offset4) {
  if (node2.isLeaf)
    return null;
  let end = offset4 + node2.nodeSize, found2 = null;
  for (let i3 = 0, span; i3 < spans.length; i3++) {
    if ((span = spans[i3]) && span.from > offset4 && span.to < end) {
      (found2 || (found2 = [])).push(span);
      spans[i3] = null;
    }
  }
  return found2;
}
function withoutNulls(array) {
  let result = [];
  for (let i3 = 0; i3 < array.length; i3++)
    if (array[i3] != null)
      result.push(array[i3]);
  return result;
}
function buildTree(spans, node2, offset4, options2) {
  let children = [], hasNulls = false;
  node2.forEach((childNode, localStart) => {
    let found2 = takeSpansForNode(spans, childNode, localStart + offset4);
    if (found2) {
      hasNulls = true;
      let subtree = buildTree(found2, childNode, offset4 + localStart + 1, options2);
      if (subtree != empty)
        children.push(localStart, localStart + childNode.nodeSize, subtree);
    }
  });
  let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset4).sort(byPos);
  for (let i3 = 0; i3 < locals.length; i3++)
    if (!locals[i3].type.valid(node2, locals[i3])) {
      if (options2.onRemove)
        options2.onRemove(locals[i3].spec);
      locals.splice(i3--, 1);
    }
  return locals.length || children.length ? new DecorationSet(locals, children) : empty;
}
function byPos(a3, b4) {
  return a3.from - b4.from || a3.to - b4.to;
}
function removeOverlap(spans) {
  let working = spans;
  for (let i3 = 0; i3 < working.length - 1; i3++) {
    let span = working[i3];
    if (span.from != span.to)
      for (let j4 = i3 + 1; j4 < working.length; j4++) {
        let next2 = working[j4];
        if (next2.from == span.from) {
          if (next2.to != span.to) {
            if (working == spans)
              working = spans.slice();
            working[j4] = next2.copy(next2.from, span.to);
            insertAhead(working, j4 + 1, next2.copy(span.to, next2.to));
          }
          continue;
        } else {
          if (next2.from < span.to) {
            if (working == spans)
              working = spans.slice();
            working[i3] = span.copy(span.from, next2.from);
            insertAhead(working, j4, span.copy(next2.from, span.to));
          }
          break;
        }
      }
  }
  return working;
}
function insertAhead(array, i3, deco) {
  while (i3 < array.length && byPos(deco, array[i3]) > 0)
    i3++;
  array.splice(i3, 0, deco);
}
function viewDecorations(view) {
  let found2 = [];
  view.someProp("decorations", (f6) => {
    let result = f6(view.state);
    if (result && result != empty)
      found2.push(result);
  });
  if (view.cursorWrapper)
    found2.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));
  return DecorationGroup.from(found2);
}
var observeOptions = {
  childList: true,
  characterData: true,
  characterDataOldValue: true,
  attributes: true,
  attributeOldValue: true,
  subtree: true
};
var useCharData = ie && ie_version <= 11;
var SelectionState = class {
  constructor() {
    this.anchorNode = null;
    this.anchorOffset = 0;
    this.focusNode = null;
    this.focusOffset = 0;
  }
  set(sel) {
    this.anchorNode = sel.anchorNode;
    this.anchorOffset = sel.anchorOffset;
    this.focusNode = sel.focusNode;
    this.focusOffset = sel.focusOffset;
  }
  clear() {
    this.anchorNode = this.focusNode = null;
  }
  eq(sel) {
    return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;
  }
};
var DOMObserver = class {
  constructor(view, handleDOMChange) {
    this.view = view;
    this.handleDOMChange = handleDOMChange;
    this.queue = [];
    this.flushingSoon = -1;
    this.observer = null;
    this.currentSelection = new SelectionState();
    this.onCharData = null;
    this.suppressingSelectionUpdates = false;
    this.lastChangedTextNode = null;
    this.observer = window.MutationObserver && new window.MutationObserver((mutations) => {
      for (let i3 = 0; i3 < mutations.length; i3++)
        this.queue.push(mutations[i3]);
      if (ie && ie_version <= 11 && mutations.some((m2) => m2.type == "childList" && m2.removedNodes.length || m2.type == "characterData" && m2.oldValue.length > m2.target.nodeValue.length))
        this.flushSoon();
      else
        this.flush();
    });
    if (useCharData) {
      this.onCharData = (e2) => {
        this.queue.push({ target: e2.target, type: "characterData", oldValue: e2.prevValue });
        this.flushSoon();
      };
    }
    this.onSelectionChange = this.onSelectionChange.bind(this);
  }
  flushSoon() {
    if (this.flushingSoon < 0)
      this.flushingSoon = window.setTimeout(() => {
        this.flushingSoon = -1;
        this.flush();
      }, 20);
  }
  forceFlush() {
    if (this.flushingSoon > -1) {
      window.clearTimeout(this.flushingSoon);
      this.flushingSoon = -1;
      this.flush();
    }
  }
  start() {
    if (this.observer) {
      this.observer.takeRecords();
      this.observer.observe(this.view.dom, observeOptions);
    }
    if (this.onCharData)
      this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
    this.connectSelection();
  }
  stop() {
    if (this.observer) {
      let take = this.observer.takeRecords();
      if (take.length) {
        for (let i3 = 0; i3 < take.length; i3++)
          this.queue.push(take[i3]);
        window.setTimeout(() => this.flush(), 20);
      }
      this.observer.disconnect();
    }
    if (this.onCharData)
      this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
    this.disconnectSelection();
  }
  connectSelection() {
    this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
  }
  disconnectSelection() {
    this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
  }
  suppressSelectionUpdates() {
    this.suppressingSelectionUpdates = true;
    setTimeout(() => this.suppressingSelectionUpdates = false, 50);
  }
  onSelectionChange() {
    if (!hasFocusAndSelection(this.view))
      return;
    if (this.suppressingSelectionUpdates)
      return selectionToDOM(this.view);
    if (ie && ie_version <= 11 && !this.view.state.selection.empty) {
      let sel = this.view.domSelectionRange();
      if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
        return this.flushSoon();
    }
    this.flush();
  }
  setCurSelection() {
    this.currentSelection.set(this.view.domSelectionRange());
  }
  ignoreSelectionChange(sel) {
    if (!sel.focusNode)
      return true;
    let ancestors = /* @__PURE__ */ new Set(), container;
    for (let scan = sel.focusNode; scan; scan = parentNode(scan))
      ancestors.add(scan);
    for (let scan = sel.anchorNode; scan; scan = parentNode(scan))
      if (ancestors.has(scan)) {
        container = scan;
        break;
      }
    let desc = container && this.view.docView.nearestDesc(container);
    if (desc && desc.ignoreMutation({
      type: "selection",
      target: container.nodeType == 3 ? container.parentNode : container
    })) {
      this.setCurSelection();
      return true;
    }
  }
  pendingRecords() {
    if (this.observer)
      for (let mut of this.observer.takeRecords())
        this.queue.push(mut);
    return this.queue;
  }
  flush() {
    let { view } = this;
    if (!view.docView || this.flushingSoon > -1)
      return;
    let mutations = this.pendingRecords();
    if (mutations.length)
      this.queue = [];
    let sel = view.domSelectionRange();
    let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel);
    let from4 = -1, to2 = -1, typeOver = false, added = [];
    if (view.editable) {
      for (let i3 = 0; i3 < mutations.length; i3++) {
        let result = this.registerMutation(mutations[i3], added);
        if (result) {
          from4 = from4 < 0 ? result.from : Math.min(result.from, from4);
          to2 = to2 < 0 ? result.to : Math.max(result.to, to2);
          if (result.typeOver)
            typeOver = true;
        }
      }
    }
    if (gecko && added.length) {
      let brs = added.filter((n) => n.nodeName == "BR");
      if (brs.length == 2) {
        let [a3, b4] = brs;
        if (a3.parentNode && a3.parentNode.parentNode == b4.parentNode)
          b4.remove();
        else
          a3.remove();
      } else {
        let { focusNode } = this.currentSelection;
        for (let br4 of brs) {
          let parent = br4.parentNode;
          if (parent && parent.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent))
            br4.remove();
        }
      }
    } else if ((chrome || safari) && added.some((n) => n.nodeName == "BR") && (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46)) {
      for (let node2 of added)
        if (node2.nodeName == "BR" && node2.parentNode) {
          let after = node2.nextSibling;
          if (after && after.nodeType == 1 && after.contentEditable == "false")
            node2.parentNode.removeChild(node2);
        }
    }
    let readSel = null;
    if (from4 < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {
      view.input.lastFocus = 0;
      selectionToDOM(view);
      this.currentSelection.set(sel);
      view.scrollToSelection();
    } else if (from4 > -1 || newSel) {
      if (from4 > -1) {
        view.docView.markDirty(from4, to2);
        checkCSS(view);
      }
      this.handleDOMChange(from4, to2, typeOver, added);
      if (view.docView && view.docView.dirty)
        view.updateState(view.state);
      else if (!this.currentSelection.eq(sel))
        selectionToDOM(view);
      this.currentSelection.set(sel);
    }
  }
  registerMutation(mut, added) {
    if (added.indexOf(mut.target) > -1)
      return null;
    let desc = this.view.docView.nearestDesc(mut.target);
    if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles
    mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style")))
      return null;
    if (!desc || desc.ignoreMutation(mut))
      return null;
    if (mut.type == "childList") {
      for (let i3 = 0; i3 < mut.addedNodes.length; i3++) {
        let node2 = mut.addedNodes[i3];
        added.push(node2);
        if (node2.nodeType == 3)
          this.lastChangedTextNode = node2;
      }
      if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))
        return { from: desc.posBefore, to: desc.posAfter };
      let prev = mut.previousSibling, next2 = mut.nextSibling;
      if (ie && ie_version <= 11 && mut.addedNodes.length) {
        for (let i3 = 0; i3 < mut.addedNodes.length; i3++) {
          let { previousSibling, nextSibling } = mut.addedNodes[i3];
          if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)
            prev = previousSibling;
          if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)
            next2 = nextSibling;
        }
      }
      let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0;
      let from4 = desc.localPosFromDOM(mut.target, fromOffset, -1);
      let toOffset = next2 && next2.parentNode == mut.target ? domIndex(next2) : mut.target.childNodes.length;
      let to2 = desc.localPosFromDOM(mut.target, toOffset, 1);
      return { from: from4, to: to2 };
    } else if (mut.type == "attributes") {
      return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };
    } else {
      this.lastChangedTextNode = mut.target;
      return {
        from: desc.posAtStart,
        to: desc.posAtEnd,
        // An event was generated for a text change that didn't change
        // any text. Mark the dom change to fall back to assuming the
        // selection was typed over with an identical value if it can't
        // find another change.
        typeOver: mut.target.nodeValue == mut.oldValue
      };
    }
  }
};
var cssChecked = /* @__PURE__ */ new WeakMap();
var cssCheckWarned = false;
function checkCSS(view) {
  if (cssChecked.has(view))
    return;
  cssChecked.set(view, null);
  if (["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {
    view.requiresGeckoHackNode = gecko;
    if (cssCheckWarned)
      return;
    console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.");
    cssCheckWarned = true;
  }
}
function rangeToSelectionRange(view, range) {
  let anchorNode = range.startContainer, anchorOffset = range.startOffset;
  let focusNode = range.endContainer, focusOffset = range.endOffset;
  let currentAnchor = view.domAtPos(view.state.selection.anchor);
  if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))
    [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
  return { anchorNode, anchorOffset, focusNode, focusOffset };
}
function safariShadowSelectionRange(view, selection) {
  if (selection.getComposedRanges) {
    let range = selection.getComposedRanges(view.root)[0];
    if (range)
      return rangeToSelectionRange(view, range);
  }
  let found2;
  function read(event) {
    event.preventDefault();
    event.stopImmediatePropagation();
    found2 = event.getTargetRanges()[0];
  }
  view.dom.addEventListener("beforeinput", read, true);
  document.execCommand("indent");
  view.dom.removeEventListener("beforeinput", read, true);
  return found2 ? rangeToSelectionRange(view, found2) : null;
}
function blockParent(view, node2) {
  for (let p4 = node2.parentNode; p4 && p4 != view.dom; p4 = p4.parentNode) {
    let desc = view.docView.nearestDesc(p4, true);
    if (desc && desc.node.isBlock)
      return p4;
  }
  return null;
}
function parseBetween(view, from_, to_) {
  let { node: parent, fromOffset, toOffset, from: from4, to: to2 } = view.docView.parseRange(from_, to_);
  let domSel = view.domSelectionRange();
  let find4;
  let anchor = domSel.anchorNode;
  if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {
    find4 = [{ node: anchor, offset: domSel.anchorOffset }];
    if (!selectionCollapsed(domSel))
      find4.push({ node: domSel.focusNode, offset: domSel.focusOffset });
  }
  if (chrome && view.input.lastKeyCode === 8) {
    for (let off = toOffset; off > fromOffset; off--) {
      let node2 = parent.childNodes[off - 1], desc = node2.pmViewDesc;
      if (node2.nodeName == "BR" && !desc) {
        toOffset = off;
        break;
      }
      if (!desc || desc.size)
        break;
    }
  }
  let startDoc = view.state.doc;
  let parser = view.someProp("domParser") || DOMParser2.fromSchema(view.state.schema);
  let $from = startDoc.resolve(from4);
  let sel = null, doc4 = parser.parse(parent, {
    topNode: $from.parent,
    topMatch: $from.parent.contentMatchAt($from.index()),
    topOpen: true,
    from: fromOffset,
    to: toOffset,
    preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true,
    findPositions: find4,
    ruleFromNode,
    context: $from
  });
  if (find4 && find4[0].pos != null) {
    let anchor2 = find4[0].pos, head2 = find4[1] && find4[1].pos;
    if (head2 == null)
      head2 = anchor2;
    sel = { anchor: anchor2 + from4, head: head2 + from4 };
  }
  return { doc: doc4, sel, from: from4, to: to2 };
}
function ruleFromNode(dom) {
  let desc = dom.pmViewDesc;
  if (desc) {
    return desc.parseRule();
  } else if (dom.nodeName == "BR" && dom.parentNode) {
    if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {
      let skip = document.createElement("div");
      skip.appendChild(document.createElement("li"));
      return { skip };
    } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {
      return { ignore: true };
    }
  } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) {
    return { ignore: true };
  }
  return null;
}
var isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;
function readDOMChange(view, from4, to2, typeOver, addedNodes) {
  let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);
  view.input.compositionPendingChanges = 0;
  if (from4 < 0) {
    let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;
    let newSel = selectionFromDOM(view, origin);
    if (newSel && !view.state.selection.eq(newSel)) {
      if (chrome && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f6) => f6(view, keyEvent(13, "Enter"))))
        return;
      let tr4 = view.state.tr.setSelection(newSel);
      if (origin == "pointer")
        tr4.setMeta("pointer", true);
      else if (origin == "key")
        tr4.scrollIntoView();
      if (compositionID)
        tr4.setMeta("composition", compositionID);
      view.dispatch(tr4);
    }
    return;
  }
  let $before = view.state.doc.resolve(from4);
  let shared = $before.sharedDepth(to2);
  from4 = $before.before(shared + 1);
  to2 = view.state.doc.resolve(to2).after(shared + 1);
  let sel = view.state.selection;
  let parse6 = parseBetween(view, from4, to2);
  let doc4 = view.state.doc, compare = doc4.slice(parse6.from, parse6.to);
  let preferredPos, preferredSide;
  if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {
    preferredPos = view.state.selection.to;
    preferredSide = "end";
  } else {
    preferredPos = view.state.selection.from;
    preferredSide = "start";
  }
  view.input.lastKeyCode = null;
  let change = findDiff(compare.content, parse6.doc.content, parse6.from, preferredPos, preferredSide);
  if (change)
    view.input.domChangeCount++;
  if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n) => n.nodeType == 1 && !isInline.test(n.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f6) => f6(view, keyEvent(13, "Enter")))) {
    view.input.lastIOSEnter = 0;
    return;
  }
  if (!change) {
    if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse6.sel && parse6.sel.anchor != parse6.sel.head)) {
      change = { start: sel.from, endA: sel.to, endB: sel.to };
    } else {
      if (parse6.sel) {
        let sel2 = resolveSelection(view, view.state.doc, parse6.sel);
        if (sel2 && !sel2.eq(view.state.selection)) {
          let tr4 = view.state.tr.setSelection(sel2);
          if (compositionID)
            tr4.setMeta("composition", compositionID);
          view.dispatch(tr4);
        }
      }
      return;
    }
  }
  if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) {
    if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse6.from) {
      change.start = view.state.selection.from;
    } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse6.to) {
      change.endB += view.state.selection.to - change.endA;
      change.endA = view.state.selection.to;
    }
  }
  if (ie && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse6.from && parse6.doc.textBetween(change.start - parse6.from - 1, change.start - parse6.from + 1) == "  ") {
    change.start--;
    change.endA--;
    change.endB--;
  }
  let $from = parse6.doc.resolveNoCache(change.start - parse6.from);
  let $to = parse6.doc.resolveNoCache(change.endB - parse6.from);
  let $fromA = doc4.resolve(change.start);
  let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;
  if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n) => n.nodeName == "DIV" || n.nodeName == "P")) || !inlineChange && $from.pos < parse6.doc.content.size && (!$from.sameParent($to) || !$from.parent.inlineContent) && $from.pos < $to.pos && !/\S/.test(parse6.doc.textBetween($from.pos, $to.pos, "", ""))) && view.someProp("handleKeyDown", (f6) => f6(view, keyEvent(13, "Enter")))) {
    view.input.lastIOSEnter = 0;
    return;
  }
  if (view.state.selection.anchor > change.start && looksLikeBackspace(doc4, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f6) => f6(view, keyEvent(8, "Backspace")))) {
    if (android && chrome)
      view.domObserver.suppressSelectionUpdates();
    return;
  }
  if (chrome && change.endB == change.start)
    view.input.lastChromeDelete = Date.now();
  if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse6.sel && parse6.sel.anchor == parse6.sel.head && parse6.sel.head == change.endA) {
    change.endB -= 2;
    $to = parse6.doc.resolveNoCache(change.endB - parse6.from);
    setTimeout(() => {
      view.someProp("handleKeyDown", function(f6) {
        return f6(view, keyEvent(13, "Enter"));
      });
    }, 20);
  }
  let chFrom = change.start, chTo = change.endA;
  let mkTr = (base4) => {
    let tr4 = base4 || view.state.tr.replace(chFrom, chTo, parse6.doc.slice(change.start - parse6.from, change.endB - parse6.from));
    if (parse6.sel) {
      let sel2 = resolveSelection(view, tr4.doc, parse6.sel);
      if (sel2 && !(chrome && view.composing && sel2.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel2.head == chFrom || sel2.head == tr4.mapping.map(chTo) - 1) || ie && sel2.empty && sel2.head == chFrom))
        tr4.setSelection(sel2);
    }
    if (compositionID)
      tr4.setMeta("composition", compositionID);
    return tr4.scrollIntoView();
  };
  let markChange;
  if (inlineChange) {
    if ($from.pos == $to.pos) {
      if (ie && ie_version <= 11 && $from.parentOffset == 0) {
        view.domObserver.suppressSelectionUpdates();
        setTimeout(() => selectionToDOM(view), 20);
      }
      let tr4 = mkTr(view.state.tr.delete(chFrom, chTo));
      let marks = doc4.resolve(change.start).marksAcross(doc4.resolve(change.endA));
      if (marks)
        tr4.ensureMarks(marks);
      view.dispatch(tr4);
    } else if (
      // Adding or removing a mark
      change.endA == change.endB && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))
    ) {
      let tr4 = mkTr(view.state.tr);
      if (markChange.type == "add")
        tr4.addMark(chFrom, chTo, markChange.mark);
      else
        tr4.removeMark(chFrom, chTo, markChange.mark);
      view.dispatch(tr4);
    } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {
      let text10 = $from.parent.textBetween($from.parentOffset, $to.parentOffset);
      let deflt = () => mkTr(view.state.tr.insertText(text10, chFrom, chTo));
      if (!view.someProp("handleTextInput", (f6) => f6(view, chFrom, chTo, text10, deflt)))
        view.dispatch(deflt());
    } else {
      view.dispatch(mkTr());
    }
  } else {
    view.dispatch(mkTr());
  }
}
function resolveSelection(view, doc4, parsedSel) {
  if (Math.max(parsedSel.anchor, parsedSel.head) > doc4.content.size)
    return null;
  return selectionBetween(view, doc4.resolve(parsedSel.anchor), doc4.resolve(parsedSel.head));
}
function isMarkChange(cur, prev) {
  let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;
  let added = curMarks, removed = prevMarks, type, mark2, update;
  for (let i3 = 0; i3 < prevMarks.length; i3++)
    added = prevMarks[i3].removeFromSet(added);
  for (let i3 = 0; i3 < curMarks.length; i3++)
    removed = curMarks[i3].removeFromSet(removed);
  if (added.length == 1 && removed.length == 0) {
    mark2 = added[0];
    type = "add";
    update = (node2) => node2.mark(mark2.addToSet(node2.marks));
  } else if (added.length == 0 && removed.length == 1) {
    mark2 = removed[0];
    type = "remove";
    update = (node2) => node2.mark(mark2.removeFromSet(node2.marks));
  } else {
    return null;
  }
  let updated = [];
  for (let i3 = 0; i3 < prev.childCount; i3++)
    updated.push(update(prev.child(i3)));
  if (Fragment.from(updated).eq(cur))
    return { mark: mark2, type };
}
function looksLikeBackspace(old, start, end, $newStart, $newEnd) {
  if (
    // The content must have shrunk
    end - start <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into
    skipClosingAndOpening($newStart, true, false) < $newEnd.pos
  )
    return false;
  let $start = old.resolve(start);
  if (!$newStart.parent.isTextblock) {
    let after = $start.nodeAfter;
    return after != null && end == start + after.nodeSize;
  }
  if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)
    return false;
  let $next = old.resolve(skipClosingAndOpening($start, true, true));
  if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end)
    return false;
  return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);
}
function skipClosingAndOpening($pos, fromEnd, mayOpen) {
  let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;
  while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {
    depth--;
    end++;
    fromEnd = false;
  }
  if (mayOpen) {
    let next2 = $pos.node(depth).maybeChild($pos.indexAfter(depth));
    while (next2 && !next2.isLeaf) {
      next2 = next2.firstChild;
      end++;
    }
  }
  return end;
}
function findDiff(a3, b4, pos, preferredPos, preferredSide) {
  let start = a3.findDiffStart(b4, pos);
  if (start == null)
    return null;
  let { a: endA, b: endB } = a3.findDiffEnd(b4, pos + a3.size, pos + b4.size);
  if (preferredSide == "end") {
    let adjust = Math.max(0, start - Math.min(endA, endB));
    preferredPos -= endA + adjust - start;
  }
  if (endA < start && a3.size < b4.size) {
    let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;
    start -= move;
    if (start && start < b4.size && isSurrogatePair(b4.textBetween(start - 1, start + 1)))
      start += move ? 1 : -1;
    endB = start + (endB - endA);
    endA = start;
  } else if (endB < start) {
    let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;
    start -= move;
    if (start && start < a3.size && isSurrogatePair(a3.textBetween(start - 1, start + 1)))
      start += move ? 1 : -1;
    endA = start + (endA - endB);
    endB = start;
  }
  return { start, endA, endB };
}
function isSurrogatePair(str) {
  if (str.length != 2)
    return false;
  let a3 = str.charCodeAt(0), b4 = str.charCodeAt(1);
  return a3 >= 56320 && a3 <= 57343 && b4 >= 55296 && b4 <= 56319;
}
var EditorView = class {
  /**
  Create a view. `place` may be a DOM node that the editor should
  be appended to, a function that will place it into the document,
  or an object whose `mount` property holds the node to use as the
  document container. If it is `null`, the editor will not be
  added to the document.
  */
  constructor(place, props) {
    this._root = null;
    this.focused = false;
    this.trackWrites = null;
    this.mounted = false;
    this.markCursor = null;
    this.cursorWrapper = null;
    this.lastSelectedViewDesc = void 0;
    this.input = new InputState();
    this.prevDirectPlugins = [];
    this.pluginViews = [];
    this.requiresGeckoHackNode = false;
    this.dragging = null;
    this._props = props;
    this.state = props.state;
    this.directPlugins = props.plugins || [];
    this.directPlugins.forEach(checkStateComponent);
    this.dispatch = this.dispatch.bind(this);
    this.dom = place && place.mount || document.createElement("div");
    if (place) {
      if (place.appendChild)
        place.appendChild(this.dom);
      else if (typeof place == "function")
        place(this.dom);
      else if (place.mount)
        this.mounted = true;
    }
    this.editable = getEditable(this);
    updateCursorWrapper(this);
    this.nodeViews = buildNodeViews(this);
    this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);
    this.domObserver = new DOMObserver(this, (from4, to2, typeOver, added) => readDOMChange(this, from4, to2, typeOver, added));
    this.domObserver.start();
    initInput(this);
    this.updatePluginViews();
  }
  /**
  Holds `true` when a
  [composition](https://w3c.github.io/uievents/#events-compositionevents)
  is active.
  */
  get composing() {
    return this.input.composing;
  }
  /**
  The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).
  */
  get props() {
    if (this._props.state != this.state) {
      let prev = this._props;
      this._props = {};
      for (let name in prev)
        this._props[name] = prev[name];
      this._props.state = this.state;
    }
    return this._props;
  }
  /**
  Update the view's props. Will immediately cause an update to
  the DOM.
  */
  update(props) {
    if (props.handleDOMEvents != this._props.handleDOMEvents)
      ensureListeners(this);
    let prevProps = this._props;
    this._props = props;
    if (props.plugins) {
      props.plugins.forEach(checkStateComponent);
      this.directPlugins = props.plugins;
    }
    this.updateStateInner(props.state, prevProps);
  }
  /**
  Update the view by updating existing props object with the object
  given as argument. Equivalent to `view.update(Object.assign({},
  view.props, props))`.
  */
  setProps(props) {
    let updated = {};
    for (let name in this._props)
      updated[name] = this._props[name];
    updated.state = this.state;
    for (let name in props)
      updated[name] = props[name];
    this.update(updated);
  }
  /**
  Update the editor's `state` prop, without touching any of the
  other props.
  */
  updateState(state) {
    this.updateStateInner(state, this._props);
  }
  updateStateInner(state, prevProps) {
    var _a2;
    let prev = this.state, redraw = false, updateSel = false;
    if (state.storedMarks && this.composing) {
      clearComposition(this);
      updateSel = true;
    }
    this.state = state;
    let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;
    if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {
      let nodeViews = buildNodeViews(this);
      if (changedNodeViews(nodeViews, this.nodeViews)) {
        this.nodeViews = nodeViews;
        redraw = true;
      }
    }
    if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {
      ensureListeners(this);
    }
    this.editable = getEditable(this);
    updateCursorWrapper(this);
    let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);
    let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve";
    let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);
    if (updateDoc || !state.selection.eq(prev.selection))
      updateSel = true;
    let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);
    if (updateSel) {
      this.domObserver.stop();
      let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);
      if (updateDoc) {
        let chromeKludge = chrome ? this.trackWrites = this.domSelectionRange().focusNode : null;
        if (this.composing)
          this.input.compositionNode = findCompositionNode(this);
        if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {
          this.docView.updateOuterDeco(outerDeco);
          this.docView.destroy();
          this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);
        }
        if (chromeKludge && !this.trackWrites)
          forceSelUpdate = true;
      }
      if (forceSelUpdate || !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this))) {
        selectionToDOM(this, forceSelUpdate);
      } else {
        syncNodeSelection(this, state.selection);
        this.domObserver.setCurSelection();
      }
      this.domObserver.start();
    }
    this.updatePluginViews(prev);
    if (((_a2 = this.dragging) === null || _a2 === void 0 ? void 0 : _a2.node) && !prev.doc.eq(state.doc))
      this.updateDraggedNode(this.dragging, prev);
    if (scroll == "reset") {
      this.dom.scrollTop = 0;
    } else if (scroll == "to selection") {
      this.scrollToSelection();
    } else if (oldScrollPos) {
      resetScrollPos(oldScrollPos);
    }
  }
  /**
  @internal
  */
  scrollToSelection() {
    let startDOM = this.domSelectionRange().focusNode;
    if (!startDOM || !this.dom.contains(startDOM.nodeType == 1 ? startDOM : startDOM.parentNode)) ;
    else if (this.someProp("handleScrollToSelection", (f6) => f6(this))) ;
    else if (this.state.selection instanceof NodeSelection) {
      let target = this.docView.domAfterPos(this.state.selection.from);
      if (target.nodeType == 1)
        scrollRectIntoView(this, target.getBoundingClientRect(), startDOM);
    } else {
      scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);
    }
  }
  destroyPluginViews() {
    let view;
    while (view = this.pluginViews.pop())
      if (view.destroy)
        view.destroy();
  }
  updatePluginViews(prevState) {
    if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {
      this.prevDirectPlugins = this.directPlugins;
      this.destroyPluginViews();
      for (let i3 = 0; i3 < this.directPlugins.length; i3++) {
        let plugin = this.directPlugins[i3];
        if (plugin.spec.view)
          this.pluginViews.push(plugin.spec.view(this));
      }
      for (let i3 = 0; i3 < this.state.plugins.length; i3++) {
        let plugin = this.state.plugins[i3];
        if (plugin.spec.view)
          this.pluginViews.push(plugin.spec.view(this));
      }
    } else {
      for (let i3 = 0; i3 < this.pluginViews.length; i3++) {
        let pluginView = this.pluginViews[i3];
        if (pluginView.update)
          pluginView.update(this, prevState);
      }
    }
  }
  updateDraggedNode(dragging, prev) {
    let sel = dragging.node, found2 = -1;
    if (this.state.doc.nodeAt(sel.from) == sel.node) {
      found2 = sel.from;
    } else {
      let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);
      let moved = movedPos > 0 && this.state.doc.nodeAt(movedPos);
      if (moved == sel.node)
        found2 = movedPos;
    }
    this.dragging = new Dragging(dragging.slice, dragging.move, found2 < 0 ? void 0 : NodeSelection.create(this.state.doc, found2));
  }
  someProp(propName, f6) {
    let prop = this._props && this._props[propName], value;
    if (prop != null && (value = f6 ? f6(prop) : prop))
      return value;
    for (let i3 = 0; i3 < this.directPlugins.length; i3++) {
      let prop2 = this.directPlugins[i3].props[propName];
      if (prop2 != null && (value = f6 ? f6(prop2) : prop2))
        return value;
    }
    let plugins = this.state.plugins;
    if (plugins)
      for (let i3 = 0; i3 < plugins.length; i3++) {
        let prop2 = plugins[i3].props[propName];
        if (prop2 != null && (value = f6 ? f6(prop2) : prop2))
          return value;
      }
  }
  /**
  Query whether the view has focus.
  */
  hasFocus() {
    if (ie) {
      let node2 = this.root.activeElement;
      if (node2 == this.dom)
        return true;
      if (!node2 || !this.dom.contains(node2))
        return false;
      while (node2 && this.dom != node2 && this.dom.contains(node2)) {
        if (node2.contentEditable == "false")
          return false;
        node2 = node2.parentElement;
      }
      return true;
    }
    return this.root.activeElement == this.dom;
  }
  /**
  Focus the editor.
  */
  focus() {
    this.domObserver.stop();
    if (this.editable)
      focusPreventScroll(this.dom);
    selectionToDOM(this);
    this.domObserver.start();
  }
  /**
  Get the document root in which the editor exists. This will
  usually be the top-level `document`, but might be a [shadow
  DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)
  root if the editor is inside one.
  */
  get root() {
    let cached = this._root;
    if (cached == null)
      for (let search3 = this.dom.parentNode; search3; search3 = search3.parentNode) {
        if (search3.nodeType == 9 || search3.nodeType == 11 && search3.host) {
          if (!search3.getSelection)
            Object.getPrototypeOf(search3).getSelection = () => search3.ownerDocument.getSelection();
          return this._root = search3;
        }
      }
    return cached || document;
  }
  /**
  When an existing editor view is moved to a new document or
  shadow tree, call this to make it recompute its root.
  */
  updateRoot() {
    this._root = null;
  }
  /**
  Given a pair of viewport coordinates, return the document
  position that corresponds to them. May return null if the given
  coordinates aren't inside of the editor. When an object is
  returned, its `pos` property is the position nearest to the
  coordinates, and its `inside` property holds the position of the
  inner node that the position falls inside of, or -1 if it is at
  the top level, not in any node.
  */
  posAtCoords(coords) {
    return posAtCoords(this, coords);
  }
  /**
  Returns the viewport rectangle at a given document position.
  `left` and `right` will be the same number, as this returns a
  flat cursor-ish rectangle. If the position is between two things
  that aren't directly adjacent, `side` determines which element
  is used. When < 0, the element before the position is used,
  otherwise the element after.
  */
  coordsAtPos(pos, side = 1) {
    return coordsAtPos(this, pos, side);
  }
  /**
  Find the DOM position that corresponds to the given document
  position. When `side` is negative, find the position as close as
  possible to the content before the position. When positive,
  prefer positions close to the content after the position. When
  zero, prefer as shallow a position as possible.
  
  Note that you should **not** mutate the editor's internal DOM,
  only inspect it (and even that is usually not necessary).
  */
  domAtPos(pos, side = 0) {
    return this.docView.domFromPos(pos, side);
  }
  /**
  Find the DOM node that represents the document node after the
  given position. May return `null` when the position doesn't point
  in front of a node or if the node is inside an opaque node view.
  
  This is intended to be able to call things like
  `getBoundingClientRect` on that DOM node. Do **not** mutate the
  editor DOM directly, or add styling this way, since that will be
  immediately overriden by the editor as it redraws the node.
  */
  nodeDOM(pos) {
    let desc = this.docView.descAt(pos);
    return desc ? desc.nodeDOM : null;
  }
  /**
  Find the document position that corresponds to a given DOM
  position. (Whenever possible, it is preferable to inspect the
  document structure directly, rather than poking around in the
  DOM, but sometimes—for example when interpreting an event
  target—you don't have a choice.)
  
  The `bias` parameter can be used to influence which side of a DOM
  node to use when the position is inside a leaf node.
  */
  posAtDOM(node2, offset4, bias = -1) {
    let pos = this.docView.posFromDOM(node2, offset4, bias);
    if (pos == null)
      throw new RangeError("DOM position not inside the editor");
    return pos;
  }
  /**
  Find out whether the selection is at the end of a textblock when
  moving in a given direction. When, for example, given `"left"`,
  it will return true if moving left from the current cursor
  position would leave that position's parent textblock. Will apply
  to the view's current state by default, but it is possible to
  pass a different state.
  */
  endOfTextblock(dir, state) {
    return endOfTextblock(this, state || this.state, dir);
  }
  /**
  Run the editor's paste logic with the given HTML string. The
  `event`, if given, will be passed to the
  [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.
  */
  pasteHTML(html7, event) {
    return doPaste(this, "", html7, false, event || new ClipboardEvent("paste"));
  }
  /**
  Run the editor's paste logic with the given plain-text input.
  */
  pasteText(text10, event) {
    return doPaste(this, text10, null, true, event || new ClipboardEvent("paste"));
  }
  /**
  Serialize the given slice as it would be if it was copied from
  this editor. Returns a DOM element that contains a
  representation of the slice as its children, a textual
  representation, and the transformed slice (which can be
  different from the given input due to hooks like
  [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)).
  */
  serializeForClipboard(slice2) {
    return serializeForClipboard(this, slice2);
  }
  /**
  Removes the editor from the DOM and destroys all [node
  views](https://prosemirror.net/docs/ref/#view.NodeView).
  */
  destroy() {
    if (!this.docView)
      return;
    destroyInput(this);
    this.destroyPluginViews();
    if (this.mounted) {
      this.docView.update(this.state.doc, [], viewDecorations(this), this);
      this.dom.textContent = "";
    } else if (this.dom.parentNode) {
      this.dom.parentNode.removeChild(this.dom);
    }
    this.docView.destroy();
    this.docView = null;
    clearReusedRange();
  }
  /**
  This is true when the view has been
  [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be
  used anymore).
  */
  get isDestroyed() {
    return this.docView == null;
  }
  /**
  Used for testing.
  */
  dispatchEvent(event) {
    return dispatchEvent(this, event);
  }
  /**
  @internal
  */
  domSelectionRange() {
    let sel = this.domSelection();
    if (!sel)
      return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };
    return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;
  }
  /**
  @internal
  */
  domSelection() {
    return this.root.getSelection();
  }
};
EditorView.prototype.dispatch = function(tr4) {
  let dispatchTransaction = this._props.dispatchTransaction;
  if (dispatchTransaction)
    dispatchTransaction.call(this, tr4);
  else
    this.updateState(this.state.apply(tr4));
};
function computeDocDeco(view) {
  let attrs = /* @__PURE__ */ Object.create(null);
  attrs.class = "ProseMirror";
  attrs.contenteditable = String(view.editable);
  view.someProp("attributes", (value) => {
    if (typeof value == "function")
      value = value(view.state);
    if (value)
      for (let attr2 in value) {
        if (attr2 == "class")
          attrs.class += " " + value[attr2];
        else if (attr2 == "style")
          attrs.style = (attrs.style ? attrs.style + ";" : "") + value[attr2];
        else if (!attrs[attr2] && attr2 != "contenteditable" && attr2 != "nodeName")
          attrs[attr2] = String(value[attr2]);
      }
  });
  if (!attrs.translate)
    attrs.translate = "no";
  return [Decoration.node(0, view.state.doc.content.size, attrs)];
}
function updateCursorWrapper(view) {
  if (view.markCursor) {
    let dom = document.createElement("img");
    dom.className = "ProseMirror-separator";
    dom.setAttribute("mark-placeholder", "true");
    dom.setAttribute("alt", "");
    view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };
  } else {
    view.cursorWrapper = null;
  }
}
function getEditable(view) {
  return !view.someProp("editable", (value) => value(view.state) === false);
}
function selectionContextChanged(sel1, sel2) {
  let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));
  return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);
}
function buildNodeViews(view) {
  let result = /* @__PURE__ */ Object.create(null);
  function add(obj) {
    for (let prop in obj)
      if (!Object.prototype.hasOwnProperty.call(result, prop))
        result[prop] = obj[prop];
  }
  view.someProp("nodeViews", add);
  view.someProp("markViews", add);
  return result;
}
function changedNodeViews(a3, b4) {
  let nA = 0, nB = 0;
  for (let prop in a3) {
    if (a3[prop] != b4[prop])
      return true;
    nA++;
  }
  for (let _2 in b4)
    nB++;
  return nA != nB;
}
function checkStateComponent(plugin) {
  if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)
    throw new RangeError("Plugins passed directly to the view must not have a state component");
}

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/map.js
var create = () => /* @__PURE__ */ new Map();
var copy2 = (m2) => {
  const r4 = create();
  m2.forEach((v8, k3) => {
    r4.set(k3, v8);
  });
  return r4;
};
var setIfUndefined = (map7, key2, createT) => {
  let set = map7.get(key2);
  if (set === void 0) {
    map7.set(key2, set = createT());
  }
  return set;
};
var map = (m2, f6) => {
  const res = [];
  for (const [key2, value] of m2) {
    res.push(f6(value, key2));
  }
  return res;
};
var any = (m2, f6) => {
  for (const [key2, value] of m2) {
    if (f6(value, key2)) {
      return true;
    }
  }
  return false;
};

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/set.js
var create2 = () => /* @__PURE__ */ new Set();

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/array.js
var last = (arr) => arr[arr.length - 1];
var appendTo = (dest, src) => {
  for (let i3 = 0; i3 < src.length; i3++) {
    dest.push(src[i3]);
  }
};
var from2 = Array.from;
var every = (arr, f6) => {
  for (let i3 = 0; i3 < arr.length; i3++) {
    if (!f6(arr[i3], i3, arr)) {
      return false;
    }
  }
  return true;
};
var some = (arr, f6) => {
  for (let i3 = 0; i3 < arr.length; i3++) {
    if (f6(arr[i3], i3, arr)) {
      return true;
    }
  }
  return false;
};
var unfold = (len, f6) => {
  const array = new Array(len);
  for (let i3 = 0; i3 < len; i3++) {
    array[i3] = f6(i3, array);
  }
  return array;
};
var isArray = Array.isArray;

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/observable.js
var ObservableV2 = class {
  constructor() {
    this._observers = create();
  }
  /**
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name
   * @param {EVENTS[NAME]} f
   */
  on(name, f6) {
    setIfUndefined(
      this._observers,
      /** @type {string} */
      name,
      create2
    ).add(f6);
    return f6;
  }
  /**
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name
   * @param {EVENTS[NAME]} f
   */
  once(name, f6) {
    const _f = (...args2) => {
      this.off(
        name,
        /** @type {any} */
        _f
      );
      f6(...args2);
    };
    this.on(
      name,
      /** @type {any} */
      _f
    );
  }
  /**
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name
   * @param {EVENTS[NAME]} f
   */
  off(name, f6) {
    const observers = this._observers.get(name);
    if (observers !== void 0) {
      observers.delete(f6);
      if (observers.size === 0) {
        this._observers.delete(name);
      }
    }
  }
  /**
   * Emit a named event. All registered event listeners that listen to the
   * specified name will receive the event.
   *
   * @todo This should catch exceptions
   *
   * @template {keyof EVENTS & string} NAME
   * @param {NAME} name The event name.
   * @param {Parameters<EVENTS[NAME]>} args The arguments that are applied to the event listener.
   */
  emit(name, args2) {
    return from2((this._observers.get(name) || create()).values()).forEach((f6) => f6(...args2));
  }
  destroy() {
    this._observers = create();
  }
};

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/math.js
var floor = Math.floor;
var abs = Math.abs;
var min = (a3, b4) => a3 < b4 ? a3 : b4;
var max = (a3, b4) => a3 > b4 ? a3 : b4;
var isNaN2 = Number.isNaN;
var isNegativeZero = (n) => n !== 0 ? n < 0 : 1 / n < 0;

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/binary.js
var BIT1 = 1;
var BIT2 = 2;
var BIT3 = 4;
var BIT4 = 8;
var BIT6 = 32;
var BIT7 = 64;
var BIT8 = 128;
var BIT18 = 1 << 17;
var BIT19 = 1 << 18;
var BIT20 = 1 << 19;
var BIT21 = 1 << 20;
var BIT22 = 1 << 21;
var BIT23 = 1 << 22;
var BIT24 = 1 << 23;
var BIT25 = 1 << 24;
var BIT26 = 1 << 25;
var BIT27 = 1 << 26;
var BIT28 = 1 << 27;
var BIT29 = 1 << 28;
var BIT30 = 1 << 29;
var BIT31 = 1 << 30;
var BIT32 = 1 << 31;
var BITS5 = 31;
var BITS6 = 63;
var BITS7 = 127;
var BITS17 = BIT18 - 1;
var BITS18 = BIT19 - 1;
var BITS19 = BIT20 - 1;
var BITS20 = BIT21 - 1;
var BITS21 = BIT22 - 1;
var BITS22 = BIT23 - 1;
var BITS23 = BIT24 - 1;
var BITS24 = BIT25 - 1;
var BITS25 = BIT26 - 1;
var BITS26 = BIT27 - 1;
var BITS27 = BIT28 - 1;
var BITS28 = BIT29 - 1;
var BITS29 = BIT30 - 1;
var BITS30 = BIT31 - 1;
var BITS31 = 2147483647;

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/number.js
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER;
var LOWEST_INT32 = 1 << 31;
var isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num);
var isNaN3 = Number.isNaN;
var parseInt2 = Number.parseInt;

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/string.js
var fromCharCode = String.fromCharCode;
var fromCodePoint = String.fromCodePoint;
var MAX_UTF16_CHARACTER = fromCharCode(65535);
var toLowerCase = (s2) => s2.toLowerCase();
var trimLeftRegex = /^\s*/g;
var trimLeft = (s2) => s2.replace(trimLeftRegex, "");
var fromCamelCaseRegex = /([A-Z])/g;
var fromCamelCase = (s2, separator) => trimLeft(s2.replace(fromCamelCaseRegex, (match2) => `${separator}${toLowerCase(match2)}`));
var _encodeUtf8Polyfill = (str) => {
  const encodedString = unescape(encodeURIComponent(str));
  const len = encodedString.length;
  const buf = new Uint8Array(len);
  for (let i3 = 0; i3 < len; i3++) {
    buf[i3] = /** @type {number} */
    encodedString.codePointAt(i3);
  }
  return buf;
};
var utf8TextEncoder = (
  /** @type {TextEncoder} */
  typeof TextEncoder !== "undefined" ? new TextEncoder() : null
);
var _encodeUtf8Native = (str) => utf8TextEncoder.encode(str);
var encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill;
var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {
  utf8TextDecoder = null;
}
var repeat = (source, n) => unfold(n, () => source).join("");

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/encoding.js
var Encoder = class {
  constructor() {
    this.cpos = 0;
    this.cbuf = new Uint8Array(100);
    this.bufs = [];
  }
};
var createEncoder = () => new Encoder();
var encode = (f6) => {
  const encoder = createEncoder();
  f6(encoder);
  return toUint8Array(encoder);
};
var length = (encoder) => {
  let len = encoder.cpos;
  for (let i3 = 0; i3 < encoder.bufs.length; i3++) {
    len += encoder.bufs[i3].length;
  }
  return len;
};
var toUint8Array = (encoder) => {
  const uint8arr = new Uint8Array(length(encoder));
  let curPos = 0;
  for (let i3 = 0; i3 < encoder.bufs.length; i3++) {
    const d = encoder.bufs[i3];
    uint8arr.set(d, curPos);
    curPos += d.length;
  }
  uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos);
  return uint8arr;
};
var verifyLen = (encoder, len) => {
  const bufferLen = encoder.cbuf.length;
  if (bufferLen - encoder.cpos < len) {
    encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos));
    encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2);
    encoder.cpos = 0;
  }
};
var write = (encoder, num) => {
  const bufferLen = encoder.cbuf.length;
  if (encoder.cpos === bufferLen) {
    encoder.bufs.push(encoder.cbuf);
    encoder.cbuf = new Uint8Array(bufferLen * 2);
    encoder.cpos = 0;
  }
  encoder.cbuf[encoder.cpos++] = num;
};
var writeUint8 = write;
var writeVarUint = (encoder, num) => {
  while (num > BITS7) {
    write(encoder, BIT8 | BITS7 & num);
    num = floor(num / 128);
  }
  write(encoder, BITS7 & num);
};
var writeVarInt = (encoder, num) => {
  const isNegative = isNegativeZero(num);
  if (isNegative) {
    num = -num;
  }
  write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num);
  num = floor(num / 64);
  while (num > 0) {
    write(encoder, (num > BITS7 ? BIT8 : 0) | BITS7 & num);
    num = floor(num / 128);
  }
};
var _strBuffer = new Uint8Array(3e4);
var _maxStrBSize = _strBuffer.length / 3;
var _writeVarStringNative = (encoder, str) => {
  if (str.length < _maxStrBSize) {
    const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
    writeVarUint(encoder, written);
    for (let i3 = 0; i3 < written; i3++) {
      write(encoder, _strBuffer[i3]);
    }
  } else {
    writeVarUint8Array(encoder, encodeUtf8(str));
  }
};
var _writeVarStringPolyfill = (encoder, str) => {
  const encodedString = unescape(encodeURIComponent(str));
  const len = encodedString.length;
  writeVarUint(encoder, len);
  for (let i3 = 0; i3 < len; i3++) {
    write(
      encoder,
      /** @type {number} */
      encodedString.codePointAt(i3)
    );
  }
};
var writeVarString = utf8TextEncoder && /** @type {any} */
utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill;
var writeUint8Array = (encoder, uint8Array) => {
  const bufferLen = encoder.cbuf.length;
  const cpos = encoder.cpos;
  const leftCopyLen = min(bufferLen - cpos, uint8Array.length);
  const rightCopyLen = uint8Array.length - leftCopyLen;
  encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
  encoder.cpos += leftCopyLen;
  if (rightCopyLen > 0) {
    encoder.bufs.push(encoder.cbuf);
    encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen));
    encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
    encoder.cpos = rightCopyLen;
  }
};
var writeVarUint8Array = (encoder, uint8Array) => {
  writeVarUint(encoder, uint8Array.byteLength);
  writeUint8Array(encoder, uint8Array);
};
var writeOnDataView = (encoder, len) => {
  verifyLen(encoder, len);
  const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len);
  encoder.cpos += len;
  return dview;
};
var writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false);
var writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false);
var writeBigInt64 = (encoder, num) => (
  /** @type {any} */
  writeOnDataView(encoder, 8).setBigInt64(0, num, false)
);
var floatTestBed = new DataView(new ArrayBuffer(4));
var isFloat32 = (num) => {
  floatTestBed.setFloat32(0, num);
  return floatTestBed.getFloat32(0) === num;
};
var writeAny = (encoder, data) => {
  switch (typeof data) {
    case "string":
      write(encoder, 119);
      writeVarString(encoder, data);
      break;
    case "number":
      if (isInteger(data) && abs(data) <= BITS31) {
        write(encoder, 125);
        writeVarInt(encoder, data);
      } else if (isFloat32(data)) {
        write(encoder, 124);
        writeFloat32(encoder, data);
      } else {
        write(encoder, 123);
        writeFloat64(encoder, data);
      }
      break;
    case "bigint":
      write(encoder, 122);
      writeBigInt64(encoder, data);
      break;
    case "object":
      if (data === null) {
        write(encoder, 126);
      } else if (isArray(data)) {
        write(encoder, 117);
        writeVarUint(encoder, data.length);
        for (let i3 = 0; i3 < data.length; i3++) {
          writeAny(encoder, data[i3]);
        }
      } else if (data instanceof Uint8Array) {
        write(encoder, 116);
        writeVarUint8Array(encoder, data);
      } else {
        write(encoder, 118);
        const keys5 = Object.keys(data);
        writeVarUint(encoder, keys5.length);
        for (let i3 = 0; i3 < keys5.length; i3++) {
          const key2 = keys5[i3];
          writeVarString(encoder, key2);
          writeAny(encoder, data[key2]);
        }
      }
      break;
    case "boolean":
      write(encoder, data ? 120 : 121);
      break;
    default:
      write(encoder, 127);
  }
};
var RleEncoder = class extends Encoder {
  /**
   * @param {function(Encoder, T):void} writer
   */
  constructor(writer) {
    super();
    this.w = writer;
    this.s = null;
    this.count = 0;
  }
  /**
   * @param {T} v
   */
  write(v8) {
    if (this.s === v8) {
      this.count++;
    } else {
      if (this.count > 0) {
        writeVarUint(this, this.count - 1);
      }
      this.count = 1;
      this.w(this, v8);
      this.s = v8;
    }
  }
};
var flushUintOptRleEncoder = (encoder) => {
  if (encoder.count > 0) {
    writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s);
    if (encoder.count > 1) {
      writeVarUint(encoder.encoder, encoder.count - 2);
    }
  }
};
var UintOptRleEncoder = class {
  constructor() {
    this.encoder = new Encoder();
    this.s = 0;
    this.count = 0;
  }
  /**
   * @param {number} v
   */
  write(v8) {
    if (this.s === v8) {
      this.count++;
    } else {
      flushUintOptRleEncoder(this);
      this.count = 1;
      this.s = v8;
    }
  }
  /**
   * Flush the encoded state and transform this to a Uint8Array.
   *
   * Note that this should only be called once.
   */
  toUint8Array() {
    flushUintOptRleEncoder(this);
    return toUint8Array(this.encoder);
  }
};
var flushIntDiffOptRleEncoder = (encoder) => {
  if (encoder.count > 0) {
    const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1);
    writeVarInt(encoder.encoder, encodedDiff);
    if (encoder.count > 1) {
      writeVarUint(encoder.encoder, encoder.count - 2);
    }
  }
};
var IntDiffOptRleEncoder = class {
  constructor() {
    this.encoder = new Encoder();
    this.s = 0;
    this.count = 0;
    this.diff = 0;
  }
  /**
   * @param {number} v
   */
  write(v8) {
    if (this.diff === v8 - this.s) {
      this.s = v8;
      this.count++;
    } else {
      flushIntDiffOptRleEncoder(this);
      this.count = 1;
      this.diff = v8 - this.s;
      this.s = v8;
    }
  }
  /**
   * Flush the encoded state and transform this to a Uint8Array.
   *
   * Note that this should only be called once.
   */
  toUint8Array() {
    flushIntDiffOptRleEncoder(this);
    return toUint8Array(this.encoder);
  }
};
var StringEncoder = class {
  constructor() {
    this.sarr = [];
    this.s = "";
    this.lensE = new UintOptRleEncoder();
  }
  /**
   * @param {string} string
   */
  write(string3) {
    this.s += string3;
    if (this.s.length > 19) {
      this.sarr.push(this.s);
      this.s = "";
    }
    this.lensE.write(string3.length);
  }
  toUint8Array() {
    const encoder = new Encoder();
    this.sarr.push(this.s);
    this.s = "";
    writeVarString(encoder, this.sarr.join(""));
    writeUint8Array(encoder, this.lensE.toUint8Array());
    return toUint8Array(encoder);
  }
};

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/error.js
var create3 = (s2) => new Error(s2);
var methodUnimplemented = () => {
  throw create3("Method unimplemented");
};
var unexpectedCase = () => {
  throw create3("Unexpected case");
};

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/decoding.js
var errorUnexpectedEndOfArray = create3("Unexpected end of array");
var errorIntegerOutOfRange = create3("Integer out of Range");
var Decoder = class {
  /**
   * @param {Uint8Array<Buf>} uint8Array Binary data to decode
   */
  constructor(uint8Array) {
    this.arr = uint8Array;
    this.pos = 0;
  }
};
var createDecoder = (uint8Array) => new Decoder(uint8Array);
var hasContent = (decoder) => decoder.pos !== decoder.arr.length;
var readUint8Array = (decoder, len) => {
  const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
  decoder.pos += len;
  return view;
};
var readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder));
var readUint8 = (decoder) => decoder.arr[decoder.pos++];
var readVarUint = (decoder) => {
  let num = 0;
  let mult = 1;
  const len = decoder.arr.length;
  while (decoder.pos < len) {
    const r4 = decoder.arr[decoder.pos++];
    num = num + (r4 & BITS7) * mult;
    mult *= 128;
    if (r4 < BIT8) {
      return num;
    }
    if (num > MAX_SAFE_INTEGER) {
      throw errorIntegerOutOfRange;
    }
  }
  throw errorUnexpectedEndOfArray;
};
var readVarInt = (decoder) => {
  let r4 = decoder.arr[decoder.pos++];
  let num = r4 & BITS6;
  let mult = 64;
  const sign = (r4 & BIT7) > 0 ? -1 : 1;
  if ((r4 & BIT8) === 0) {
    return sign * num;
  }
  const len = decoder.arr.length;
  while (decoder.pos < len) {
    r4 = decoder.arr[decoder.pos++];
    num = num + (r4 & BITS7) * mult;
    mult *= 128;
    if (r4 < BIT8) {
      return sign * num;
    }
    if (num > MAX_SAFE_INTEGER) {
      throw errorIntegerOutOfRange;
    }
  }
  throw errorUnexpectedEndOfArray;
};
var _readVarStringPolyfill = (decoder) => {
  let remainingLen = readVarUint(decoder);
  if (remainingLen === 0) {
    return "";
  } else {
    let encodedString = String.fromCodePoint(readUint8(decoder));
    if (--remainingLen < 100) {
      while (remainingLen--) {
        encodedString += String.fromCodePoint(readUint8(decoder));
      }
    } else {
      while (remainingLen > 0) {
        const nextLen = remainingLen < 1e4 ? remainingLen : 1e4;
        const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
        decoder.pos += nextLen;
        encodedString += String.fromCodePoint.apply(
          null,
          /** @type {any} */
          bytes
        );
        remainingLen -= nextLen;
      }
    }
    return decodeURIComponent(escape(encodedString));
  }
};
var _readVarStringNative = (decoder) => (
  /** @type any */
  utf8TextDecoder.decode(readVarUint8Array(decoder))
);
var readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill;
var readFromDataView = (decoder, len) => {
  const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len);
  decoder.pos += len;
  return dv;
};
var readFloat32 = (decoder) => readFromDataView(decoder, 4).getFloat32(0, false);
var readFloat64 = (decoder) => readFromDataView(decoder, 8).getFloat64(0, false);
var readBigInt64 = (decoder) => (
  /** @type {any} */
  readFromDataView(decoder, 8).getBigInt64(0, false)
);
var readAnyLookupTable = [
  (decoder) => void 0,
  // CASE 127: undefined
  (decoder) => null,
  // CASE 126: null
  readVarInt,
  // CASE 125: integer
  readFloat32,
  // CASE 124: float32
  readFloat64,
  // CASE 123: float64
  readBigInt64,
  // CASE 122: bigint
  (decoder) => false,
  // CASE 121: boolean (false)
  (decoder) => true,
  // CASE 120: boolean (true)
  readVarString,
  // CASE 119: string
  (decoder) => {
    const len = readVarUint(decoder);
    const obj = {};
    for (let i3 = 0; i3 < len; i3++) {
      const key2 = readVarString(decoder);
      obj[key2] = readAny(decoder);
    }
    return obj;
  },
  (decoder) => {
    const len = readVarUint(decoder);
    const arr = [];
    for (let i3 = 0; i3 < len; i3++) {
      arr.push(readAny(decoder));
    }
    return arr;
  },
  readVarUint8Array
  // CASE 116: Uint8Array
];
var readAny = (decoder) => readAnyLookupTable[127 - readUint8(decoder)](decoder);
var RleDecoder = class extends Decoder {
  /**
   * @param {Uint8Array} uint8Array
   * @param {function(Decoder):T} reader
   */
  constructor(uint8Array, reader) {
    super(uint8Array);
    this.reader = reader;
    this.s = null;
    this.count = 0;
  }
  read() {
    if (this.count === 0) {
      this.s = this.reader(this);
      if (hasContent(this)) {
        this.count = readVarUint(this) + 1;
      } else {
        this.count = -1;
      }
    }
    this.count--;
    return (
      /** @type {T} */
      this.s
    );
  }
};
var UintOptRleDecoder = class extends Decoder {
  /**
   * @param {Uint8Array} uint8Array
   */
  constructor(uint8Array) {
    super(uint8Array);
    this.s = 0;
    this.count = 0;
  }
  read() {
    if (this.count === 0) {
      this.s = readVarInt(this);
      const isNegative = isNegativeZero(this.s);
      this.count = 1;
      if (isNegative) {
        this.s = -this.s;
        this.count = readVarUint(this) + 2;
      }
    }
    this.count--;
    return (
      /** @type {number} */
      this.s
    );
  }
};
var IntDiffOptRleDecoder = class extends Decoder {
  /**
   * @param {Uint8Array} uint8Array
   */
  constructor(uint8Array) {
    super(uint8Array);
    this.s = 0;
    this.count = 0;
    this.diff = 0;
  }
  /**
   * @return {number}
   */
  read() {
    if (this.count === 0) {
      const diff = readVarInt(this);
      const hasCount = diff & 1;
      this.diff = floor(diff / 2);
      this.count = 1;
      if (hasCount) {
        this.count = readVarUint(this) + 2;
      }
    }
    this.s += this.diff;
    this.count--;
    return this.s;
  }
};
var StringDecoder = class {
  /**
   * @param {Uint8Array} uint8Array
   */
  constructor(uint8Array) {
    this.decoder = new UintOptRleDecoder(uint8Array);
    this.str = readVarString(this.decoder);
    this.spos = 0;
  }
  /**
   * @return {string}
   */
  read() {
    const end = this.spos + this.decoder.read();
    const res = this.str.slice(this.spos, end);
    this.spos = end;
    return res;
  }
};

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/webcrypto.js
var subtle = crypto.subtle;
var getRandomValues = crypto.getRandomValues.bind(crypto);

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/random.js
var rand = Math.random;
var uint32 = () => getRandomValues(new Uint32Array(1))[0];
var oneOf = (arr) => arr[floor(rand() * arr.length)];
var uuidv4Template = "10000000-1000-4000-8000" + -1e11;
var uuidv4 = () => uuidv4Template.replace(
  /[018]/g,
  /** @param {number} c */
  (c3) => (c3 ^ uint32() & 15 >> c3 / 4).toString(16)
);

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/time.js
var getUnixTime = Date.now;

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/promise.js
var create4 = (f6) => (
  /** @type {Promise<T>} */
  new Promise(f6)
);
var all = Promise.all.bind(Promise);

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/conditions.js
var undefinedToNull = (v8) => v8 === void 0 ? null : v8;

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/storage.js
var VarStoragePolyfill = class {
  constructor() {
    this.map = /* @__PURE__ */ new Map();
  }
  /**
   * @param {string} key
   * @param {any} newValue
   */
  setItem(key2, newValue) {
    this.map.set(key2, newValue);
  }
  /**
   * @param {string} key
   */
  getItem(key2) {
    return this.map.get(key2);
  }
};
var _localStorage = new VarStoragePolyfill();
var usePolyfill = true;
try {
  if (typeof localStorage !== "undefined" && localStorage) {
    _localStorage = localStorage;
    usePolyfill = false;
  }
} catch (e2) {
}
var varStorage = _localStorage;

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/trait/equality.js
var EqualityTraitSymbol = Symbol("Equality");
var equals = (a3, b4) => {
  var _a2;
  return a3 === b4 || !!((_a2 = a3 == null ? void 0 : a3[EqualityTraitSymbol]) == null ? void 0 : _a2.call(a3, b4)) || false;
};

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/object.js
var isObject = (o2) => typeof o2 === "object";
var assign = Object.assign;
var keys2 = Object.keys;
var forEach = (obj, f6) => {
  for (const key2 in obj) {
    f6(obj[key2], key2);
  }
};
var size = (obj) => keys2(obj).length;
var isEmpty = (obj) => {
  for (const _k in obj) {
    return false;
  }
  return true;
};
var every2 = (obj, f6) => {
  for (const key2 in obj) {
    if (!f6(obj[key2], key2)) {
      return false;
    }
  }
  return true;
};
var hasProperty = (obj, key2) => Object.prototype.hasOwnProperty.call(obj, key2);
var equalFlat = (a3, b4) => a3 === b4 || size(a3) === size(b4) && every2(a3, (val, key2) => (val !== void 0 || hasProperty(b4, key2)) && equals(b4[key2], val));
var freeze = Object.freeze;
var deepFreeze = (o2) => {
  for (const key2 in o2) {
    const c3 = o2[key2];
    if (typeof c3 === "object" || typeof c3 === "function") {
      deepFreeze(o2[key2]);
    }
  }
  return freeze(o2);
};

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/function.js
var callAll = (fs, args2, i3 = 0) => {
  try {
    for (; i3 < fs.length; i3++) {
      fs[i3](...args2);
    }
  } finally {
    if (i3 < fs.length) {
      callAll(fs, args2, i3 + 1);
    }
  }
};
var id = (a3) => a3;
var equalityDeep = (a3, b4) => {
  if (a3 === b4) {
    return true;
  }
  if (a3 == null || b4 == null || a3.constructor !== b4.constructor && (a3.constructor || Object) !== (b4.constructor || Object)) {
    return false;
  }
  if (a3[EqualityTraitSymbol] != null) {
    return a3[EqualityTraitSymbol](b4);
  }
  switch (a3.constructor) {
    case ArrayBuffer:
      a3 = new Uint8Array(a3);
      b4 = new Uint8Array(b4);
    // eslint-disable-next-line no-fallthrough
    case Uint8Array: {
      if (a3.byteLength !== b4.byteLength) {
        return false;
      }
      for (let i3 = 0; i3 < a3.length; i3++) {
        if (a3[i3] !== b4[i3]) {
          return false;
        }
      }
      break;
    }
    case Set: {
      if (a3.size !== b4.size) {
        return false;
      }
      for (const value of a3) {
        if (!b4.has(value)) {
          return false;
        }
      }
      break;
    }
    case Map: {
      if (a3.size !== b4.size) {
        return false;
      }
      for (const key2 of a3.keys()) {
        if (!b4.has(key2) || !equalityDeep(a3.get(key2), b4.get(key2))) {
          return false;
        }
      }
      break;
    }
    case void 0:
    case Object:
      if (size(a3) !== size(b4)) {
        return false;
      }
      for (const key2 in a3) {
        if (!hasProperty(a3, key2) || !equalityDeep(a3[key2], b4[key2])) {
          return false;
        }
      }
      break;
    case Array:
      if (a3.length !== b4.length) {
        return false;
      }
      for (let i3 = 0; i3 < a3.length; i3++) {
        if (!equalityDeep(a3[i3], b4[i3])) {
          return false;
        }
      }
      break;
    default:
      return false;
  }
  return true;
};
var isOneOf = (value, options2) => options2.includes(value);

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/environment.js
var isNode = typeof process !== "undefined" && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
var isBrowser = typeof window !== "undefined" && typeof document !== "undefined" && !isNode;
var isMac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
var params;
var args = [];
var computeParams = () => {
  if (params === void 0) {
    if (isNode) {
      params = create();
      const pargs = process.argv;
      let currParamName = null;
      for (let i3 = 0; i3 < pargs.length; i3++) {
        const parg = pargs[i3];
        if (parg[0] === "-") {
          if (currParamName !== null) {
            params.set(currParamName, "");
          }
          currParamName = parg;
        } else {
          if (currParamName !== null) {
            params.set(currParamName, parg);
            currParamName = null;
          } else {
            args.push(parg);
          }
        }
      }
      if (currParamName !== null) {
        params.set(currParamName, "");
      }
    } else if (typeof location === "object") {
      params = create();
      (location.search || "?").slice(1).split("&").forEach((kv) => {
        if (kv.length !== 0) {
          const [key2, value] = kv.split("=");
          params.set(`--${fromCamelCase(key2, "-")}`, value);
          params.set(`-${fromCamelCase(key2, "-")}`, value);
        }
      });
    } else {
      params = create();
    }
  }
  return params;
};
var hasParam = (name) => computeParams().has(name);
var getVariable = (name) => isNode ? undefinedToNull(process.env[name.toUpperCase().replaceAll("-", "_")]) : undefinedToNull(varStorage.getItem(name));
var hasConf = (name) => hasParam("--" + name) || getVariable(name) !== null;
var production = hasConf("production");
var forceColor = isNode && isOneOf(process.env.FORCE_COLOR, ["true", "1", "2"]);
var supportsColor = forceColor || !hasParam("--no-colors") && // @todo deprecate --no-colors
!hasConf("no-color") && (!isNode || process.stdout.isTTY) && (!isNode || hasParam("--color") || getVariable("COLORTERM") !== null || (getVariable("TERM") || "").includes("color"));

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/buffer.js
var createUint8ArrayFromLen = (len) => new Uint8Array(len);
var toBase64Browser = (bytes) => {
  let s2 = "";
  for (let i3 = 0; i3 < bytes.byteLength; i3++) {
    s2 += fromCharCode(bytes[i3]);
  }
  return btoa(s2);
};
var toBase64Node = (bytes) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
var toBase64 = isBrowser ? toBase64Browser : toBase64Node;
var copyUint8Array = (uint8Array) => {
  const newBuf = createUint8ArrayFromLen(uint8Array.byteLength);
  newBuf.set(uint8Array);
  return newBuf;
};
var encodeAny = (data) => encode((encoder) => writeAny(encoder, data));

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/pair.js
var Pair = class {
  /**
   * @param {L} left
   * @param {R} right
   */
  constructor(left, right) {
    this.left = left;
    this.right = right;
  }
};
var create5 = (left, right) => new Pair(left, right);

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/prng.js
var bool = (gen) => gen.next() >= 0.5;
var int53 = (gen, min3, max3) => floor(gen.next() * (max3 + 1 - min3) + min3);
var int32 = (gen, min3, max3) => floor(gen.next() * (max3 + 1 - min3) + min3);
var int31 = (gen, min3, max3) => int32(gen, min3, max3);
var letter = (gen) => fromCharCode(int31(gen, 97, 122));
var word = (gen, minLen = 0, maxLen = 20) => {
  const len = int31(gen, minLen, maxLen);
  let str = "";
  for (let i3 = 0; i3 < len; i3++) {
    str += letter(gen);
  }
  return str;
};
var oneOf2 = (gen, array) => array[int31(gen, 0, array.length - 1)];

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/schema.js
var schemaSymbol = Symbol("0schema");
var ValidationError = class {
  constructor() {
    this._rerrs = [];
  }
  /**
   * @param {string?} path
   * @param {string} expected
   * @param {string} has
   * @param {string?} message
   */
  extend(path2, expected, has, message = null) {
    this._rerrs.push({ path: path2, expected, has, message });
  }
  toString() {
    const s2 = [];
    for (let i3 = this._rerrs.length - 1; i3 > 0; i3--) {
      const r4 = this._rerrs[i3];
      s2.push(repeat(" ", (this._rerrs.length - i3) * 2) + `${r4.path != null ? `[${r4.path}] ` : ""}${r4.has} doesn't match ${r4.expected}. ${r4.message}`);
    }
    return s2.join("\n");
  }
};
var shapeExtends = (a3, b4) => {
  if (a3 === b4) return true;
  if (a3 == null || b4 == null || a3.constructor !== b4.constructor) return false;
  if (a3[EqualityTraitSymbol]) return equals(a3, b4);
  if (isArray(a3)) {
    return every(
      a3,
      (aitem) => some(b4, (bitem) => shapeExtends(aitem, bitem))
    );
  } else if (isObject(a3)) {
    return every2(
      a3,
      (aitem, akey) => shapeExtends(aitem, b4[akey])
    );
  }
  return false;
};
var Schema2 = class {
  /**
   * @param {Schema<any>} other
   */
  extends(other) {
    let [a3, b4] = [
      /** @type {any} */
      this.shape,
      /** @type {any} */
      other.shape
    ];
    if (
      /** @type {typeof Schema<any>} */
      this.constructor._dilutes
    ) [b4, a3] = [a3, b4];
    return shapeExtends(a3, b4);
  }
  /**
   * Overwrite this when necessary. By default, we only check the `shape` property which every shape
   * should have.
   * @param {Schema<any>} other
   */
  equals(other) {
    return this.constructor === other.constructor && equalityDeep(this.shape, other.shape);
  }
  [schemaSymbol]() {
    return true;
  }
  /**
   * @param {object} other
   */
  [EqualityTraitSymbol](other) {
    return this.equals(
      /** @type {any} */
      other
    );
  }
  /**
   * Use `schema.validate(obj)` with a typed parameter that is already of typed to be an instance of
   * Schema. Validate will check the structure of the parameter and return true iff the instance
   * really is an instance of Schema.
   *
   * @param {T} o
   * @return {boolean}
   */
  validate(o2) {
    return this.check(o2);
  }
  /* c8 ignore start */
  /**
   * Similar to validate, but this method accepts untyped parameters.
   *
   * @param {any} _o
   * @param {ValidationError} [_err]
   * @return {_o is T}
   */
  check(_o3, _err) {
    methodUnimplemented();
  }
  /* c8 ignore stop */
  /**
   * @type {Schema<T?>}
   */
  get nullable() {
    return $union(this, $null);
  }
  /**
   * @type {$Optional<Schema<T>>}
   */
  get optional() {
    return new $Optional(
      /** @type {Schema<T>} */
      this
    );
  }
  /**
   * Cast a variable to a specific type. Returns the casted value, or throws an exception otherwise.
   * Use this if you know that the type is of a specific type and you just want to convince the type
   * system.
   *
   * **Do not rely on these error messages!**
   * Performs an assertion check only if not in a production environment.
   *
   * @template OO
   * @param {OO} o
   * @return {Extract<OO, T> extends never ? T : (OO extends Array<never> ? T : Extract<OO,T>)}
   */
  cast(o2) {
    assert(o2, this);
    return (
      /** @type {any} */
      o2
    );
  }
  /**
   * EXPECTO PATRONUM!! 🪄
   * This function protects against type errors. Though it may not work in the real world.
   *
   * "After all this time?"
   * "Always." - Snape, talking about type safety
   *
   * Ensures that a variable is a a specific type. Returns the value, or throws an exception if the assertion check failed.
   * Use this if you know that the type is of a specific type and you just want to convince the type
   * system.
   *
   * Can be useful when defining lambdas: `s.lambda(s.$number, s.$void).expect((n) => n + 1)`
   *
   * **Do not rely on these error messages!**
   * Performs an assertion check if not in a production environment.
   *
   * @param {T} o
   * @return {o extends T ? T : never}
   */
  expect(o2) {
    assert(o2, this);
    return o2;
  }
};
// this.shape must not be defined on Schema. Otherwise typecheck on metatypes (e.g. $$object) won't work as expected anymore
/**
 * If true, the more things are added to the shape the more objects this schema will accept (e.g.
 * union). By default, the more objects are added, the the fewer objects this schema will accept.
 * @protected
 */
__publicField(Schema2, "_dilutes", false);
var $ConstructedBy = class extends Schema2 {
  /**
   * @param {C} c
   * @param {((o:Instance<C>)=>boolean)|null} check
   */
  constructor(c3, check) {
    super();
    this.shape = c3;
    this._c = check;
  }
  /**
   * @param {any} o
   * @param {ValidationError} [err]
   * @return {o is C extends ((...args:any[]) => infer T) ? T : (C extends (new (...args:any[]) => any) ? InstanceType<C> : never)} o
   */
  check(o2, err = void 0) {
    const c3 = (o2 == null ? void 0 : o2.constructor) === this.shape && (this._c == null || this._c(o2));
    !c3 && (err == null ? void 0 : err.extend(null, this.shape.name, o2 == null ? void 0 : o2.constructor.name, (o2 == null ? void 0 : o2.constructor) !== this.shape ? "Constructor match failed" : "Check failed"));
    return c3;
  }
};
var $constructedBy = (c3, check = null) => new $ConstructedBy(c3, check);
var $$constructedBy = $constructedBy($ConstructedBy);
var $Custom = class extends Schema2 {
  /**
   * @param {(o:any) => boolean} check
   */
  constructor(check) {
    super();
    this.shape = check;
  }
  /**
   * @param {any} o
   * @param {ValidationError} err
   * @return {o is any}
   */
  check(o2, err) {
    const c3 = this.shape(o2);
    !c3 && (err == null ? void 0 : err.extend(null, "custom prop", o2 == null ? void 0 : o2.constructor.name, "failed to check custom prop"));
    return c3;
  }
};
var $custom = (check) => new $Custom(check);
var $$custom = $constructedBy($Custom);
var $Literal = class extends Schema2 {
  /**
   * @param {Array<T>} literals
   */
  constructor(literals) {
    super();
    this.shape = literals;
  }
  /**
   *
   * @param {any} o
   * @param {ValidationError} [err]
   * @return {o is T}
   */
  check(o2, err) {
    const c3 = this.shape.some((a3) => a3 === o2);
    !c3 && (err == null ? void 0 : err.extend(null, this.shape.join(" | "), o2.toString()));
    return c3;
  }
};
var $literal = (...literals) => new $Literal(literals);
var $$literal = $constructedBy($Literal);
var _regexEscape = (
  /** @type {any} */
  RegExp.escape || /** @type {(str:string) => string} */
  ((str) => str.replace(/[().|&,$^[\]]/g, (s2) => "\\" + s2))
);
var _schemaStringTemplateToRegex = (s2) => {
  if ($string.check(s2)) {
    return [_regexEscape(s2)];
  }
  if ($$literal.check(s2)) {
    return (
      /** @type {Array<string|number>} */
      s2.shape.map((v8) => v8 + "")
    );
  }
  if ($$number.check(s2)) {
    return ["[+-]?\\d+.?\\d*"];
  }
  if ($$string.check(s2)) {
    return [".*"];
  }
  if ($$union.check(s2)) {
    return s2.shape.map(_schemaStringTemplateToRegex).flat(1);
  }
  unexpectedCase();
};
var $StringTemplate = class extends Schema2 {
  /**
   * @param {T} shape
   */
  constructor(shape) {
    super();
    this.shape = shape;
    this._r = new RegExp("^" + shape.map(_schemaStringTemplateToRegex).map((opts) => `(${opts.join("|")})`).join("") + "$");
  }
  /**
   * @param {any} o
   * @param {ValidationError} [err]
   * @return {o is CastStringTemplateArgsToTemplate<T>}
   */
  check(o2, err) {
    const c3 = this._r.exec(o2) != null;
    !c3 && (err == null ? void 0 : err.extend(null, this._r.toString(), o2.toString(), "String doesn't match string template."));
    return c3;
  }
};
var $$stringTemplate = $constructedBy($StringTemplate);
var isOptionalSymbol = Symbol("optional");
var $Optional = class extends Schema2 {
  /**
   * @param {S} shape
   */
  constructor(shape) {
    super();
    this.shape = shape;
  }
  /**
   * @param {any} o
   * @param {ValidationError} [err]
   * @return {o is (Unwrap<S>|undefined)}
   */
  check(o2, err) {
    const c3 = o2 === void 0 || this.shape.check(o2);
    !c3 && (err == null ? void 0 : err.extend(null, "undefined (optional)", "()"));
    return c3;
  }
  get [isOptionalSymbol]() {
    return true;
  }
};
var $$optional = $constructedBy($Optional);
var $Never = class extends Schema2 {
  /**
   * @param {any} _o
   * @param {ValidationError} [err]
   * @return {_o is never}
   */
  check(_o3, err) {
    err == null ? void 0 : err.extend(null, "never", typeof _o3);
    return false;
  }
};
var $never = new $Never();
var $$never = $constructedBy($Never);
var _$Object = class _$Object extends Schema2 {
  /**
   * @param {S} shape
   * @param {boolean} partial
   */
  constructor(shape, partial = false) {
    super();
    this.shape = shape;
    this._isPartial = partial;
  }
  /**
   * @type {Schema<Partial<$ObjectToType<S>>>}
   */
  get partial() {
    return new _$Object(this.shape, true);
  }
  /**
   * @param {any} o
   * @param {ValidationError} err
   * @return {o is $ObjectToType<S>}
   */
  check(o2, err) {
    if (o2 == null) {
      err == null ? void 0 : err.extend(null, "object", "null");
      return false;
    }
    return every2(this.shape, (vv, vk) => {
      const c3 = this._isPartial && !hasProperty(o2, vk) || vv.check(o2[vk], err);
      !c3 && (err == null ? void 0 : err.extend(vk.toString(), vv.toString(), typeof o2[vk], "Object property does not match"));
      return c3;
    });
  }
};
__publicField(_$Object, "_dilutes", true);
var $Object = _$Object;
var $object = (def) => (
  /** @type {any} */
  new $Object(def)
);
var $$object = $constructedBy($Object);
var $objectAny = $custom((o2) => o2 != null && (o2.constructor === Object || o2.constructor == null));
var $Record = class extends Schema2 {
  /**
   * @param {Keys} keys
   * @param {Values} values
   */
  constructor(keys5, values2) {
    super();
    this.shape = {
      keys: keys5,
      values: values2
    };
  }
  /**
   * @param {any} o
   * @param {ValidationError} err
   * @return {o is { [key in Unwrap<Keys>]: Unwrap<Values> }}
   */
  check(o2, err) {
    return o2 != null && every2(o2, (vv, vk) => {
      const ck = this.shape.keys.check(vk, err);
      !ck && (err == null ? void 0 : err.extend(vk + "", "Record", typeof o2, ck ? "Key doesn't match schema" : "Value doesn't match value"));
      return ck && this.shape.values.check(vv, err);
    });
  }
};
var $record = (keys5, values2) => new $Record(keys5, values2);
var $$record = $constructedBy($Record);
var $Tuple = class extends Schema2 {
  /**
   * @param {S} shape
   */
  constructor(shape) {
    super();
    this.shape = shape;
  }
  /**
   * @param {any} o
   * @param {ValidationError} err
   * @return {o is { [K in keyof S]: S[K] extends Schema<infer Type> ? Type : never }}
   */
  check(o2, err) {
    return o2 != null && every2(this.shape, (vv, vk) => {
      const c3 = (
        /** @type {Schema<any>} */
        vv.check(o2[vk], err)
      );
      !c3 && (err == null ? void 0 : err.extend(vk.toString(), "Tuple", typeof vv));
      return c3;
    });
  }
};
var $tuple = (...def) => new $Tuple(def);
var $$tuple = $constructedBy($Tuple);
var $Array = class extends Schema2 {
  /**
   * @param {Array<S>} v
   */
  constructor(v8) {
    super();
    this.shape = v8.length === 1 ? v8[0] : new $Union(v8);
  }
  /**
   * @param {any} o
   * @param {ValidationError} [err]
   * @return {o is Array<S extends Schema<infer T> ? T : never>} o
   */
  check(o2, err) {
    const c3 = isArray(o2) && every(o2, (oi2) => this.shape.check(oi2));
    !c3 && (err == null ? void 0 : err.extend(null, "Array", ""));
    return c3;
  }
};
var $array = (...def) => new $Array(def);
var $$array = $constructedBy($Array);
var $arrayAny = $custom((o2) => isArray(o2));
var $InstanceOf = class extends Schema2 {
  /**
   * @param {new (...args:any) => T} constructor
   * @param {((o:T) => boolean)|null} check
   */
  constructor(constructor, check) {
    super();
    this.shape = constructor;
    this._c = check;
  }
  /**
   * @param {any} o
   * @param {ValidationError} err
   * @return {o is T}
   */
  check(o2, err) {
    const c3 = o2 instanceof this.shape && (this._c == null || this._c(o2));
    !c3 && (err == null ? void 0 : err.extend(null, this.shape.name, o2 == null ? void 0 : o2.constructor.name));
    return c3;
  }
};
var $instanceOf = (c3, check = null) => new $InstanceOf(c3, check);
var $$instanceOf = $constructedBy($InstanceOf);
var $$schema = $instanceOf(Schema2);
var $Lambda = class extends Schema2 {
  /**
   * @param {Args} args
   */
  constructor(args2) {
    super();
    this.len = args2.length - 1;
    this.args = $tuple(...args2.slice(-1));
    this.res = args2[this.len];
  }
  /**
   * @param {any} f
   * @param {ValidationError} err
   * @return {f is _LArgsToLambdaDef<Args>}
   */
  check(f6, err) {
    const c3 = f6.constructor === Function && f6.length <= this.len;
    !c3 && (err == null ? void 0 : err.extend(null, "function", typeof f6));
    return c3;
  }
};
var $$lambda = $constructedBy($Lambda);
var $function = $custom((o2) => typeof o2 === "function");
var $Intersection = class extends Schema2 {
  /**
   * @param {T} v
   */
  constructor(v8) {
    super();
    this.shape = v8;
  }
  /**
   * @param {any} o
   * @param {ValidationError} [err]
   * @return {o is Intersect<UnwrapArray<T>>}
   */
  check(o2, err) {
    const c3 = every(this.shape, (check) => check.check(o2, err));
    !c3 && (err == null ? void 0 : err.extend(null, "Intersectinon", typeof o2));
    return c3;
  }
};
var $$intersect = $constructedBy($Intersection, (o2) => o2.shape.length > 0);
var $Union = class extends Schema2 {
  /**
   * @param {Array<Schema<S>>} v
   */
  constructor(v8) {
    super();
    this.shape = v8;
  }
  /**
   * @param {any} o
   * @param {ValidationError} [err]
   * @return {o is S}
   */
  check(o2, err) {
    const c3 = some(this.shape, (vv) => vv.check(o2, err));
    err == null ? void 0 : err.extend(null, "Union", typeof o2);
    return c3;
  }
};
__publicField($Union, "_dilutes", true);
var $union = (...schemas) => schemas.findIndex(($s) => $$union.check($s)) >= 0 ? $union(...schemas.map(($s) => $($s)).map(($s) => $$union.check($s) ? $s.shape : [$s]).flat(1)) : schemas.length === 1 ? schemas[0] : new $Union(schemas);
var $$union = (
  /** @type {Schema<$Union<any>>} */
  $constructedBy($Union)
);
var _t = () => true;
var $any = $custom(_t);
var $$any = (
  /** @type {Schema<Schema<any>>} */
  $constructedBy($Custom, (o2) => o2.shape === _t)
);
var $bigint = $custom((o2) => typeof o2 === "bigint");
var $$bigint = (
  /** @type {Schema<Schema<BigInt>>} */
  $custom((o2) => o2 === $bigint)
);
var $symbol = $custom((o2) => typeof o2 === "symbol");
var $$symbol = (
  /** @type {Schema<Schema<Symbol>>} */
  $custom((o2) => o2 === $symbol)
);
var $number = $custom((o2) => typeof o2 === "number");
var $$number = (
  /** @type {Schema<Schema<number>>} */
  $custom((o2) => o2 === $number)
);
var $string = $custom((o2) => typeof o2 === "string");
var $$string = (
  /** @type {Schema<Schema<string>>} */
  $custom((o2) => o2 === $string)
);
var $boolean = $custom((o2) => typeof o2 === "boolean");
var $$boolean = (
  /** @type {Schema<Schema<Boolean>>} */
  $custom((o2) => o2 === $boolean)
);
var $undefined = $literal(void 0);
var $$undefined = (
  /** @type {Schema<Schema<undefined>>} */
  $constructedBy($Literal, (o2) => o2.shape.length === 1 && o2.shape[0] === void 0)
);
var $void = $literal(void 0);
var $null = $literal(null);
var $$null = (
  /** @type {Schema<Schema<null>>} */
  $constructedBy($Literal, (o2) => o2.shape.length === 1 && o2.shape[0] === null)
);
var $uint8Array = $constructedBy(Uint8Array);
var $$uint8Array = (
  /** @type {Schema<Schema<Uint8Array>>} */
  $constructedBy($ConstructedBy, (o2) => o2.shape === Uint8Array)
);
var $primitive = $union($number, $string, $null, $undefined, $bigint, $boolean, $symbol);
var $json = (() => {
  const $jsonArr = (
    /** @type {$Array<$any>} */
    $array($any)
  );
  const $jsonRecord = (
    /** @type {$Record<$string,$any>} */
    $record($string, $any)
  );
  const $json2 = $union($number, $string, $null, $boolean, $jsonArr, $jsonRecord);
  $jsonArr.shape = $json2;
  $jsonRecord.shape.values = $json2;
  return $json2;
})();
var $ = (o2) => {
  if ($$schema.check(o2)) {
    return (
      /** @type {any} */
      o2
    );
  } else if ($objectAny.check(o2)) {
    const o22 = {};
    for (const k3 in o2) {
      o22[k3] = $(o2[k3]);
    }
    return (
      /** @type {any} */
      $object(o22)
    );
  } else if ($arrayAny.check(o2)) {
    return (
      /** @type {any} */
      $union(...o2.map($))
    );
  } else if ($primitive.check(o2)) {
    return (
      /** @type {any} */
      $literal(o2)
    );
  } else if ($function.check(o2)) {
    return (
      /** @type {any} */
      $constructedBy(
        /** @type {any} */
        o2
      )
    );
  }
  unexpectedCase();
};
var assert = production ? () => {
} : (o2, schema) => {
  const err = new ValidationError();
  if (!schema.check(o2, err)) {
    throw create3(`Expected value to be of type ${schema.constructor.name}.
${err.toString()}`);
  }
};
var PatternMatcher = class {
  /**
   * @param {Schema<State>} [$state]
   */
  constructor($state) {
    this.patterns = [];
    this.$state = $state;
  }
  /**
   * @template P
   * @template R
   * @param {P} pattern
   * @param {(o:NoInfer<Unwrap<ReadSchema<P>>>,s:State)=>R} handler
   * @return {PatternMatcher<State,Patterns|Pattern<Unwrap<ReadSchema<P>>,R>>}
   */
  if(pattern, handler) {
    this.patterns.push({ if: $(pattern), h: handler });
    return this;
  }
  /**
   * @template R
   * @param {(o:any,s:State)=>R} h
   */
  else(h7) {
    return this.if($any, h7);
  }
  /**
   * @return {State extends undefined
   *   ? <In extends Unwrap<Patterns['if']>>(o:In,state?:undefined)=>PatternMatchResult<Patterns,In>
   *   : <In extends Unwrap<Patterns['if']>>(o:In,state:State)=>PatternMatchResult<Patterns,In>}
   */
  done() {
    return (
      /** @type {any} */
      (o2, s2) => {
        for (let i3 = 0; i3 < this.patterns.length; i3++) {
          const p4 = this.patterns[i3];
          if (p4.if.check(o2)) {
            return p4.h(o2, s2);
          }
        }
        throw create3("Unhandled pattern");
      }
    );
  }
};
var match = (state) => new PatternMatcher(
  /** @type {any} */
  state
);
var _random = (
  /** @type {any} */
  match(
    /** @type {Schema<prng.PRNG>} */
    $any
  ).if($$number, (_o3, gen) => int53(gen, MIN_SAFE_INTEGER, MAX_SAFE_INTEGER)).if($$string, (_o3, gen) => word(gen)).if($$boolean, (_o3, gen) => bool(gen)).if($$bigint, (_o3, gen) => BigInt(int53(gen, MIN_SAFE_INTEGER, MAX_SAFE_INTEGER))).if($$union, (o2, gen) => random(gen, oneOf2(gen, o2.shape))).if($$object, (o2, gen) => {
    const res = {};
    for (const k3 in o2.shape) {
      let prop = o2.shape[k3];
      if ($$optional.check(prop)) {
        if (bool(gen)) {
          continue;
        }
        prop = prop.shape;
      }
      res[k3] = _random(prop, gen);
    }
    return res;
  }).if($$array, (o2, gen) => {
    const arr = [];
    const n = int32(gen, 0, 42);
    for (let i3 = 0; i3 < n; i3++) {
      arr.push(random(gen, o2.shape));
    }
    return arr;
  }).if($$literal, (o2, gen) => {
    return oneOf2(gen, o2.shape);
  }).if($$null, (o2, gen) => {
    return null;
  }).if($$lambda, (o2, gen) => {
    const res = random(gen, o2.res);
    return () => res;
  }).if($$any, (o2, gen) => random(gen, oneOf2(gen, [
    $number,
    $string,
    $null,
    $undefined,
    $bigint,
    $boolean,
    $array($number),
    $record($union("a", "b", "c"), $number)
  ]))).if($$record, (o2, gen) => {
    const res = {};
    const keysN = int53(gen, 0, 3);
    for (let i3 = 0; i3 < keysN; i3++) {
      const key2 = random(gen, o2.shape.keys);
      const val = random(gen, o2.shape.values);
      res[key2] = val;
    }
    return res;
  }).done()
);
var random = (gen, schema) => (
  /** @type {any} */
  _random($(schema), gen)
);

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/dom.js
var doc3 = (
  /** @type {Document} */
  typeof document !== "undefined" ? document : {}
);
var $fragment = $custom((el2) => el2.nodeType === DOCUMENT_FRAGMENT_NODE);
var domParser = (
  /** @type {DOMParser} */
  typeof DOMParser !== "undefined" ? new DOMParser() : null
);
var $element = $custom((el2) => el2.nodeType === ELEMENT_NODE);
var $text = $custom((el2) => el2.nodeType === TEXT_NODE);
var mapToStyleString = (m2) => map(m2, (value, key2) => `${key2}:${value};`).join("");
var ELEMENT_NODE = doc3.ELEMENT_NODE;
var TEXT_NODE = doc3.TEXT_NODE;
var CDATA_SECTION_NODE = doc3.CDATA_SECTION_NODE;
var COMMENT_NODE = doc3.COMMENT_NODE;
var DOCUMENT_NODE = doc3.DOCUMENT_NODE;
var DOCUMENT_TYPE_NODE = doc3.DOCUMENT_TYPE_NODE;
var DOCUMENT_FRAGMENT_NODE = doc3.DOCUMENT_FRAGMENT_NODE;
var $node = $custom((el2) => el2.nodeType === DOCUMENT_NODE);

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/eventloop.js
var createTimeoutClass = (clearFunction) => class TT {
  /**
   * @param {number} timeoutId
   */
  constructor(timeoutId) {
    this._ = timeoutId;
  }
  destroy() {
    clearFunction(this._);
  }
};
var Timeout = createTimeoutClass(clearTimeout);
var timeout = (timeout2, callback) => new Timeout(setTimeout(callback, timeout2));
var Interval = createTimeoutClass(clearInterval);
var Animation = createTimeoutClass((arg) => typeof requestAnimationFrame !== "undefined" && cancelAnimationFrame(arg));
var Idle = createTimeoutClass((arg) => typeof cancelIdleCallback !== "undefined" && cancelIdleCallback(arg));

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/symbol.js
var create6 = Symbol;

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/logging.common.js
var BOLD = create6();
var UNBOLD = create6();
var BLUE = create6();
var GREY = create6();
var GREEN = create6();
var RED = create6();
var PURPLE = create6();
var ORANGE = create6();
var UNCOLOR = create6();
var computeNoColorLoggingArgs = (args2) => {
  var _a2;
  if (args2.length === 1 && ((_a2 = args2[0]) == null ? void 0 : _a2.constructor) === Function) {
    args2 = /** @type {Array<string|Symbol|Object|number>} */
    /** @type {[function]} */
    args2[0]();
  }
  const strBuilder = [];
  const logArgs = [];
  let i3 = 0;
  for (; i3 < args2.length; i3++) {
    const arg = args2[i3];
    if (arg === void 0) {
      break;
    } else if (arg.constructor === String || arg.constructor === Number) {
      strBuilder.push(arg);
    } else if (arg.constructor === Object) {
      break;
    }
  }
  if (i3 > 0) {
    logArgs.push(strBuilder.join(""));
  }
  for (; i3 < args2.length; i3++) {
    const arg = args2[i3];
    if (!(arg instanceof Symbol)) {
      logArgs.push(arg);
    }
  }
  return logArgs;
};
var lastLoggingTime = getUnixTime();

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/logging.js
var _browserStyleMap = {
  [BOLD]: create5("font-weight", "bold"),
  [UNBOLD]: create5("font-weight", "normal"),
  [BLUE]: create5("color", "blue"),
  [GREEN]: create5("color", "green"),
  [GREY]: create5("color", "grey"),
  [RED]: create5("color", "red"),
  [PURPLE]: create5("color", "purple"),
  [ORANGE]: create5("color", "orange"),
  // not well supported in chrome when debugging node with inspector - TODO: deprecate
  [UNCOLOR]: create5("color", "black")
};
var computeBrowserLoggingArgs = (args2) => {
  var _a2;
  if (args2.length === 1 && ((_a2 = args2[0]) == null ? void 0 : _a2.constructor) === Function) {
    args2 = /** @type {Array<string|Symbol|Object|number>} */
    /** @type {[function]} */
    args2[0]();
  }
  const strBuilder = [];
  const styles = [];
  const currentStyle = create();
  let logArgs = [];
  let i3 = 0;
  for (; i3 < args2.length; i3++) {
    const arg = args2[i3];
    const style3 = _browserStyleMap[arg];
    if (style3 !== void 0) {
      currentStyle.set(style3.left, style3.right);
    } else {
      if (arg === void 0) {
        break;
      }
      if (arg.constructor === String || arg.constructor === Number) {
        const style4 = mapToStyleString(currentStyle);
        if (i3 > 0 || style4.length > 0) {
          strBuilder.push("%c" + arg);
          styles.push(style4);
        } else {
          strBuilder.push(arg);
        }
      } else {
        break;
      }
    }
  }
  if (i3 > 0) {
    logArgs = styles;
    logArgs.unshift(strBuilder.join(""));
  }
  for (; i3 < args2.length; i3++) {
    const arg = args2[i3];
    if (!(arg instanceof Symbol)) {
      logArgs.push(arg);
    }
  }
  return logArgs;
};
var computeLoggingArgs = supportsColor ? computeBrowserLoggingArgs : computeNoColorLoggingArgs;
var print = (...args2) => {
  console.log(...computeLoggingArgs(args2));
  vconsoles.forEach((vc) => vc.print(args2));
};
var warn = (...args2) => {
  console.warn(...computeLoggingArgs(args2));
  args2.unshift(ORANGE);
  vconsoles.forEach((vc) => vc.print(args2));
};
var vconsoles = create2();

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/iterator.js
var createIterator = (next2) => ({
  /**
   * @return {IterableIterator<T>}
   */
  [Symbol.iterator]() {
    return this;
  },
  // @ts-ignore
  next: next2
});
var iteratorFilter = (iterator, filter) => createIterator(() => {
  let res;
  do {
    res = iterator.next();
  } while (!res.done && !filter(res.value));
  return res;
});
var iteratorMap = (iterator, fmap) => createIterator(() => {
  const { done, value } = iterator.next();
  return { done, value: done ? void 0 : fmap(value) };
});

// ../../node_modules/.pnpm/yjs@13.6.28/node_modules/yjs/dist/yjs.mjs
var DeleteItem = class {
  /**
   * @param {number} clock
   * @param {number} len
   */
  constructor(clock, len) {
    this.clock = clock;
    this.len = len;
  }
};
var DeleteSet = class {
  constructor() {
    this.clients = /* @__PURE__ */ new Map();
  }
};
var iterateDeletedStructs = (transaction, ds, f6) => ds.clients.forEach((deletes, clientid) => {
  const structs = (
    /** @type {Array<GC|Item>} */
    transaction.doc.store.clients.get(clientid)
  );
  if (structs != null) {
    const lastStruct = structs[structs.length - 1];
    const clockState = lastStruct.id.clock + lastStruct.length;
    for (let i3 = 0, del3 = deletes[i3]; i3 < deletes.length && del3.clock < clockState; del3 = deletes[++i3]) {
      iterateStructs(transaction, structs, del3.clock, del3.len, f6);
    }
  }
});
var findIndexDS = (dis, clock) => {
  let left = 0;
  let right = dis.length - 1;
  while (left <= right) {
    const midindex = floor((left + right) / 2);
    const mid = dis[midindex];
    const midclock = mid.clock;
    if (midclock <= clock) {
      if (clock < midclock + mid.len) {
        return midindex;
      }
      left = midindex + 1;
    } else {
      right = midindex - 1;
    }
  }
  return null;
};
var isDeleted = (ds, id2) => {
  const dis = ds.clients.get(id2.client);
  return dis !== void 0 && findIndexDS(dis, id2.clock) !== null;
};
var sortAndMergeDeleteSet = (ds) => {
  ds.clients.forEach((dels) => {
    dels.sort((a3, b4) => a3.clock - b4.clock);
    let i3, j4;
    for (i3 = 1, j4 = 1; i3 < dels.length; i3++) {
      const left = dels[j4 - 1];
      const right = dels[i3];
      if (left.clock + left.len >= right.clock) {
        left.len = max(left.len, right.clock + right.len - left.clock);
      } else {
        if (j4 < i3) {
          dels[j4] = right;
        }
        j4++;
      }
    }
    dels.length = j4;
  });
};
var mergeDeleteSets = (dss) => {
  const merged = new DeleteSet();
  for (let dssI = 0; dssI < dss.length; dssI++) {
    dss[dssI].clients.forEach((delsLeft, client) => {
      if (!merged.clients.has(client)) {
        const dels = delsLeft.slice();
        for (let i3 = dssI + 1; i3 < dss.length; i3++) {
          appendTo(dels, dss[i3].clients.get(client) || []);
        }
        merged.clients.set(client, dels);
      }
    });
  }
  sortAndMergeDeleteSet(merged);
  return merged;
};
var addToDeleteSet = (ds, client, clock, length2) => {
  setIfUndefined(ds.clients, client, () => (
    /** @type {Array<DeleteItem>} */
    []
  )).push(new DeleteItem(clock, length2));
};
var createDeleteSet = () => new DeleteSet();
var createDeleteSetFromStructStore = (ss) => {
  const ds = createDeleteSet();
  ss.clients.forEach((structs, client) => {
    const dsitems = [];
    for (let i3 = 0; i3 < structs.length; i3++) {
      const struct = structs[i3];
      if (struct.deleted) {
        const clock = struct.id.clock;
        let len = struct.length;
        if (i3 + 1 < structs.length) {
          for (let next2 = structs[i3 + 1]; i3 + 1 < structs.length && next2.deleted; next2 = structs[++i3 + 1]) {
            len += next2.length;
          }
        }
        dsitems.push(new DeleteItem(clock, len));
      }
    }
    if (dsitems.length > 0) {
      ds.clients.set(client, dsitems);
    }
  });
  return ds;
};
var writeDeleteSet = (encoder, ds) => {
  writeVarUint(encoder.restEncoder, ds.clients.size);
  from2(ds.clients.entries()).sort((a3, b4) => b4[0] - a3[0]).forEach(([client, dsitems]) => {
    encoder.resetDsCurVal();
    writeVarUint(encoder.restEncoder, client);
    const len = dsitems.length;
    writeVarUint(encoder.restEncoder, len);
    for (let i3 = 0; i3 < len; i3++) {
      const item = dsitems[i3];
      encoder.writeDsClock(item.clock);
      encoder.writeDsLen(item.len);
    }
  });
};
var readDeleteSet = (decoder) => {
  const ds = new DeleteSet();
  const numClients = readVarUint(decoder.restDecoder);
  for (let i3 = 0; i3 < numClients; i3++) {
    decoder.resetDsCurVal();
    const client = readVarUint(decoder.restDecoder);
    const numberOfDeletes = readVarUint(decoder.restDecoder);
    if (numberOfDeletes > 0) {
      const dsField = setIfUndefined(ds.clients, client, () => (
        /** @type {Array<DeleteItem>} */
        []
      ));
      for (let i4 = 0; i4 < numberOfDeletes; i4++) {
        dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()));
      }
    }
  }
  return ds;
};
var readAndApplyDeleteSet = (decoder, transaction, store) => {
  const unappliedDS = new DeleteSet();
  const numClients = readVarUint(decoder.restDecoder);
  for (let i3 = 0; i3 < numClients; i3++) {
    decoder.resetDsCurVal();
    const client = readVarUint(decoder.restDecoder);
    const numberOfDeletes = readVarUint(decoder.restDecoder);
    const structs = store.clients.get(client) || [];
    const state = getState(store, client);
    for (let i4 = 0; i4 < numberOfDeletes; i4++) {
      const clock = decoder.readDsClock();
      const clockEnd = clock + decoder.readDsLen();
      if (clock < state) {
        if (state < clockEnd) {
          addToDeleteSet(unappliedDS, client, state, clockEnd - state);
        }
        let index4 = findIndexSS(structs, clock);
        let struct = structs[index4];
        if (!struct.deleted && struct.id.clock < clock) {
          structs.splice(index4 + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));
          index4++;
        }
        while (index4 < structs.length) {
          struct = structs[index4++];
          if (struct.id.clock < clockEnd) {
            if (!struct.deleted) {
              if (clockEnd < struct.id.clock + struct.length) {
                structs.splice(index4, 0, splitItem(transaction, struct, clockEnd - struct.id.clock));
              }
              struct.delete(transaction);
            }
          } else {
            break;
          }
        }
      } else {
        addToDeleteSet(unappliedDS, client, clock, clockEnd - clock);
      }
    }
  }
  if (unappliedDS.clients.size > 0) {
    const ds = new UpdateEncoderV2();
    writeVarUint(ds.restEncoder, 0);
    writeDeleteSet(ds, unappliedDS);
    return ds.toUint8Array();
  }
  return null;
};
var generateNewClientId = uint32;
var Doc = class _Doc extends ObservableV2 {
  /**
   * @param {DocOpts} opts configuration
   */
  constructor({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta: meta2 = null, autoLoad = false, shouldLoad = true } = {}) {
    super();
    this.gc = gc;
    this.gcFilter = gcFilter;
    this.clientID = generateNewClientId();
    this.guid = guid;
    this.collectionid = collectionid;
    this.share = /* @__PURE__ */ new Map();
    this.store = new StructStore();
    this._transaction = null;
    this._transactionCleanups = [];
    this.subdocs = /* @__PURE__ */ new Set();
    this._item = null;
    this.shouldLoad = shouldLoad;
    this.autoLoad = autoLoad;
    this.meta = meta2;
    this.isLoaded = false;
    this.isSynced = false;
    this.isDestroyed = false;
    this.whenLoaded = create4((resolve2) => {
      this.on("load", () => {
        this.isLoaded = true;
        resolve2(this);
      });
    });
    const provideSyncedPromise = () => create4((resolve2) => {
      const eventHandler = (isSynced) => {
        if (isSynced === void 0 || isSynced === true) {
          this.off("sync", eventHandler);
          resolve2();
        }
      };
      this.on("sync", eventHandler);
    });
    this.on("sync", (isSynced) => {
      if (isSynced === false && this.isSynced) {
        this.whenSynced = provideSyncedPromise();
      }
      this.isSynced = isSynced === void 0 || isSynced === true;
      if (this.isSynced && !this.isLoaded) {
        this.emit("load", [this]);
      }
    });
    this.whenSynced = provideSyncedPromise();
  }
  /**
   * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).
   *
   * `load()` might be used in the future to request any provider to load the most current data.
   *
   * It is safe to call `load()` multiple times.
   */
  load() {
    const item = this._item;
    if (item !== null && !this.shouldLoad) {
      transact(
        /** @type {any} */
        item.parent.doc,
        (transaction) => {
          transaction.subdocsLoaded.add(this);
        },
        null,
        true
      );
    }
    this.shouldLoad = true;
  }
  getSubdocs() {
    return this.subdocs;
  }
  getSubdocGuids() {
    return new Set(from2(this.subdocs).map((doc4) => doc4.guid));
  }
  /**
   * Changes that happen inside of a transaction are bundled. This means that
   * the observer fires _after_ the transaction is finished and that all changes
   * that happened inside of the transaction are sent as one message to the
   * other peers.
   *
   * @template T
   * @param {function(Transaction):T} f The function that should be executed as a transaction
   * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin
   * @return T
   *
   * @public
   */
  transact(f6, origin = null) {
    return transact(this, f6, origin);
  }
  /**
   * Define a shared data type.
   *
   * Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result
   * and do not overwrite each other. I.e.
   * `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)`
   *
   * After this method is called, the type is also available on `ydoc.share.get(name)`.
   *
   * *Best Practices:*
   * Define all types right after the Y.Doc instance is created and store them in a separate object.
   * Also use the typed methods `getText(name)`, `getArray(name)`, ..
   *
   * @template {typeof AbstractType<any>} Type
   * @example
   *   const ydoc = new Y.Doc(..)
   *   const appState = {
   *     document: ydoc.getText('document')
   *     comments: ydoc.getArray('comments')
   *   }
   *
   * @param {string} name
   * @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...
   * @return {InstanceType<Type>} The created type. Constructed with TypeConstructor
   *
   * @public
   */
  get(name, TypeConstructor = (
    /** @type {any} */
    AbstractType
  )) {
    const type = setIfUndefined(this.share, name, () => {
      const t2 = new TypeConstructor();
      t2._integrate(this, null);
      return t2;
    });
    const Constr = type.constructor;
    if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {
      if (Constr === AbstractType) {
        const t2 = new TypeConstructor();
        t2._map = type._map;
        type._map.forEach(
          /** @param {Item?} n */
          (n) => {
            for (; n !== null; n = n.left) {
              n.parent = t2;
            }
          }
        );
        t2._start = type._start;
        for (let n = t2._start; n !== null; n = n.right) {
          n.parent = t2;
        }
        t2._length = type._length;
        this.share.set(name, t2);
        t2._integrate(this, null);
        return (
          /** @type {InstanceType<Type>} */
          t2
        );
      } else {
        throw new Error(`Type with the name ${name} has already been defined with a different constructor`);
      }
    }
    return (
      /** @type {InstanceType<Type>} */
      type
    );
  }
  /**
   * @template T
   * @param {string} [name]
   * @return {YArray<T>}
   *
   * @public
   */
  getArray(name = "") {
    return (
      /** @type {YArray<T>} */
      this.get(name, YArray)
    );
  }
  /**
   * @param {string} [name]
   * @return {YText}
   *
   * @public
   */
  getText(name = "") {
    return this.get(name, YText);
  }
  /**
   * @template T
   * @param {string} [name]
   * @return {YMap<T>}
   *
   * @public
   */
  getMap(name = "") {
    return (
      /** @type {YMap<T>} */
      this.get(name, YMap)
    );
  }
  /**
   * @param {string} [name]
   * @return {YXmlElement}
   *
   * @public
   */
  getXmlElement(name = "") {
    return (
      /** @type {YXmlElement<{[key:string]:string}>} */
      this.get(name, YXmlElement)
    );
  }
  /**
   * @param {string} [name]
   * @return {YXmlFragment}
   *
   * @public
   */
  getXmlFragment(name = "") {
    return this.get(name, YXmlFragment);
  }
  /**
   * Converts the entire document into a js object, recursively traversing each yjs type
   * Doesn't log types that have not been defined (using ydoc.getType(..)).
   *
   * @deprecated Do not use this method and rather call toJSON directly on the shared types.
   *
   * @return {Object<string, any>}
   */
  toJSON() {
    const doc4 = {};
    this.share.forEach((value, key2) => {
      doc4[key2] = value.toJSON();
    });
    return doc4;
  }
  /**
   * Emit `destroy` event and unregister all event handlers.
   */
  destroy() {
    this.isDestroyed = true;
    from2(this.subdocs).forEach((subdoc) => subdoc.destroy());
    const item = this._item;
    if (item !== null) {
      this._item = null;
      const content5 = (
        /** @type {ContentDoc} */
        item.content
      );
      content5.doc = new _Doc({ guid: this.guid, ...content5.opts, shouldLoad: false });
      content5.doc._item = item;
      transact(
        /** @type {any} */
        item.parent.doc,
        (transaction) => {
          const doc4 = content5.doc;
          if (!item.deleted) {
            transaction.subdocsAdded.add(doc4);
          }
          transaction.subdocsRemoved.add(this);
        },
        null,
        true
      );
    }
    this.emit("destroyed", [true]);
    this.emit("destroy", [this]);
    super.destroy();
  }
};
var DSDecoderV1 = class {
  /**
   * @param {decoding.Decoder} decoder
   */
  constructor(decoder) {
    this.restDecoder = decoder;
  }
  resetDsCurVal() {
  }
  /**
   * @return {number}
   */
  readDsClock() {
    return readVarUint(this.restDecoder);
  }
  /**
   * @return {number}
   */
  readDsLen() {
    return readVarUint(this.restDecoder);
  }
};
var UpdateDecoderV1 = class extends DSDecoderV1 {
  /**
   * @return {ID}
   */
  readLeftID() {
    return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder));
  }
  /**
   * @return {ID}
   */
  readRightID() {
    return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder));
  }
  /**
   * Read the next client id.
   * Use this in favor of readID whenever possible to reduce the number of objects created.
   */
  readClient() {
    return readVarUint(this.restDecoder);
  }
  /**
   * @return {number} info An unsigned 8-bit integer
   */
  readInfo() {
    return readUint8(this.restDecoder);
  }
  /**
   * @return {string}
   */
  readString() {
    return readVarString(this.restDecoder);
  }
  /**
   * @return {boolean} isKey
   */
  readParentInfo() {
    return readVarUint(this.restDecoder) === 1;
  }
  /**
   * @return {number} info An unsigned 8-bit integer
   */
  readTypeRef() {
    return readVarUint(this.restDecoder);
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @return {number} len
   */
  readLen() {
    return readVarUint(this.restDecoder);
  }
  /**
   * @return {any}
   */
  readAny() {
    return readAny(this.restDecoder);
  }
  /**
   * @return {Uint8Array}
   */
  readBuf() {
    return copyUint8Array(readVarUint8Array(this.restDecoder));
  }
  /**
   * Legacy implementation uses JSON parse. We use any-decoding in v2.
   *
   * @return {any}
   */
  readJSON() {
    return JSON.parse(readVarString(this.restDecoder));
  }
  /**
   * @return {string}
   */
  readKey() {
    return readVarString(this.restDecoder);
  }
};
var DSDecoderV2 = class {
  /**
   * @param {decoding.Decoder} decoder
   */
  constructor(decoder) {
    this.dsCurrVal = 0;
    this.restDecoder = decoder;
  }
  resetDsCurVal() {
    this.dsCurrVal = 0;
  }
  /**
   * @return {number}
   */
  readDsClock() {
    this.dsCurrVal += readVarUint(this.restDecoder);
    return this.dsCurrVal;
  }
  /**
   * @return {number}
   */
  readDsLen() {
    const diff = readVarUint(this.restDecoder) + 1;
    this.dsCurrVal += diff;
    return diff;
  }
};
var UpdateDecoderV2 = class extends DSDecoderV2 {
  /**
   * @param {decoding.Decoder} decoder
   */
  constructor(decoder) {
    super(decoder);
    this.keys = [];
    readVarUint(decoder);
    this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
    this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
    this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
    this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
    this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);
    this.stringDecoder = new StringDecoder(readVarUint8Array(decoder));
    this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);
    this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
    this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
  }
  /**
   * @return {ID}
   */
  readLeftID() {
    return new ID(this.clientDecoder.read(), this.leftClockDecoder.read());
  }
  /**
   * @return {ID}
   */
  readRightID() {
    return new ID(this.clientDecoder.read(), this.rightClockDecoder.read());
  }
  /**
   * Read the next client id.
   * Use this in favor of readID whenever possible to reduce the number of objects created.
   */
  readClient() {
    return this.clientDecoder.read();
  }
  /**
   * @return {number} info An unsigned 8-bit integer
   */
  readInfo() {
    return (
      /** @type {number} */
      this.infoDecoder.read()
    );
  }
  /**
   * @return {string}
   */
  readString() {
    return this.stringDecoder.read();
  }
  /**
   * @return {boolean}
   */
  readParentInfo() {
    return this.parentInfoDecoder.read() === 1;
  }
  /**
   * @return {number} An unsigned 8-bit integer
   */
  readTypeRef() {
    return this.typeRefDecoder.read();
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @return {number}
   */
  readLen() {
    return this.lenDecoder.read();
  }
  /**
   * @return {any}
   */
  readAny() {
    return readAny(this.restDecoder);
  }
  /**
   * @return {Uint8Array}
   */
  readBuf() {
    return readVarUint8Array(this.restDecoder);
  }
  /**
   * This is mainly here for legacy purposes.
   *
   * 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.
   *
   * @return {any}
   */
  readJSON() {
    return readAny(this.restDecoder);
  }
  /**
   * @return {string}
   */
  readKey() {
    const keyClock = this.keyClockDecoder.read();
    if (keyClock < this.keys.length) {
      return this.keys[keyClock];
    } else {
      const key2 = this.stringDecoder.read();
      this.keys.push(key2);
      return key2;
    }
  }
};
var DSEncoderV1 = class {
  constructor() {
    this.restEncoder = createEncoder();
  }
  toUint8Array() {
    return toUint8Array(this.restEncoder);
  }
  resetDsCurVal() {
  }
  /**
   * @param {number} clock
   */
  writeDsClock(clock) {
    writeVarUint(this.restEncoder, clock);
  }
  /**
   * @param {number} len
   */
  writeDsLen(len) {
    writeVarUint(this.restEncoder, len);
  }
};
var UpdateEncoderV1 = class extends DSEncoderV1 {
  /**
   * @param {ID} id
   */
  writeLeftID(id2) {
    writeVarUint(this.restEncoder, id2.client);
    writeVarUint(this.restEncoder, id2.clock);
  }
  /**
   * @param {ID} id
   */
  writeRightID(id2) {
    writeVarUint(this.restEncoder, id2.client);
    writeVarUint(this.restEncoder, id2.clock);
  }
  /**
   * Use writeClient and writeClock instead of writeID if possible.
   * @param {number} client
   */
  writeClient(client) {
    writeVarUint(this.restEncoder, client);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeInfo(info) {
    writeUint8(this.restEncoder, info);
  }
  /**
   * @param {string} s
   */
  writeString(s2) {
    writeVarString(this.restEncoder, s2);
  }
  /**
   * @param {boolean} isYKey
   */
  writeParentInfo(isYKey) {
    writeVarUint(this.restEncoder, isYKey ? 1 : 0);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeTypeRef(info) {
    writeVarUint(this.restEncoder, info);
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @param {number} len
   */
  writeLen(len) {
    writeVarUint(this.restEncoder, len);
  }
  /**
   * @param {any} any
   */
  writeAny(any2) {
    writeAny(this.restEncoder, any2);
  }
  /**
   * @param {Uint8Array} buf
   */
  writeBuf(buf) {
    writeVarUint8Array(this.restEncoder, buf);
  }
  /**
   * @param {any} embed
   */
  writeJSON(embed) {
    writeVarString(this.restEncoder, JSON.stringify(embed));
  }
  /**
   * @param {string} key
   */
  writeKey(key2) {
    writeVarString(this.restEncoder, key2);
  }
};
var DSEncoderV2 = class {
  constructor() {
    this.restEncoder = createEncoder();
    this.dsCurrVal = 0;
  }
  toUint8Array() {
    return toUint8Array(this.restEncoder);
  }
  resetDsCurVal() {
    this.dsCurrVal = 0;
  }
  /**
   * @param {number} clock
   */
  writeDsClock(clock) {
    const diff = clock - this.dsCurrVal;
    this.dsCurrVal = clock;
    writeVarUint(this.restEncoder, diff);
  }
  /**
   * @param {number} len
   */
  writeDsLen(len) {
    if (len === 0) {
      unexpectedCase();
    }
    writeVarUint(this.restEncoder, len - 1);
    this.dsCurrVal += len;
  }
};
var UpdateEncoderV2 = class extends DSEncoderV2 {
  constructor() {
    super();
    this.keyMap = /* @__PURE__ */ new Map();
    this.keyClock = 0;
    this.keyClockEncoder = new IntDiffOptRleEncoder();
    this.clientEncoder = new UintOptRleEncoder();
    this.leftClockEncoder = new IntDiffOptRleEncoder();
    this.rightClockEncoder = new IntDiffOptRleEncoder();
    this.infoEncoder = new RleEncoder(writeUint8);
    this.stringEncoder = new StringEncoder();
    this.parentInfoEncoder = new RleEncoder(writeUint8);
    this.typeRefEncoder = new UintOptRleEncoder();
    this.lenEncoder = new UintOptRleEncoder();
  }
  toUint8Array() {
    const encoder = createEncoder();
    writeVarUint(encoder, 0);
    writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.clientEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array());
    writeVarUint8Array(encoder, toUint8Array(this.infoEncoder));
    writeVarUint8Array(encoder, this.stringEncoder.toUint8Array());
    writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder));
    writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array());
    writeVarUint8Array(encoder, this.lenEncoder.toUint8Array());
    writeUint8Array(encoder, toUint8Array(this.restEncoder));
    return toUint8Array(encoder);
  }
  /**
   * @param {ID} id
   */
  writeLeftID(id2) {
    this.clientEncoder.write(id2.client);
    this.leftClockEncoder.write(id2.clock);
  }
  /**
   * @param {ID} id
   */
  writeRightID(id2) {
    this.clientEncoder.write(id2.client);
    this.rightClockEncoder.write(id2.clock);
  }
  /**
   * @param {number} client
   */
  writeClient(client) {
    this.clientEncoder.write(client);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeInfo(info) {
    this.infoEncoder.write(info);
  }
  /**
   * @param {string} s
   */
  writeString(s2) {
    this.stringEncoder.write(s2);
  }
  /**
   * @param {boolean} isYKey
   */
  writeParentInfo(isYKey) {
    this.parentInfoEncoder.write(isYKey ? 1 : 0);
  }
  /**
   * @param {number} info An unsigned 8-bit integer
   */
  writeTypeRef(info) {
    this.typeRefEncoder.write(info);
  }
  /**
   * Write len of a struct - well suited for Opt RLE encoder.
   *
   * @param {number} len
   */
  writeLen(len) {
    this.lenEncoder.write(len);
  }
  /**
   * @param {any} any
   */
  writeAny(any2) {
    writeAny(this.restEncoder, any2);
  }
  /**
   * @param {Uint8Array} buf
   */
  writeBuf(buf) {
    writeVarUint8Array(this.restEncoder, buf);
  }
  /**
   * This is mainly here for legacy purposes.
   *
   * 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.
   *
   * @param {any} embed
   */
  writeJSON(embed) {
    writeAny(this.restEncoder, embed);
  }
  /**
   * Property keys are often reused. For example, in y-prosemirror the key `bold` might
   * occur very often. For a 3d application, the key `position` might occur very often.
   *
   * We cache these keys in a Map and refer to them via a unique number.
   *
   * @param {string} key
   */
  writeKey(key2) {
    const clock = this.keyMap.get(key2);
    if (clock === void 0) {
      this.keyClockEncoder.write(this.keyClock++);
      this.stringEncoder.write(key2);
    } else {
      this.keyClockEncoder.write(clock);
    }
  }
};
var writeStructs = (encoder, structs, client, clock) => {
  clock = max(clock, structs[0].id.clock);
  const startNewStructs = findIndexSS(structs, clock);
  writeVarUint(encoder.restEncoder, structs.length - startNewStructs);
  encoder.writeClient(client);
  writeVarUint(encoder.restEncoder, clock);
  const firstStruct = structs[startNewStructs];
  firstStruct.write(encoder, clock - firstStruct.id.clock);
  for (let i3 = startNewStructs + 1; i3 < structs.length; i3++) {
    structs[i3].write(encoder, 0);
  }
};
var writeClientsStructs = (encoder, store, _sm) => {
  const sm = /* @__PURE__ */ new Map();
  _sm.forEach((clock, client) => {
    if (getState(store, client) > clock) {
      sm.set(client, clock);
    }
  });
  getStateVector(store).forEach((_clock, client) => {
    if (!_sm.has(client)) {
      sm.set(client, 0);
    }
  });
  writeVarUint(encoder.restEncoder, sm.size);
  from2(sm.entries()).sort((a3, b4) => b4[0] - a3[0]).forEach(([client, clock]) => {
    writeStructs(
      encoder,
      /** @type {Array<GC|Item>} */
      store.clients.get(client),
      client,
      clock
    );
  });
};
var readClientsStructRefs = (decoder, doc4) => {
  const clientRefs = create();
  const numOfStateUpdates = readVarUint(decoder.restDecoder);
  for (let i3 = 0; i3 < numOfStateUpdates; i3++) {
    const numberOfStructs = readVarUint(decoder.restDecoder);
    const refs = new Array(numberOfStructs);
    const client = decoder.readClient();
    let clock = readVarUint(decoder.restDecoder);
    clientRefs.set(client, { i: 0, refs });
    for (let i4 = 0; i4 < numberOfStructs; i4++) {
      const info = decoder.readInfo();
      switch (BITS5 & info) {
        case 0: {
          const len = decoder.readLen();
          refs[i4] = new GC(createID(client, clock), len);
          clock += len;
          break;
        }
        case 10: {
          const len = readVarUint(decoder.restDecoder);
          refs[i4] = new Skip(createID(client, clock), len);
          clock += len;
          break;
        }
        default: {
          const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;
          const struct = new Item(
            createID(client, clock),
            null,
            // left
            (info & BIT8) === BIT8 ? decoder.readLeftID() : null,
            // origin
            null,
            // right
            (info & BIT7) === BIT7 ? decoder.readRightID() : null,
            // right origin
            cantCopyParentInfo ? decoder.readParentInfo() ? doc4.get(decoder.readString()) : decoder.readLeftID() : null,
            // parent
            cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null,
            // parentSub
            readItemContent(decoder, info)
            // item content
          );
          refs[i4] = struct;
          clock += struct.length;
        }
      }
    }
  }
  return clientRefs;
};
var integrateStructs = (transaction, store, clientsStructRefs) => {
  const stack = [];
  let clientsStructRefsIds = from2(clientsStructRefs.keys()).sort((a3, b4) => a3 - b4);
  if (clientsStructRefsIds.length === 0) {
    return null;
  }
  const getNextStructTarget = () => {
    if (clientsStructRefsIds.length === 0) {
      return null;
    }
    let nextStructsTarget = (
      /** @type {{i:number,refs:Array<GC|Item>}} */
      clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])
    );
    while (nextStructsTarget.refs.length === nextStructsTarget.i) {
      clientsStructRefsIds.pop();
      if (clientsStructRefsIds.length > 0) {
        nextStructsTarget = /** @type {{i:number,refs:Array<GC|Item>}} */
        clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]);
      } else {
        return null;
      }
    }
    return nextStructsTarget;
  };
  let curStructsTarget = getNextStructTarget();
  if (curStructsTarget === null) {
    return null;
  }
  const restStructs = new StructStore();
  const missingSV = /* @__PURE__ */ new Map();
  const updateMissingSv = (client, clock) => {
    const mclock = missingSV.get(client);
    if (mclock == null || mclock > clock) {
      missingSV.set(client, clock);
    }
  };
  let stackHead = (
    /** @type {any} */
    curStructsTarget.refs[
      /** @type {any} */
      curStructsTarget.i++
    ]
  );
  const state = /* @__PURE__ */ new Map();
  const addStackToRestSS = () => {
    for (const item of stack) {
      const client = item.id.client;
      const inapplicableItems = clientsStructRefs.get(client);
      if (inapplicableItems) {
        inapplicableItems.i--;
        restStructs.clients.set(client, inapplicableItems.refs.slice(inapplicableItems.i));
        clientsStructRefs.delete(client);
        inapplicableItems.i = 0;
        inapplicableItems.refs = [];
      } else {
        restStructs.clients.set(client, [item]);
      }
      clientsStructRefsIds = clientsStructRefsIds.filter((c3) => c3 !== client);
    }
    stack.length = 0;
  };
  while (true) {
    if (stackHead.constructor !== Skip) {
      const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client));
      const offset4 = localClock - stackHead.id.clock;
      if (offset4 < 0) {
        stack.push(stackHead);
        updateMissingSv(stackHead.id.client, stackHead.id.clock - 1);
        addStackToRestSS();
      } else {
        const missing = stackHead.getMissing(transaction, store);
        if (missing !== null) {
          stack.push(stackHead);
          const structRefs = clientsStructRefs.get(
            /** @type {number} */
            missing
          ) || { refs: [], i: 0 };
          if (structRefs.refs.length === structRefs.i) {
            updateMissingSv(
              /** @type {number} */
              missing,
              getState(store, missing)
            );
            addStackToRestSS();
          } else {
            stackHead = structRefs.refs[structRefs.i++];
            continue;
          }
        } else if (offset4 === 0 || offset4 < stackHead.length) {
          stackHead.integrate(transaction, offset4);
          state.set(stackHead.id.client, stackHead.id.clock + stackHead.length);
        }
      }
    }
    if (stack.length > 0) {
      stackHead = /** @type {GC|Item} */
      stack.pop();
    } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {
      stackHead = /** @type {GC|Item} */
      curStructsTarget.refs[curStructsTarget.i++];
    } else {
      curStructsTarget = getNextStructTarget();
      if (curStructsTarget === null) {
        break;
      } else {
        stackHead = /** @type {GC|Item} */
        curStructsTarget.refs[curStructsTarget.i++];
      }
    }
  }
  if (restStructs.clients.size > 0) {
    const encoder = new UpdateEncoderV2();
    writeClientsStructs(encoder, restStructs, /* @__PURE__ */ new Map());
    writeVarUint(encoder.restEncoder, 0);
    return { missing: missingSV, update: encoder.toUint8Array() };
  }
  return null;
};
var writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState);
var readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => transact(ydoc, (transaction) => {
  transaction.local = false;
  let retry = false;
  const doc4 = transaction.doc;
  const store = doc4.store;
  const ss = readClientsStructRefs(structDecoder, doc4);
  const restStructs = integrateStructs(transaction, store, ss);
  const pending = store.pendingStructs;
  if (pending) {
    for (const [client, clock] of pending.missing) {
      if (clock < getState(store, client)) {
        retry = true;
        break;
      }
    }
    if (restStructs) {
      for (const [client, clock] of restStructs.missing) {
        const mclock = pending.missing.get(client);
        if (mclock == null || mclock > clock) {
          pending.missing.set(client, clock);
        }
      }
      pending.update = mergeUpdatesV2([pending.update, restStructs.update]);
    }
  } else {
    store.pendingStructs = restStructs;
  }
  const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store);
  if (store.pendingDs) {
    const pendingDSUpdate = new UpdateDecoderV2(createDecoder(store.pendingDs));
    readVarUint(pendingDSUpdate.restDecoder);
    const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store);
    if (dsRest && dsRest2) {
      store.pendingDs = mergeUpdatesV2([dsRest, dsRest2]);
    } else {
      store.pendingDs = dsRest || dsRest2;
    }
  } else {
    store.pendingDs = dsRest;
  }
  if (retry) {
    const update = (
      /** @type {{update: Uint8Array}} */
      store.pendingStructs.update
    );
    store.pendingStructs = null;
    applyUpdateV2(transaction.doc, update);
  }
}, transactionOrigin, false);
var applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {
  const decoder = createDecoder(update);
  readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder));
};
var applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1);
var writeStateAsUpdate = (encoder, doc4, targetStateVector = /* @__PURE__ */ new Map()) => {
  writeClientsStructs(encoder, doc4.store, targetStateVector);
  writeDeleteSet(encoder, createDeleteSetFromStructStore(doc4.store));
};
var encodeStateAsUpdateV2 = (doc4, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => {
  const targetStateVector = decodeStateVector(encodedTargetStateVector);
  writeStateAsUpdate(encoder, doc4, targetStateVector);
  const updates = [encoder.toUint8Array()];
  if (doc4.store.pendingDs) {
    updates.push(doc4.store.pendingDs);
  }
  if (doc4.store.pendingStructs) {
    updates.push(diffUpdateV2(doc4.store.pendingStructs.update, encodedTargetStateVector));
  }
  if (updates.length > 1) {
    if (encoder.constructor === UpdateEncoderV1) {
      return mergeUpdates(updates.map((update, i3) => i3 === 0 ? update : convertUpdateFormatV2ToV1(update)));
    } else if (encoder.constructor === UpdateEncoderV2) {
      return mergeUpdatesV2(updates);
    }
  }
  return updates[0];
};
var encodeStateAsUpdate = (doc4, encodedTargetStateVector) => encodeStateAsUpdateV2(doc4, encodedTargetStateVector, new UpdateEncoderV1());
var readStateVector = (decoder) => {
  const ss = /* @__PURE__ */ new Map();
  const ssLength = readVarUint(decoder.restDecoder);
  for (let i3 = 0; i3 < ssLength; i3++) {
    const client = readVarUint(decoder.restDecoder);
    const clock = readVarUint(decoder.restDecoder);
    ss.set(client, clock);
  }
  return ss;
};
var decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState)));
var writeStateVector = (encoder, sv) => {
  writeVarUint(encoder.restEncoder, sv.size);
  from2(sv.entries()).sort((a3, b4) => b4[0] - a3[0]).forEach(([client, clock]) => {
    writeVarUint(encoder.restEncoder, client);
    writeVarUint(encoder.restEncoder, clock);
  });
  return encoder;
};
var writeDocumentStateVector = (encoder, doc4) => writeStateVector(encoder, getStateVector(doc4.store));
var encodeStateVectorV2 = (doc4, encoder = new DSEncoderV2()) => {
  if (doc4 instanceof Map) {
    writeStateVector(encoder, doc4);
  } else {
    writeDocumentStateVector(encoder, doc4);
  }
  return encoder.toUint8Array();
};
var encodeStateVector = (doc4) => encodeStateVectorV2(doc4, new DSEncoderV1());
var EventHandler = class {
  constructor() {
    this.l = [];
  }
};
var createEventHandler = () => new EventHandler();
var addEventHandlerListener = (eventHandler, f6) => eventHandler.l.push(f6);
var removeEventHandlerListener = (eventHandler, f6) => {
  const l2 = eventHandler.l;
  const len = l2.length;
  eventHandler.l = l2.filter((g) => f6 !== g);
  if (len === eventHandler.l.length) {
    console.error("[yjs] Tried to remove event handler that doesn't exist.");
  }
};
var callEventHandlerListeners = (eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]);
var ID = class {
  /**
   * @param {number} client client id
   * @param {number} clock unique per client id, continuous number
   */
  constructor(client, clock) {
    this.client = client;
    this.clock = clock;
  }
};
var compareIDs = (a3, b4) => a3 === b4 || a3 !== null && b4 !== null && a3.client === b4.client && a3.clock === b4.clock;
var createID = (client, clock) => new ID(client, clock);
var findRootTypeKey = (type) => {
  for (const [key2, value] of type.doc.share.entries()) {
    if (value === type) {
      return key2;
    }
  }
  throw unexpectedCase();
};
var isParentOf = (parent, child) => {
  while (child !== null) {
    if (child.parent === parent) {
      return true;
    }
    child = /** @type {AbstractType<any>} */
    child.parent._item;
  }
  return false;
};
var RelativePosition = class {
  /**
   * @param {ID|null} type
   * @param {string|null} tname
   * @param {ID|null} item
   * @param {number} assoc
   */
  constructor(type, tname, item, assoc = 0) {
    this.type = type;
    this.tname = tname;
    this.item = item;
    this.assoc = assoc;
  }
};
var 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);
var AbsolutePosition = class {
  /**
   * @param {AbstractType<any>} type
   * @param {number} index
   * @param {number} [assoc]
   */
  constructor(type, index4, assoc = 0) {
    this.type = type;
    this.index = index4;
    this.assoc = assoc;
  }
};
var createAbsolutePosition = (type, index4, assoc = 0) => new AbsolutePosition(type, index4, assoc);
var createRelativePosition = (type, item, assoc) => {
  let typeid = null;
  let tname = null;
  if (type._item === null) {
    tname = findRootTypeKey(type);
  } else {
    typeid = createID(type._item.id.client, type._item.id.clock);
  }
  return new RelativePosition(typeid, tname, item, assoc);
};
var createRelativePositionFromTypeIndex = (type, index4, assoc = 0) => {
  let t2 = type._start;
  if (assoc < 0) {
    if (index4 === 0) {
      return createRelativePosition(type, null, assoc);
    }
    index4--;
  }
  while (t2 !== null) {
    if (!t2.deleted && t2.countable) {
      if (t2.length > index4) {
        return createRelativePosition(type, createID(t2.id.client, t2.id.clock + index4), assoc);
      }
      index4 -= t2.length;
    }
    if (t2.right === null && assoc < 0) {
      return createRelativePosition(type, t2.lastId, assoc);
    }
    t2 = t2.right;
  }
  return createRelativePosition(type, null, assoc);
};
var getItemWithOffset = (store, id2) => {
  const item = getItem(store, id2);
  const diff = id2.clock - item.id.clock;
  return {
    item,
    diff
  };
};
var createAbsolutePositionFromRelativePosition = (rpos, doc4, followUndoneDeletions = true) => {
  const store = doc4.store;
  const rightID = rpos.item;
  const typeID = rpos.type;
  const tname = rpos.tname;
  const assoc = rpos.assoc;
  let type = null;
  let index4 = 0;
  if (rightID !== null) {
    if (getState(store, rightID.client) <= rightID.clock) {
      return null;
    }
    const res = followUndoneDeletions ? followRedone(store, rightID) : getItemWithOffset(store, rightID);
    const right = res.item;
    if (!(right instanceof Item)) {
      return null;
    }
    type = /** @type {AbstractType<any>} */
    right.parent;
    if (type._item === null || !type._item.deleted) {
      index4 = right.deleted || !right.countable ? 0 : res.diff + (assoc >= 0 ? 0 : 1);
      let n = right.left;
      while (n !== null) {
        if (!n.deleted && n.countable) {
          index4 += n.length;
        }
        n = n.left;
      }
    }
  } else {
    if (tname !== null) {
      type = doc4.get(tname);
    } else if (typeID !== null) {
      if (getState(store, typeID.client) <= typeID.clock) {
        return null;
      }
      const { item } = followUndoneDeletions ? followRedone(store, typeID) : { item: getItem(store, typeID) };
      if (item instanceof Item && item.content instanceof ContentType) {
        type = item.content.type;
      } else {
        return null;
      }
    } else {
      throw unexpectedCase();
    }
    if (assoc >= 0) {
      index4 = type._length;
    } else {
      index4 = 0;
    }
  }
  return createAbsolutePosition(type, index4, rpos.assoc);
};
var compareRelativePositions = (a3, b4) => a3 === b4 || a3 !== null && b4 !== null && a3.tname === b4.tname && compareIDs(a3.item, b4.item) && compareIDs(a3.type, b4.type) && a3.assoc === b4.assoc;
var Snapshot = class {
  /**
   * @param {DeleteSet} ds
   * @param {Map<number,number>} sv state map
   */
  constructor(ds, sv) {
    this.ds = ds;
    this.sv = sv;
  }
};
var createSnapshot = (ds, sm) => new Snapshot(ds, sm);
var emptySnapshot = createSnapshot(createDeleteSet(), /* @__PURE__ */ new Map());
var snapshot = (doc4) => createSnapshot(createDeleteSetFromStructStore(doc4.store), getStateVector(doc4.store));
var isVisible = (item, snapshot2) => snapshot2 === void 0 ? !item.deleted : snapshot2.sv.has(item.id.client) && (snapshot2.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot2.ds, item.id);
var splitSnapshotAffectedStructs = (transaction, snapshot2) => {
  const meta2 = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create2);
  const store = transaction.doc.store;
  if (!meta2.has(snapshot2)) {
    snapshot2.sv.forEach((clock, client) => {
      if (clock < getState(store, client)) {
        getItemCleanStart(transaction, createID(client, clock));
      }
    });
    iterateDeletedStructs(transaction, snapshot2.ds, (_item) => {
    });
    meta2.add(snapshot2);
  }
};
var StructStore = class {
  constructor() {
    this.clients = /* @__PURE__ */ new Map();
    this.pendingStructs = null;
    this.pendingDs = null;
  }
};
var getStateVector = (store) => {
  const sm = /* @__PURE__ */ new Map();
  store.clients.forEach((structs, client) => {
    const struct = structs[structs.length - 1];
    sm.set(client, struct.id.clock + struct.length);
  });
  return sm;
};
var getState = (store, client) => {
  const structs = store.clients.get(client);
  if (structs === void 0) {
    return 0;
  }
  const lastStruct = structs[structs.length - 1];
  return lastStruct.id.clock + lastStruct.length;
};
var addStruct = (store, struct) => {
  let structs = store.clients.get(struct.id.client);
  if (structs === void 0) {
    structs = [];
    store.clients.set(struct.id.client, structs);
  } else {
    const lastStruct = structs[structs.length - 1];
    if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {
      throw unexpectedCase();
    }
  }
  structs.push(struct);
};
var findIndexSS = (structs, clock) => {
  let left = 0;
  let right = structs.length - 1;
  let mid = structs[right];
  let midclock = mid.id.clock;
  if (midclock === clock) {
    return right;
  }
  let midindex = floor(clock / (midclock + mid.length - 1) * right);
  while (left <= right) {
    mid = structs[midindex];
    midclock = mid.id.clock;
    if (midclock <= clock) {
      if (clock < midclock + mid.length) {
        return midindex;
      }
      left = midindex + 1;
    } else {
      right = midindex - 1;
    }
    midindex = floor((left + right) / 2);
  }
  throw unexpectedCase();
};
var find = (store, id2) => {
  const structs = store.clients.get(id2.client);
  return structs[findIndexSS(structs, id2.clock)];
};
var getItem = (
  /** @type {function(StructStore,ID):Item} */
  find
);
var findIndexCleanStart = (transaction, structs, clock) => {
  const index4 = findIndexSS(structs, clock);
  const struct = structs[index4];
  if (struct.id.clock < clock && struct instanceof Item) {
    structs.splice(index4 + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));
    return index4 + 1;
  }
  return index4;
};
var getItemCleanStart = (transaction, id2) => {
  const structs = (
    /** @type {Array<Item>} */
    transaction.doc.store.clients.get(id2.client)
  );
  return structs[findIndexCleanStart(transaction, structs, id2.clock)];
};
var getItemCleanEnd = (transaction, store, id2) => {
  const structs = store.clients.get(id2.client);
  const index4 = findIndexSS(structs, id2.clock);
  const struct = structs[index4];
  if (id2.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {
    structs.splice(index4 + 1, 0, splitItem(transaction, struct, id2.clock - struct.id.clock + 1));
  }
  return struct;
};
var replaceStruct = (store, struct, newStruct) => {
  const structs = (
    /** @type {Array<GC|Item>} */
    store.clients.get(struct.id.client)
  );
  structs[findIndexSS(structs, struct.id.clock)] = newStruct;
};
var iterateStructs = (transaction, structs, clockStart, len, f6) => {
  if (len === 0) {
    return;
  }
  const clockEnd = clockStart + len;
  let index4 = findIndexCleanStart(transaction, structs, clockStart);
  let struct;
  do {
    struct = structs[index4++];
    if (clockEnd < struct.id.clock + struct.length) {
      findIndexCleanStart(transaction, structs, clockEnd);
    }
    f6(struct);
  } while (index4 < structs.length && structs[index4].id.clock < clockEnd);
};
var Transaction2 = class {
  /**
   * @param {Doc} doc
   * @param {any} origin
   * @param {boolean} local
   */
  constructor(doc4, origin, local) {
    this.doc = doc4;
    this.deleteSet = new DeleteSet();
    this.beforeState = getStateVector(doc4.store);
    this.afterState = /* @__PURE__ */ new Map();
    this.changed = /* @__PURE__ */ new Map();
    this.changedParentTypes = /* @__PURE__ */ new Map();
    this._mergeStructs = [];
    this.origin = origin;
    this.meta = /* @__PURE__ */ new Map();
    this.local = local;
    this.subdocsAdded = /* @__PURE__ */ new Set();
    this.subdocsRemoved = /* @__PURE__ */ new Set();
    this.subdocsLoaded = /* @__PURE__ */ new Set();
    this._needFormattingCleanup = false;
  }
};
var writeUpdateMessageFromTransaction = (encoder, transaction) => {
  if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {
    return false;
  }
  sortAndMergeDeleteSet(transaction.deleteSet);
  writeStructsFromTransaction(encoder, transaction);
  writeDeleteSet(encoder, transaction.deleteSet);
  return true;
};
var addChangedTypeToTransaction = (transaction, type, parentSub) => {
  const item = type._item;
  if (item === null || item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted) {
    setIfUndefined(transaction.changed, type, create2).add(parentSub);
  }
};
var tryToMergeWithLefts = (structs, pos) => {
  let right = structs[pos];
  let left = structs[pos - 1];
  let i3 = pos;
  for (; i3 > 0; right = left, left = structs[--i3 - 1]) {
    if (left.deleted === right.deleted && left.constructor === right.constructor) {
      if (left.mergeWith(right)) {
        if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType<any>} */
        right.parent._map.get(right.parentSub) === right) {
          right.parent._map.set(
            right.parentSub,
            /** @type {Item} */
            left
          );
        }
        continue;
      }
    }
    break;
  }
  const merged = pos - i3;
  if (merged) {
    structs.splice(pos + 1 - merged, merged);
  }
  return merged;
};
var tryGcDeleteSet = (ds, store, gcFilter) => {
  for (const [client, deleteItems] of ds.clients.entries()) {
    const structs = (
      /** @type {Array<GC|Item>} */
      store.clients.get(client)
    );
    for (let di2 = deleteItems.length - 1; di2 >= 0; di2--) {
      const deleteItem = deleteItems[di2];
      const endDeleteItemClock = deleteItem.clock + deleteItem.len;
      for (let si2 = findIndexSS(structs, deleteItem.clock), struct = structs[si2]; si2 < structs.length && struct.id.clock < endDeleteItemClock; struct = structs[++si2]) {
        const struct2 = structs[si2];
        if (deleteItem.clock + deleteItem.len <= struct2.id.clock) {
          break;
        }
        if (struct2 instanceof Item && struct2.deleted && !struct2.keep && gcFilter(struct2)) {
          struct2.gc(store, false);
        }
      }
    }
  }
};
var tryMergeDeleteSet = (ds, store) => {
  ds.clients.forEach((deleteItems, client) => {
    const structs = (
      /** @type {Array<GC|Item>} */
      store.clients.get(client)
    );
    for (let di2 = deleteItems.length - 1; di2 >= 0; di2--) {
      const deleteItem = deleteItems[di2];
      const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1));
      for (let si2 = mostRightIndexToCheck, struct = structs[si2]; si2 > 0 && struct.id.clock >= deleteItem.clock; struct = structs[si2]) {
        si2 -= 1 + tryToMergeWithLefts(structs, si2);
      }
    }
  });
};
var cleanupTransactions = (transactionCleanups, i3) => {
  if (i3 < transactionCleanups.length) {
    const transaction = transactionCleanups[i3];
    const doc4 = transaction.doc;
    const store = doc4.store;
    const ds = transaction.deleteSet;
    const mergeStructs = transaction._mergeStructs;
    try {
      sortAndMergeDeleteSet(ds);
      transaction.afterState = getStateVector(transaction.doc.store);
      doc4.emit("beforeObserverCalls", [transaction, doc4]);
      const fs = [];
      transaction.changed.forEach(
        (subs, itemtype) => fs.push(() => {
          if (itemtype._item === null || !itemtype._item.deleted) {
            itemtype._callObserver(transaction, subs);
          }
        })
      );
      fs.push(() => {
        transaction.changedParentTypes.forEach((events, type) => {
          if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) {
            events = events.filter(
              (event) => event.target._item === null || !event.target._item.deleted
            );
            events.forEach((event) => {
              event.currentTarget = type;
              event._path = null;
            });
            events.sort((event1, event2) => event1.path.length - event2.path.length);
            callEventHandlerListeners(type._dEH, events, transaction);
          }
        });
      });
      fs.push(() => doc4.emit("afterTransaction", [transaction, doc4]));
      callAll(fs, []);
      if (transaction._needFormattingCleanup) {
        cleanupYTextAfterTransaction(transaction);
      }
    } finally {
      if (doc4.gc) {
        tryGcDeleteSet(ds, store, doc4.gcFilter);
      }
      tryMergeDeleteSet(ds, store);
      transaction.afterState.forEach((clock, client) => {
        const beforeClock = transaction.beforeState.get(client) || 0;
        if (beforeClock !== clock) {
          const structs = (
            /** @type {Array<GC|Item>} */
            store.clients.get(client)
          );
          const firstChangePos = max(findIndexSS(structs, beforeClock), 1);
          for (let i4 = structs.length - 1; i4 >= firstChangePos; ) {
            i4 -= 1 + tryToMergeWithLefts(structs, i4);
          }
        }
      });
      for (let i4 = mergeStructs.length - 1; i4 >= 0; i4--) {
        const { client, clock } = mergeStructs[i4].id;
        const structs = (
          /** @type {Array<GC|Item>} */
          store.clients.get(client)
        );
        const replacedStructPos = findIndexSS(structs, clock);
        if (replacedStructPos + 1 < structs.length) {
          if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) {
            continue;
          }
        }
        if (replacedStructPos > 0) {
          tryToMergeWithLefts(structs, replacedStructPos);
        }
      }
      if (!transaction.local && transaction.afterState.get(doc4.clientID) !== transaction.beforeState.get(doc4.clientID)) {
        print(ORANGE, BOLD, "[yjs] ", UNBOLD, RED, "Changed the client-id because another client seems to be using it.");
        doc4.clientID = generateNewClientId();
      }
      doc4.emit("afterTransactionCleanup", [transaction, doc4]);
      if (doc4._observers.has("update")) {
        const encoder = new UpdateEncoderV1();
        const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction);
        if (hasContent2) {
          doc4.emit("update", [encoder.toUint8Array(), transaction.origin, doc4, transaction]);
        }
      }
      if (doc4._observers.has("updateV2")) {
        const encoder = new UpdateEncoderV2();
        const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction);
        if (hasContent2) {
          doc4.emit("updateV2", [encoder.toUint8Array(), transaction.origin, doc4, transaction]);
        }
      }
      const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction;
      if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) {
        subdocsAdded.forEach((subdoc) => {
          subdoc.clientID = doc4.clientID;
          if (subdoc.collectionid == null) {
            subdoc.collectionid = doc4.collectionid;
          }
          doc4.subdocs.add(subdoc);
        });
        subdocsRemoved.forEach((subdoc) => doc4.subdocs.delete(subdoc));
        doc4.emit("subdocs", [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc4, transaction]);
        subdocsRemoved.forEach((subdoc) => subdoc.destroy());
      }
      if (transactionCleanups.length <= i3 + 1) {
        doc4._transactionCleanups = [];
        doc4.emit("afterAllTransactions", [doc4, transactionCleanups]);
      } else {
        cleanupTransactions(transactionCleanups, i3 + 1);
      }
    }
  }
};
var transact = (doc4, f6, origin = null, local = true) => {
  const transactionCleanups = doc4._transactionCleanups;
  let initialCall = false;
  let result = null;
  if (doc4._transaction === null) {
    initialCall = true;
    doc4._transaction = new Transaction2(doc4, origin, local);
    transactionCleanups.push(doc4._transaction);
    if (transactionCleanups.length === 1) {
      doc4.emit("beforeAllTransactions", [doc4]);
    }
    doc4.emit("beforeTransaction", [doc4._transaction, doc4]);
  }
  try {
    result = f6(doc4._transaction);
  } finally {
    if (initialCall) {
      const finishCleanup = doc4._transaction === transactionCleanups[0];
      doc4._transaction = null;
      if (finishCleanup) {
        cleanupTransactions(transactionCleanups, 0);
      }
    }
  }
  return result;
};
var StackItem = class {
  /**
   * @param {DeleteSet} deletions
   * @param {DeleteSet} insertions
   */
  constructor(deletions, insertions) {
    this.insertions = insertions;
    this.deletions = deletions;
    this.meta = /* @__PURE__ */ new Map();
  }
};
var clearUndoManagerStackItem = (tr4, um, stackItem) => {
  iterateDeletedStructs(tr4, stackItem.deletions, (item) => {
    if (item instanceof Item && um.scope.some((type) => type === tr4.doc || isParentOf(
      /** @type {AbstractType<any>} */
      type,
      item
    ))) {
      keepItem(item, false);
    }
  });
};
var popStackItem = (undoManager, stack, eventType) => {
  let _tr = null;
  const doc4 = undoManager.doc;
  const scope = undoManager.scope;
  transact(doc4, (transaction) => {
    while (stack.length > 0 && undoManager.currStackItem === null) {
      const store = doc4.store;
      const stackItem = (
        /** @type {StackItem} */
        stack.pop()
      );
      const itemsToRedo = /* @__PURE__ */ new Set();
      const itemsToDelete = [];
      let performedChange = false;
      iterateDeletedStructs(transaction, stackItem.insertions, (struct) => {
        if (struct instanceof Item) {
          if (struct.redone !== null) {
            let { item, diff } = followRedone(store, struct.id);
            if (diff > 0) {
              item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff));
            }
            struct = item;
          }
          if (!struct.deleted && scope.some((type) => type === transaction.doc || isParentOf(
            /** @type {AbstractType<any>} */
            type,
            /** @type {Item} */
            struct
          ))) {
            itemsToDelete.push(struct);
          }
        }
      });
      iterateDeletedStructs(transaction, stackItem.deletions, (struct) => {
        if (struct instanceof Item && scope.some((type) => type === transaction.doc || isParentOf(
          /** @type {AbstractType<any>} */
          type,
          struct
        )) && // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.
        !isDeleted(stackItem.insertions, struct.id)) {
          itemsToRedo.add(struct);
        }
      });
      itemsToRedo.forEach((struct) => {
        performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager.ignoreRemoteMapChanges, undoManager) !== null || performedChange;
      });
      for (let i3 = itemsToDelete.length - 1; i3 >= 0; i3--) {
        const item = itemsToDelete[i3];
        if (undoManager.deleteFilter(item)) {
          item.delete(transaction);
          performedChange = true;
        }
      }
      undoManager.currStackItem = performedChange ? stackItem : null;
    }
    transaction.changed.forEach((subProps, type) => {
      if (subProps.has(null) && type._searchMarker) {
        type._searchMarker.length = 0;
      }
    });
    _tr = transaction;
  }, undoManager);
  const res = undoManager.currStackItem;
  if (res != null) {
    const changedParentTypes = _tr.changedParentTypes;
    undoManager.emit("stack-item-popped", [{ stackItem: res, type: eventType, changedParentTypes, origin: undoManager }, undoManager]);
    undoManager.currStackItem = null;
  }
  return res;
};
var UndoManager = class extends ObservableV2 {
  /**
   * @param {Doc|AbstractType<any>|Array<AbstractType<any>>} typeScope Limits the scope of the UndoManager. If this is set to a ydoc instance, all changes on that ydoc will be undone. If set to a specific type, only changes on that type or its children will be undone. Also accepts an array of types.
   * @param {UndoManagerOptions} options
   */
  constructor(typeScope, {
    captureTimeout = 500,
    captureTransaction = (_tr) => true,
    deleteFilter = () => true,
    trackedOrigins = /* @__PURE__ */ new Set([null]),
    ignoreRemoteMapChanges = false,
    doc: doc4 = (
      /** @type {Doc} */
      isArray(typeScope) ? typeScope[0].doc : typeScope instanceof Doc ? typeScope : typeScope.doc
    )
  } = {}) {
    super();
    this.scope = [];
    this.doc = doc4;
    this.addToScope(typeScope);
    this.deleteFilter = deleteFilter;
    trackedOrigins.add(this);
    this.trackedOrigins = trackedOrigins;
    this.captureTransaction = captureTransaction;
    this.undoStack = [];
    this.redoStack = [];
    this.undoing = false;
    this.redoing = false;
    this.currStackItem = null;
    this.lastChange = 0;
    this.ignoreRemoteMapChanges = ignoreRemoteMapChanges;
    this.captureTimeout = captureTimeout;
    this.afterTransactionHandler = (transaction) => {
      if (!this.captureTransaction(transaction) || !this.scope.some((type) => transaction.changedParentTypes.has(
        /** @type {AbstractType<any>} */
        type
      ) || type === this.doc) || !this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor))) {
        return;
      }
      const undoing = this.undoing;
      const redoing = this.redoing;
      const stack = undoing ? this.redoStack : this.undoStack;
      if (undoing) {
        this.stopCapturing();
      } else if (!redoing) {
        this.clear(false, true);
      }
      const insertions = new DeleteSet();
      transaction.afterState.forEach((endClock, client) => {
        const startClock = transaction.beforeState.get(client) || 0;
        const len = endClock - startClock;
        if (len > 0) {
          addToDeleteSet(insertions, client, startClock, len);
        }
      });
      const now = getUnixTime();
      let didAdd = false;
      if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) {
        const lastOp = stack[stack.length - 1];
        lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet]);
        lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions]);
      } else {
        stack.push(new StackItem(transaction.deleteSet, insertions));
        didAdd = true;
      }
      if (!undoing && !redoing) {
        this.lastChange = now;
      }
      iterateDeletedStructs(
        transaction,
        transaction.deleteSet,
        /** @param {Item|GC} item */
        (item) => {
          if (item instanceof Item && this.scope.some((type) => type === transaction.doc || isParentOf(
            /** @type {AbstractType<any>} */
            type,
            item
          ))) {
            keepItem(item, true);
          }
        }
      );
      const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? "redo" : "undo", changedParentTypes: transaction.changedParentTypes }, this];
      if (didAdd) {
        this.emit("stack-item-added", changeEvent);
      } else {
        this.emit("stack-item-updated", changeEvent);
      }
    };
    this.doc.on("afterTransaction", this.afterTransactionHandler);
    this.doc.on("destroy", () => {
      this.destroy();
    });
  }
  /**
   * Extend the scope.
   *
   * @param {Array<AbstractType<any> | Doc> | AbstractType<any> | Doc} ytypes
   */
  addToScope(ytypes) {
    const tmpSet = new Set(this.scope);
    ytypes = isArray(ytypes) ? ytypes : [ytypes];
    ytypes.forEach((ytype) => {
      if (!tmpSet.has(ytype)) {
        tmpSet.add(ytype);
        if (ytype instanceof AbstractType ? ytype.doc !== this.doc : ytype !== this.doc) warn("[yjs#509] Not same Y.Doc");
        this.scope.push(ytype);
      }
    });
  }
  /**
   * @param {any} origin
   */
  addTrackedOrigin(origin) {
    this.trackedOrigins.add(origin);
  }
  /**
   * @param {any} origin
   */
  removeTrackedOrigin(origin) {
    this.trackedOrigins.delete(origin);
  }
  clear(clearUndoStack = true, clearRedoStack = true) {
    if (clearUndoStack && this.canUndo() || clearRedoStack && this.canRedo()) {
      this.doc.transact((tr4) => {
        if (clearUndoStack) {
          this.undoStack.forEach((item) => clearUndoManagerStackItem(tr4, this, item));
          this.undoStack = [];
        }
        if (clearRedoStack) {
          this.redoStack.forEach((item) => clearUndoManagerStackItem(tr4, this, item));
          this.redoStack = [];
        }
        this.emit("stack-cleared", [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }]);
      });
    }
  }
  /**
   * UndoManager merges Undo-StackItem if they are created within time-gap
   * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next
   * StackItem won't be merged.
   *
   *
   * @example
   *     // without stopCapturing
   *     ytext.insert(0, 'a')
   *     ytext.insert(1, 'b')
   *     um.undo()
   *     ytext.toString() // => '' (note that 'ab' was removed)
   *     // with stopCapturing
   *     ytext.insert(0, 'a')
   *     um.stopCapturing()
   *     ytext.insert(0, 'b')
   *     um.undo()
   *     ytext.toString() // => 'a' (note that only 'b' was removed)
   *
   */
  stopCapturing() {
    this.lastChange = 0;
  }
  /**
   * Undo last changes on type.
   *
   * @return {StackItem?} Returns StackItem if a change was applied
   */
  undo() {
    this.undoing = true;
    let res;
    try {
      res = popStackItem(this, this.undoStack, "undo");
    } finally {
      this.undoing = false;
    }
    return res;
  }
  /**
   * Redo last undo operation.
   *
   * @return {StackItem?} Returns StackItem if a change was applied
   */
  redo() {
    this.redoing = true;
    let res;
    try {
      res = popStackItem(this, this.redoStack, "redo");
    } finally {
      this.redoing = false;
    }
    return res;
  }
  /**
   * Are undo steps available?
   *
   * @return {boolean} `true` if undo is possible
   */
  canUndo() {
    return this.undoStack.length > 0;
  }
  /**
   * Are redo steps available?
   *
   * @return {boolean} `true` if redo is possible
   */
  canRedo() {
    return this.redoStack.length > 0;
  }
  destroy() {
    this.trackedOrigins.delete(this);
    this.doc.off("afterTransaction", this.afterTransactionHandler);
    super.destroy();
  }
};
function* lazyStructReaderGenerator(decoder) {
  const numOfStateUpdates = readVarUint(decoder.restDecoder);
  for (let i3 = 0; i3 < numOfStateUpdates; i3++) {
    const numberOfStructs = readVarUint(decoder.restDecoder);
    const client = decoder.readClient();
    let clock = readVarUint(decoder.restDecoder);
    for (let i4 = 0; i4 < numberOfStructs; i4++) {
      const info = decoder.readInfo();
      if (info === 10) {
        const len = readVarUint(decoder.restDecoder);
        yield new Skip(createID(client, clock), len);
        clock += len;
      } else if ((BITS5 & info) !== 0) {
        const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;
        const struct = new Item(
          createID(client, clock),
          null,
          // left
          (info & BIT8) === BIT8 ? decoder.readLeftID() : null,
          // origin
          null,
          // right
          (info & BIT7) === BIT7 ? decoder.readRightID() : null,
          // right origin
          // @ts-ignore Force writing a string here.
          cantCopyParentInfo ? decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID() : null,
          // parent
          cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null,
          // parentSub
          readItemContent(decoder, info)
          // item content
        );
        yield struct;
        clock += struct.length;
      } else {
        const len = decoder.readLen();
        yield new GC(createID(client, clock), len);
        clock += len;
      }
    }
  }
}
var LazyStructReader = class {
  /**
   * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder
   * @param {boolean} filterSkips
   */
  constructor(decoder, filterSkips) {
    this.gen = lazyStructReaderGenerator(decoder);
    this.curr = null;
    this.done = false;
    this.filterSkips = filterSkips;
    this.next();
  }
  /**
   * @return {Item | GC | Skip |null}
   */
  next() {
    do {
      this.curr = this.gen.next().value || null;
    } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip);
    return this.curr;
  }
};
var LazyStructWriter = class {
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  constructor(encoder) {
    this.currClient = 0;
    this.startClock = 0;
    this.written = 0;
    this.encoder = encoder;
    this.clientStructs = [];
  }
};
var mergeUpdates = (updates) => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1);
var sliceStruct = (left, diff) => {
  if (left.constructor === GC) {
    const { client, clock } = left.id;
    return new GC(createID(client, clock + diff), left.length - diff);
  } else if (left.constructor === Skip) {
    const { client, clock } = left.id;
    return new Skip(createID(client, clock + diff), left.length - diff);
  } else {
    const leftItem = (
      /** @type {Item} */
      left
    );
    const { client, clock } = leftItem.id;
    return new Item(
      createID(client, clock + diff),
      null,
      createID(client, clock + diff - 1),
      null,
      leftItem.rightOrigin,
      leftItem.parent,
      leftItem.parentSub,
      leftItem.content.splice(diff)
    );
  }
};
var mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
  if (updates.length === 1) {
    return updates[0];
  }
  const updateDecoders = updates.map((update) => new YDecoder(createDecoder(update)));
  let lazyStructDecoders = updateDecoders.map((decoder) => new LazyStructReader(decoder, true));
  let currWrite = null;
  const updateEncoder = new YEncoder();
  const lazyStructEncoder = new LazyStructWriter(updateEncoder);
  while (true) {
    lazyStructDecoders = lazyStructDecoders.filter((dec) => dec.curr !== null);
    lazyStructDecoders.sort(
      /** @type {function(any,any):number} */
      (dec1, dec2) => {
        if (dec1.curr.id.client === dec2.curr.id.client) {
          const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock;
          if (clockDiff === 0) {
            return dec1.curr.constructor === dec2.curr.constructor ? 0 : dec1.curr.constructor === Skip ? 1 : -1;
          } else {
            return clockDiff;
          }
        } else {
          return dec2.curr.id.client - dec1.curr.id.client;
        }
      }
    );
    if (lazyStructDecoders.length === 0) {
      break;
    }
    const currDecoder = lazyStructDecoders[0];
    const firstClient = (
      /** @type {Item | GC} */
      currDecoder.curr.id.client
    );
    if (currWrite !== null) {
      let curr = (
        /** @type {Item | GC | null} */
        currDecoder.curr
      );
      let iterated = false;
      while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) {
        curr = currDecoder.next();
        iterated = true;
      }
      if (curr === null || // current decoder is empty
      curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient`
      iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) {
        continue;
      }
      if (firstClient !== currWrite.struct.id.client) {
        writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
        currWrite = { struct: curr, offset: 0 };
        currDecoder.next();
      } else {
        if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) {
          if (currWrite.struct.constructor === Skip) {
            currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock;
          } else {
            writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
            const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length;
            const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff);
            currWrite = { struct, offset: 0 };
          }
        } else {
          const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock;
          if (diff > 0) {
            if (currWrite.struct.constructor === Skip) {
              currWrite.struct.length -= diff;
            } else {
              curr = sliceStruct(curr, diff);
            }
          }
          if (!currWrite.struct.mergeWith(
            /** @type {any} */
            curr
          )) {
            writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
            currWrite = { struct: curr, offset: 0 };
            currDecoder.next();
          }
        }
      }
    } else {
      currWrite = { struct: (
        /** @type {Item | GC} */
        currDecoder.curr
      ), offset: 0 };
      currDecoder.next();
    }
    for (let next2 = currDecoder.curr; next2 !== null && next2.id.client === firstClient && next2.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next2.constructor !== Skip; next2 = currDecoder.next()) {
      writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
      currWrite = { struct: next2, offset: 0 };
    }
  }
  if (currWrite !== null) {
    writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
    currWrite = null;
  }
  finishLazyStructWriting(lazyStructEncoder);
  const dss = updateDecoders.map((decoder) => readDeleteSet(decoder));
  const ds = mergeDeleteSets(dss);
  writeDeleteSet(updateEncoder, ds);
  return updateEncoder.toUint8Array();
};
var diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
  const state = decodeStateVector(sv);
  const encoder = new YEncoder();
  const lazyStructWriter = new LazyStructWriter(encoder);
  const decoder = new YDecoder(createDecoder(update));
  const reader = new LazyStructReader(decoder, false);
  while (reader.curr) {
    const curr = reader.curr;
    const currClient = curr.id.client;
    const svClock = state.get(currClient) || 0;
    if (reader.curr.constructor === Skip) {
      reader.next();
      continue;
    }
    if (curr.id.clock + curr.length > svClock) {
      writeStructToLazyStructWriter(lazyStructWriter, curr, max(svClock - curr.id.clock, 0));
      reader.next();
      while (reader.curr && reader.curr.id.client === currClient) {
        writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0);
        reader.next();
      }
    } else {
      while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) {
        reader.next();
      }
    }
  }
  finishLazyStructWriting(lazyStructWriter);
  const ds = readDeleteSet(decoder);
  writeDeleteSet(encoder, ds);
  return encoder.toUint8Array();
};
var flushLazyStructWriter = (lazyWriter) => {
  if (lazyWriter.written > 0) {
    lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) });
    lazyWriter.encoder.restEncoder = createEncoder();
    lazyWriter.written = 0;
  }
};
var writeStructToLazyStructWriter = (lazyWriter, struct, offset4) => {
  if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) {
    flushLazyStructWriter(lazyWriter);
  }
  if (lazyWriter.written === 0) {
    lazyWriter.currClient = struct.id.client;
    lazyWriter.encoder.writeClient(struct.id.client);
    writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset4);
  }
  struct.write(lazyWriter.encoder, offset4);
  lazyWriter.written++;
};
var finishLazyStructWriting = (lazyWriter) => {
  flushLazyStructWriter(lazyWriter);
  const restEncoder = lazyWriter.encoder.restEncoder;
  writeVarUint(restEncoder, lazyWriter.clientStructs.length);
  for (let i3 = 0; i3 < lazyWriter.clientStructs.length; i3++) {
    const partStructs = lazyWriter.clientStructs[i3];
    writeVarUint(restEncoder, partStructs.written);
    writeUint8Array(restEncoder, partStructs.restEncoder);
  }
};
var convertUpdateFormat = (update, blockTransformer, YDecoder, YEncoder) => {
  const updateDecoder = new YDecoder(createDecoder(update));
  const lazyDecoder = new LazyStructReader(updateDecoder, false);
  const updateEncoder = new YEncoder();
  const lazyWriter = new LazyStructWriter(updateEncoder);
  for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {
    writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0);
  }
  finishLazyStructWriting(lazyWriter);
  const ds = readDeleteSet(updateDecoder);
  writeDeleteSet(updateEncoder, ds);
  return updateEncoder.toUint8Array();
};
var convertUpdateFormatV2ToV1 = (update) => convertUpdateFormat(update, id, UpdateDecoderV2, UpdateEncoderV1);
var errorComputeChanges = "You must not compute changes after the event-handler fired.";
var YEvent = class {
  /**
   * @param {T} target The changed type.
   * @param {Transaction} transaction
   */
  constructor(target, transaction) {
    this.target = target;
    this.currentTarget = target;
    this.transaction = transaction;
    this._changes = null;
    this._keys = null;
    this._delta = null;
    this._path = null;
  }
  /**
   * Computes the path from `y` to the changed type.
   *
   * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with.
   *
   * The following property holds:
   * @example
   *   let type = y
   *   event.path.forEach(dir => {
   *     type = type.get(dir)
   *   })
   *   type === event.target // => true
   */
  get path() {
    return this._path || (this._path = getPathTo(this.currentTarget, this.target));
  }
  /**
   * Check if a struct is deleted by this event.
   *
   * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.
   *
   * @param {AbstractStruct} struct
   * @return {boolean}
   */
  deletes(struct) {
    return isDeleted(this.transaction.deleteSet, struct.id);
  }
  /**
   * @type {Map<string, { action: 'add' | 'update' | 'delete', oldValue: any }>}
   */
  get keys() {
    if (this._keys === null) {
      if (this.transaction.doc._transactionCleanups.length === 0) {
        throw create3(errorComputeChanges);
      }
      const keys5 = /* @__PURE__ */ new Map();
      const target = this.target;
      const changed = (
        /** @type Set<string|null> */
        this.transaction.changed.get(target)
      );
      changed.forEach((key2) => {
        if (key2 !== null) {
          const item = (
            /** @type {Item} */
            target._map.get(key2)
          );
          let action;
          let oldValue;
          if (this.adds(item)) {
            let prev = item.left;
            while (prev !== null && this.adds(prev)) {
              prev = prev.left;
            }
            if (this.deletes(item)) {
              if (prev !== null && this.deletes(prev)) {
                action = "delete";
                oldValue = last(prev.content.getContent());
              } else {
                return;
              }
            } else {
              if (prev !== null && this.deletes(prev)) {
                action = "update";
                oldValue = last(prev.content.getContent());
              } else {
                action = "add";
                oldValue = void 0;
              }
            }
          } else {
            if (this.deletes(item)) {
              action = "delete";
              oldValue = last(
                /** @type {Item} */
                item.content.getContent()
              );
            } else {
              return;
            }
          }
          keys5.set(key2, { action, oldValue });
        }
      });
      this._keys = keys5;
    }
    return this._keys;
  }
  /**
   * This is a computed property. Note that this can only be safely computed during the
   * event call. Computing this property after other changes happened might result in
   * unexpected behavior (incorrect computation of deltas). A safe way to collect changes
   * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.
   *
   * @type {Array<{insert?: string | Array<any> | object | AbstractType<any>, retain?: number, delete?: number, attributes?: Object<string, any>}>}
   */
  get delta() {
    return this.changes.delta;
  }
  /**
   * Check if a struct is added by this event.
   *
   * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.
   *
   * @param {AbstractStruct} struct
   * @return {boolean}
   */
  adds(struct) {
    return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0);
  }
  /**
   * This is a computed property. Note that this can only be safely computed during the
   * event call. Computing this property after other changes happened might result in
   * unexpected behavior (incorrect computation of deltas). A safe way to collect changes
   * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.
   *
   * @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}>}}
   */
  get changes() {
    let changes = this._changes;
    if (changes === null) {
      if (this.transaction.doc._transactionCleanups.length === 0) {
        throw create3(errorComputeChanges);
      }
      const target = this.target;
      const added = create2();
      const deleted = create2();
      const delta = [];
      changes = {
        added,
        deleted,
        delta,
        keys: this.keys
      };
      const changed = (
        /** @type Set<string|null> */
        this.transaction.changed.get(target)
      );
      if (changed.has(null)) {
        let lastOp = null;
        const packOp = () => {
          if (lastOp) {
            delta.push(lastOp);
          }
        };
        for (let item = target._start; item !== null; item = item.right) {
          if (item.deleted) {
            if (this.deletes(item) && !this.adds(item)) {
              if (lastOp === null || lastOp.delete === void 0) {
                packOp();
                lastOp = { delete: 0 };
              }
              lastOp.delete += item.length;
              deleted.add(item);
            }
          } else {
            if (this.adds(item)) {
              if (lastOp === null || lastOp.insert === void 0) {
                packOp();
                lastOp = { insert: [] };
              }
              lastOp.insert = lastOp.insert.concat(item.content.getContent());
              added.add(item);
            } else {
              if (lastOp === null || lastOp.retain === void 0) {
                packOp();
                lastOp = { retain: 0 };
              }
              lastOp.retain += item.length;
            }
          }
        }
        if (lastOp !== null && lastOp.retain === void 0) {
          packOp();
        }
      }
      this._changes = changes;
    }
    return (
      /** @type {any} */
      changes
    );
  }
};
var getPathTo = (parent, child) => {
  const path2 = [];
  while (child._item !== null && child !== parent) {
    if (child._item.parentSub !== null) {
      path2.unshift(child._item.parentSub);
    } else {
      let i3 = 0;
      let c3 = (
        /** @type {AbstractType<any>} */
        child._item.parent._start
      );
      while (c3 !== child._item && c3 !== null) {
        if (!c3.deleted && c3.countable) {
          i3 += c3.length;
        }
        c3 = c3.right;
      }
      path2.unshift(i3);
    }
    child = /** @type {AbstractType<any>} */
    child._item.parent;
  }
  return path2;
};
var warnPrematureAccess = () => {
  warn("Invalid access: Add Yjs type to a document before reading data.");
};
var maxSearchMarker = 80;
var globalSearchMarkerTimestamp = 0;
var ArraySearchMarker = class {
  /**
   * @param {Item} p
   * @param {number} index
   */
  constructor(p4, index4) {
    p4.marker = true;
    this.p = p4;
    this.index = index4;
    this.timestamp = globalSearchMarkerTimestamp++;
  }
};
var refreshMarkerTimestamp = (marker) => {
  marker.timestamp = globalSearchMarkerTimestamp++;
};
var overwriteMarker = (marker, p4, index4) => {
  marker.p.marker = false;
  marker.p = p4;
  p4.marker = true;
  marker.index = index4;
  marker.timestamp = globalSearchMarkerTimestamp++;
};
var markPosition = (searchMarker, p4, index4) => {
  if (searchMarker.length >= maxSearchMarker) {
    const marker = searchMarker.reduce((a3, b4) => a3.timestamp < b4.timestamp ? a3 : b4);
    overwriteMarker(marker, p4, index4);
    return marker;
  } else {
    const pm = new ArraySearchMarker(p4, index4);
    searchMarker.push(pm);
    return pm;
  }
};
var findMarker = (yarray, index4) => {
  if (yarray._start === null || index4 === 0 || yarray._searchMarker === null) {
    return null;
  }
  const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a3, b4) => abs(index4 - a3.index) < abs(index4 - b4.index) ? a3 : b4);
  let p4 = yarray._start;
  let pindex = 0;
  if (marker !== null) {
    p4 = marker.p;
    pindex = marker.index;
    refreshMarkerTimestamp(marker);
  }
  while (p4.right !== null && pindex < index4) {
    if (!p4.deleted && p4.countable) {
      if (index4 < pindex + p4.length) {
        break;
      }
      pindex += p4.length;
    }
    p4 = p4.right;
  }
  while (p4.left !== null && pindex > index4) {
    p4 = p4.left;
    if (!p4.deleted && p4.countable) {
      pindex -= p4.length;
    }
  }
  while (p4.left !== null && p4.left.id.client === p4.id.client && p4.left.id.clock + p4.left.length === p4.id.clock) {
    p4 = p4.left;
    if (!p4.deleted && p4.countable) {
      pindex -= p4.length;
    }
  }
  if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray<any>} */
  p4.parent.length / maxSearchMarker) {
    overwriteMarker(marker, p4, pindex);
    return marker;
  } else {
    return markPosition(yarray._searchMarker, p4, pindex);
  }
};
var updateMarkerChanges = (searchMarker, index4, len) => {
  for (let i3 = searchMarker.length - 1; i3 >= 0; i3--) {
    const m2 = searchMarker[i3];
    if (len > 0) {
      let p4 = m2.p;
      p4.marker = false;
      while (p4 && (p4.deleted || !p4.countable)) {
        p4 = p4.left;
        if (p4 && !p4.deleted && p4.countable) {
          m2.index -= p4.length;
        }
      }
      if (p4 === null || p4.marker === true) {
        searchMarker.splice(i3, 1);
        continue;
      }
      m2.p = p4;
      p4.marker = true;
    }
    if (index4 < m2.index || len > 0 && index4 === m2.index) {
      m2.index = max(index4, m2.index + len);
    }
  }
};
var callTypeObservers = (type, transaction, event) => {
  const changedType = type;
  const changedParentTypes = transaction.changedParentTypes;
  while (true) {
    setIfUndefined(changedParentTypes, type, () => []).push(event);
    if (type._item === null) {
      break;
    }
    type = /** @type {AbstractType<any>} */
    type._item.parent;
  }
  callEventHandlerListeners(changedType._eH, event, transaction);
};
var AbstractType = class {
  constructor() {
    this._item = null;
    this._map = /* @__PURE__ */ new Map();
    this._start = null;
    this.doc = null;
    this._length = 0;
    this._eH = createEventHandler();
    this._dEH = createEventHandler();
    this._searchMarker = null;
  }
  /**
   * @return {AbstractType<any>|null}
   */
  get parent() {
    return this._item ? (
      /** @type {AbstractType<any>} */
      this._item.parent
    ) : null;
  }
  /**
   * Integrate this type into the Yjs instance.
   *
   * * Save this struct in the os
   * * This type is sent to other client
   * * Observer functions are fired
   *
   * @param {Doc} y The Yjs instance
   * @param {Item|null} item
   */
  _integrate(y3, item) {
    this.doc = y3;
    this._item = item;
  }
  /**
   * @return {AbstractType<EventType>}
   */
  _copy() {
    throw methodUnimplemented();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {AbstractType<EventType>}
   */
  clone() {
    throw methodUnimplemented();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder
   */
  _write(_encoder) {
  }
  /**
   * The first non-deleted item
   */
  get _first() {
    let n = this._start;
    while (n !== null && n.deleted) {
      n = n.right;
    }
    return n;
  }
  /**
   * Creates YEvent and calls all type observers.
   * Must be implemented by each type.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} _parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(transaction, _parentSubs) {
    if (!transaction.local && this._searchMarker) {
      this._searchMarker.length = 0;
    }
  }
  /**
   * Observe all events that are created on this type.
   *
   * @param {function(EventType, Transaction):void} f Observer function
   */
  observe(f6) {
    addEventHandlerListener(this._eH, f6);
  }
  /**
   * Observe all events that are created by this type and its children.
   *
   * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function
   */
  observeDeep(f6) {
    addEventHandlerListener(this._dEH, f6);
  }
  /**
   * Unregister an observer function.
   *
   * @param {function(EventType,Transaction):void} f Observer function
   */
  unobserve(f6) {
    removeEventHandlerListener(this._eH, f6);
  }
  /**
   * Unregister an observer function.
   *
   * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function
   */
  unobserveDeep(f6) {
    removeEventHandlerListener(this._dEH, f6);
  }
  /**
   * @abstract
   * @return {any}
   */
  toJSON() {
  }
};
var typeListSlice = (type, start, end) => {
  type.doc ?? warnPrematureAccess();
  if (start < 0) {
    start = type._length + start;
  }
  if (end < 0) {
    end = type._length + end;
  }
  let len = end - start;
  const cs = [];
  let n = type._start;
  while (n !== null && len > 0) {
    if (n.countable && !n.deleted) {
      const c3 = n.content.getContent();
      if (c3.length <= start) {
        start -= c3.length;
      } else {
        for (let i3 = start; i3 < c3.length && len > 0; i3++) {
          cs.push(c3[i3]);
          len--;
        }
        start = 0;
      }
    }
    n = n.right;
  }
  return cs;
};
var typeListToArray = (type) => {
  type.doc ?? warnPrematureAccess();
  const cs = [];
  let n = type._start;
  while (n !== null) {
    if (n.countable && !n.deleted) {
      const c3 = n.content.getContent();
      for (let i3 = 0; i3 < c3.length; i3++) {
        cs.push(c3[i3]);
      }
    }
    n = n.right;
  }
  return cs;
};
var typeListToArraySnapshot = (type, snapshot2) => {
  const cs = [];
  let n = type._start;
  while (n !== null) {
    if (n.countable && isVisible(n, snapshot2)) {
      const c3 = n.content.getContent();
      for (let i3 = 0; i3 < c3.length; i3++) {
        cs.push(c3[i3]);
      }
    }
    n = n.right;
  }
  return cs;
};
var typeListForEach = (type, f6) => {
  let index4 = 0;
  let n = type._start;
  type.doc ?? warnPrematureAccess();
  while (n !== null) {
    if (n.countable && !n.deleted) {
      const c3 = n.content.getContent();
      for (let i3 = 0; i3 < c3.length; i3++) {
        f6(c3[i3], index4++, type);
      }
    }
    n = n.right;
  }
};
var typeListMap = (type, f6) => {
  const result = [];
  typeListForEach(type, (c3, i3) => {
    result.push(f6(c3, i3, type));
  });
  return result;
};
var typeListCreateIterator = (type) => {
  let n = type._start;
  let currentContent = null;
  let currentContentIndex = 0;
  return {
    [Symbol.iterator]() {
      return this;
    },
    next: () => {
      if (currentContent === null) {
        while (n !== null && n.deleted) {
          n = n.right;
        }
        if (n === null) {
          return {
            done: true,
            value: void 0
          };
        }
        currentContent = n.content.getContent();
        currentContentIndex = 0;
        n = n.right;
      }
      const value = currentContent[currentContentIndex++];
      if (currentContent.length <= currentContentIndex) {
        currentContent = null;
      }
      return {
        done: false,
        value
      };
    }
  };
};
var typeListGet = (type, index4) => {
  type.doc ?? warnPrematureAccess();
  const marker = findMarker(type, index4);
  let n = type._start;
  if (marker !== null) {
    n = marker.p;
    index4 -= marker.index;
  }
  for (; n !== null; n = n.right) {
    if (!n.deleted && n.countable) {
      if (index4 < n.length) {
        return n.content.getContent()[index4];
      }
      index4 -= n.length;
    }
  }
};
var typeListInsertGenericsAfter = (transaction, parent, referenceItem, content5) => {
  let left = referenceItem;
  const doc4 = transaction.doc;
  const ownClientId = doc4.clientID;
  const store = doc4.store;
  const right = referenceItem === null ? parent._start : referenceItem.right;
  let jsonContent = [];
  const packJsonContent = () => {
    if (jsonContent.length > 0) {
      left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent));
      left.integrate(transaction, 0);
      jsonContent = [];
    }
  };
  content5.forEach((c3) => {
    if (c3 === null) {
      jsonContent.push(c3);
    } else {
      switch (c3.constructor) {
        case Number:
        case Object:
        case Boolean:
        case Array:
        case String:
          jsonContent.push(c3);
          break;
        default:
          packJsonContent();
          switch (c3.constructor) {
            case Uint8Array:
            case ArrayBuffer:
              left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(
                /** @type {Uint8Array} */
                c3
              )));
              left.integrate(transaction, 0);
              break;
            case Doc:
              left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(
                /** @type {Doc} */
                c3
              ));
              left.integrate(transaction, 0);
              break;
            default:
              if (c3 instanceof AbstractType) {
                left = new Item(createID(ownClientId, getState(store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c3));
                left.integrate(transaction, 0);
              } else {
                throw new Error("Unexpected content type in insert operation");
              }
          }
      }
    }
  });
  packJsonContent();
};
var lengthExceeded = () => create3("Length exceeded!");
var typeListInsertGenerics = (transaction, parent, index4, content5) => {
  if (index4 > parent._length) {
    throw lengthExceeded();
  }
  if (index4 === 0) {
    if (parent._searchMarker) {
      updateMarkerChanges(parent._searchMarker, index4, content5.length);
    }
    return typeListInsertGenericsAfter(transaction, parent, null, content5);
  }
  const startIndex = index4;
  const marker = findMarker(parent, index4);
  let n = parent._start;
  if (marker !== null) {
    n = marker.p;
    index4 -= marker.index;
    if (index4 === 0) {
      n = n.prev;
      index4 += n && n.countable && !n.deleted ? n.length : 0;
    }
  }
  for (; n !== null; n = n.right) {
    if (!n.deleted && n.countable) {
      if (index4 <= n.length) {
        if (index4 < n.length) {
          getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index4));
        }
        break;
      }
      index4 -= n.length;
    }
  }
  if (parent._searchMarker) {
    updateMarkerChanges(parent._searchMarker, startIndex, content5.length);
  }
  return typeListInsertGenericsAfter(transaction, parent, n, content5);
};
var typeListPushGenerics = (transaction, parent, content5) => {
  const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start });
  let n = marker.p;
  if (n) {
    while (n.right) {
      n = n.right;
    }
  }
  return typeListInsertGenericsAfter(transaction, parent, n, content5);
};
var typeListDelete = (transaction, parent, index4, length2) => {
  if (length2 === 0) {
    return;
  }
  const startIndex = index4;
  const startLength = length2;
  const marker = findMarker(parent, index4);
  let n = parent._start;
  if (marker !== null) {
    n = marker.p;
    index4 -= marker.index;
  }
  for (; n !== null && index4 > 0; n = n.right) {
    if (!n.deleted && n.countable) {
      if (index4 < n.length) {
        getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index4));
      }
      index4 -= n.length;
    }
  }
  while (length2 > 0 && n !== null) {
    if (!n.deleted) {
      if (length2 < n.length) {
        getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length2));
      }
      n.delete(transaction);
      length2 -= n.length;
    }
    n = n.right;
  }
  if (length2 > 0) {
    throw lengthExceeded();
  }
  if (parent._searchMarker) {
    updateMarkerChanges(
      parent._searchMarker,
      startIndex,
      -startLength + length2
      /* in case we remove the above exception */
    );
  }
};
var typeMapDelete = (transaction, parent, key2) => {
  const c3 = parent._map.get(key2);
  if (c3 !== void 0) {
    c3.delete(transaction);
  }
};
var typeMapSet = (transaction, parent, key2, value) => {
  const left = parent._map.get(key2) || null;
  const doc4 = transaction.doc;
  const ownClientId = doc4.clientID;
  let content5;
  if (value == null) {
    content5 = new ContentAny([value]);
  } else {
    switch (value.constructor) {
      case Number:
      case Object:
      case Boolean:
      case Array:
      case String:
      case Date:
      case BigInt:
        content5 = new ContentAny([value]);
        break;
      case Uint8Array:
        content5 = new ContentBinary(
          /** @type {Uint8Array} */
          value
        );
        break;
      case Doc:
        content5 = new ContentDoc(
          /** @type {Doc} */
          value
        );
        break;
      default:
        if (value instanceof AbstractType) {
          content5 = new ContentType(value);
        } else {
          throw new Error("Unexpected content type");
        }
    }
  }
  new Item(createID(ownClientId, getState(doc4.store, ownClientId)), left, left && left.lastId, null, null, parent, key2, content5).integrate(transaction, 0);
};
var typeMapGet = (parent, key2) => {
  parent.doc ?? warnPrematureAccess();
  const val = parent._map.get(key2);
  return val !== void 0 && !val.deleted ? val.content.getContent()[val.length - 1] : void 0;
};
var typeMapGetAll = (parent) => {
  const res = {};
  parent.doc ?? warnPrematureAccess();
  parent._map.forEach((value, key2) => {
    if (!value.deleted) {
      res[key2] = value.content.getContent()[value.length - 1];
    }
  });
  return res;
};
var typeMapHas = (parent, key2) => {
  parent.doc ?? warnPrematureAccess();
  const val = parent._map.get(key2);
  return val !== void 0 && !val.deleted;
};
var typeMapGetAllSnapshot = (parent, snapshot2) => {
  const res = {};
  parent._map.forEach((value, key2) => {
    let v8 = value;
    while (v8 !== null && (!snapshot2.sv.has(v8.id.client) || v8.id.clock >= (snapshot2.sv.get(v8.id.client) || 0))) {
      v8 = v8.left;
    }
    if (v8 !== null && isVisible(v8, snapshot2)) {
      res[key2] = v8.content.getContent()[v8.length - 1];
    }
  });
  return res;
};
var createMapIterator = (type) => {
  type.doc ?? warnPrematureAccess();
  return iteratorFilter(
    type._map.entries(),
    /** @param {any} entry */
    (entry) => !entry[1].deleted
  );
};
var YArrayEvent = class extends YEvent {
};
var YArray = class _YArray extends AbstractType {
  constructor() {
    super();
    this._prelimContent = [];
    this._searchMarker = [];
  }
  /**
   * Construct a new YArray containing the specified items.
   * @template {Object<string,any>|Array<any>|number|null|string|Uint8Array} T
   * @param {Array<T>} items
   * @return {YArray<T>}
   */
  static from(items) {
    const a3 = new _YArray();
    a3.push(items);
    return a3;
  }
  /**
   * Integrate this type into the Yjs instance.
   *
   * * Save this struct in the os
   * * This type is sent to other client
   * * Observer functions are fired
   *
   * @param {Doc} y The Yjs instance
   * @param {Item} item
   */
  _integrate(y3, item) {
    super._integrate(y3, item);
    this.insert(
      0,
      /** @type {Array<any>} */
      this._prelimContent
    );
    this._prelimContent = null;
  }
  /**
   * @return {YArray<T>}
   */
  _copy() {
    return new _YArray();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YArray<T>}
   */
  clone() {
    const arr = new _YArray();
    arr.insert(0, this.toArray().map(
      (el2) => el2 instanceof AbstractType ? (
        /** @type {typeof el} */
        el2.clone()
      ) : el2
    ));
    return arr;
  }
  get length() {
    this.doc ?? warnPrematureAccess();
    return this._length;
  }
  /**
   * Creates YArrayEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(transaction, parentSubs) {
    super._callObserver(transaction, parentSubs);
    callTypeObservers(this, transaction, new YArrayEvent(this, transaction));
  }
  /**
   * Inserts new content at an index.
   *
   * Important: This function expects an array of content. Not just a content
   * object. The reason for this "weirdness" is that inserting several elements
   * is very efficient when it is done as a single operation.
   *
   * @example
   *  // Insert character 'a' at position 0
   *  yarray.insert(0, ['a'])
   *  // Insert numbers 1, 2 at position 1
   *  yarray.insert(1, [1, 2])
   *
   * @param {number} index The index to insert content at.
   * @param {Array<T>} content The array of content
   */
  insert(index4, content5) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListInsertGenerics(
          transaction,
          this,
          index4,
          /** @type {any} */
          content5
        );
      });
    } else {
      this._prelimContent.splice(index4, 0, ...content5);
    }
  }
  /**
   * Appends content to this YArray.
   *
   * @param {Array<T>} content Array of content to append.
   *
   * @todo Use the following implementation in all types.
   */
  push(content5) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListPushGenerics(
          transaction,
          this,
          /** @type {any} */
          content5
        );
      });
    } else {
      this._prelimContent.push(...content5);
    }
  }
  /**
   * Prepends content to this YArray.
   *
   * @param {Array<T>} content Array of content to prepend.
   */
  unshift(content5) {
    this.insert(0, content5);
  }
  /**
   * Deletes elements starting from an index.
   *
   * @param {number} index Index at which to start deleting elements
   * @param {number} length The number of elements to remove. Defaults to 1.
   */
  delete(index4, length2 = 1) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListDelete(transaction, this, index4, length2);
      });
    } else {
      this._prelimContent.splice(index4, length2);
    }
  }
  /**
   * Returns the i-th element from a YArray.
   *
   * @param {number} index The index of the element to return from the YArray
   * @return {T}
   */
  get(index4) {
    return typeListGet(this, index4);
  }
  /**
   * Transforms this YArray to a JavaScript Array.
   *
   * @return {Array<T>}
   */
  toArray() {
    return typeListToArray(this);
  }
  /**
   * Returns a portion of this YArray into a JavaScript Array selected
   * from start to end (end not included).
   *
   * @param {number} [start]
   * @param {number} [end]
   * @return {Array<T>}
   */
  slice(start = 0, end = this.length) {
    return typeListSlice(this, start, end);
  }
  /**
   * Transforms this Shared Type to a JSON object.
   *
   * @return {Array<any>}
   */
  toJSON() {
    return this.map((c3) => c3 instanceof AbstractType ? c3.toJSON() : c3);
  }
  /**
   * Returns an Array with the result of calling a provided function on every
   * element of this YArray.
   *
   * @template M
   * @param {function(T,number,YArray<T>):M} f Function that produces an element of the new Array
   * @return {Array<M>} A new array with each element being the result of the
   *                 callback function
   */
  map(f6) {
    return typeListMap(
      this,
      /** @type {any} */
      f6
    );
  }
  /**
   * Executes a provided function once on every element of this YArray.
   *
   * @param {function(T,number,YArray<T>):void} f A function to execute on every element of this YArray.
   */
  forEach(f6) {
    typeListForEach(this, f6);
  }
  /**
   * @return {IterableIterator<T>}
   */
  [Symbol.iterator]() {
    return typeListCreateIterator(this);
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(encoder) {
    encoder.writeTypeRef(YArrayRefID);
  }
};
var readYArray = (_decoder) => new YArray();
var YMapEvent = class extends YEvent {
  /**
   * @param {YMap<T>} ymap The YArray that changed.
   * @param {Transaction} transaction
   * @param {Set<any>} subs The keys that changed.
   */
  constructor(ymap, transaction, subs) {
    super(ymap, transaction);
    this.keysChanged = subs;
  }
};
var YMap = class _YMap extends AbstractType {
  /**
   *
   * @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap
   */
  constructor(entries) {
    super();
    this._prelimContent = null;
    if (entries === void 0) {
      this._prelimContent = /* @__PURE__ */ new Map();
    } else {
      this._prelimContent = new Map(entries);
    }
  }
  /**
   * Integrate this type into the Yjs instance.
   *
   * * Save this struct in the os
   * * This type is sent to other client
   * * Observer functions are fired
   *
   * @param {Doc} y The Yjs instance
   * @param {Item} item
   */
  _integrate(y3, item) {
    super._integrate(y3, item);
    this._prelimContent.forEach((value, key2) => {
      this.set(key2, value);
    });
    this._prelimContent = null;
  }
  /**
   * @return {YMap<MapType>}
   */
  _copy() {
    return new _YMap();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YMap<MapType>}
   */
  clone() {
    const map7 = new _YMap();
    this.forEach((value, key2) => {
      map7.set(key2, value instanceof AbstractType ? (
        /** @type {typeof value} */
        value.clone()
      ) : value);
    });
    return map7;
  }
  /**
   * Creates YMapEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(transaction, parentSubs) {
    callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs));
  }
  /**
   * Transforms this Shared Type to a JSON object.
   *
   * @return {Object<string,any>}
   */
  toJSON() {
    this.doc ?? warnPrematureAccess();
    const map7 = {};
    this._map.forEach((item, key2) => {
      if (!item.deleted) {
        const v8 = item.content.getContent()[item.length - 1];
        map7[key2] = v8 instanceof AbstractType ? v8.toJSON() : v8;
      }
    });
    return map7;
  }
  /**
   * Returns the size of the YMap (count of key/value pairs)
   *
   * @return {number}
   */
  get size() {
    return [...createMapIterator(this)].length;
  }
  /**
   * Returns the keys for each element in the YMap Type.
   *
   * @return {IterableIterator<string>}
   */
  keys() {
    return iteratorMap(
      createMapIterator(this),
      /** @param {any} v */
      (v8) => v8[0]
    );
  }
  /**
   * Returns the values for each element in the YMap Type.
   *
   * @return {IterableIterator<MapType>}
   */
  values() {
    return iteratorMap(
      createMapIterator(this),
      /** @param {any} v */
      (v8) => v8[1].content.getContent()[v8[1].length - 1]
    );
  }
  /**
   * Returns an Iterator of [key, value] pairs
   *
   * @return {IterableIterator<[string, MapType]>}
   */
  entries() {
    return iteratorMap(
      createMapIterator(this),
      /** @param {any} v */
      (v8) => (
        /** @type {any} */
        [v8[0], v8[1].content.getContent()[v8[1].length - 1]]
      )
    );
  }
  /**
   * Executes a provided function on once on every key-value pair.
   *
   * @param {function(MapType,string,YMap<MapType>):void} f A function to execute on every element of this YArray.
   */
  forEach(f6) {
    this.doc ?? warnPrematureAccess();
    this._map.forEach((item, key2) => {
      if (!item.deleted) {
        f6(item.content.getContent()[item.length - 1], key2, this);
      }
    });
  }
  /**
   * Returns an Iterator of [key, value] pairs
   *
   * @return {IterableIterator<[string, MapType]>}
   */
  [Symbol.iterator]() {
    return this.entries();
  }
  /**
   * Remove a specified element from this YMap.
   *
   * @param {string} key The key of the element to remove.
   */
  delete(key2) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapDelete(transaction, this, key2);
      });
    } else {
      this._prelimContent.delete(key2);
    }
  }
  /**
   * Adds or updates an element with a specified key and value.
   * @template {MapType} VAL
   *
   * @param {string} key The key of the element to add to this YMap
   * @param {VAL} value The value of the element to add
   * @return {VAL}
   */
  set(key2, value) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapSet(
          transaction,
          this,
          key2,
          /** @type {any} */
          value
        );
      });
    } else {
      this._prelimContent.set(key2, value);
    }
    return value;
  }
  /**
   * Returns a specified element from this YMap.
   *
   * @param {string} key
   * @return {MapType|undefined}
   */
  get(key2) {
    return (
      /** @type {any} */
      typeMapGet(this, key2)
    );
  }
  /**
   * Returns a boolean indicating whether the specified key exists or not.
   *
   * @param {string} key The key to test.
   * @return {boolean}
   */
  has(key2) {
    return typeMapHas(this, key2);
  }
  /**
   * Removes all elements from this YMap.
   */
  clear() {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        this.forEach(function(_value, key2, map7) {
          typeMapDelete(transaction, map7, key2);
        });
      });
    } else {
      this._prelimContent.clear();
    }
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(encoder) {
    encoder.writeTypeRef(YMapRefID);
  }
};
var readYMap = (_decoder) => new YMap();
var equalAttrs = (a3, b4) => a3 === b4 || typeof a3 === "object" && typeof b4 === "object" && a3 && b4 && equalFlat(a3, b4);
var ItemTextListPosition = class {
  /**
   * @param {Item|null} left
   * @param {Item|null} right
   * @param {number} index
   * @param {Map<string,any>} currentAttributes
   */
  constructor(left, right, index4, currentAttributes) {
    this.left = left;
    this.right = right;
    this.index = index4;
    this.currentAttributes = currentAttributes;
  }
  /**
   * Only call this if you know that this.right is defined
   */
  forward() {
    if (this.right === null) {
      unexpectedCase();
    }
    switch (this.right.content.constructor) {
      case ContentFormat:
        if (!this.right.deleted) {
          updateCurrentAttributes(
            this.currentAttributes,
            /** @type {ContentFormat} */
            this.right.content
          );
        }
        break;
      default:
        if (!this.right.deleted) {
          this.index += this.right.length;
        }
        break;
    }
    this.left = this.right;
    this.right = this.right.right;
  }
};
var findNextPosition = (transaction, pos, count2) => {
  while (pos.right !== null && count2 > 0) {
    switch (pos.right.content.constructor) {
      case ContentFormat:
        if (!pos.right.deleted) {
          updateCurrentAttributes(
            pos.currentAttributes,
            /** @type {ContentFormat} */
            pos.right.content
          );
        }
        break;
      default:
        if (!pos.right.deleted) {
          if (count2 < pos.right.length) {
            getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count2));
          }
          pos.index += pos.right.length;
          count2 -= pos.right.length;
        }
        break;
    }
    pos.left = pos.right;
    pos.right = pos.right.right;
  }
  return pos;
};
var findPosition = (transaction, parent, index4, useSearchMarker) => {
  const currentAttributes = /* @__PURE__ */ new Map();
  const marker = useSearchMarker ? findMarker(parent, index4) : null;
  if (marker) {
    const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes);
    return findNextPosition(transaction, pos, index4 - marker.index);
  } else {
    const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes);
    return findNextPosition(transaction, pos, index4);
  }
};
var insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {
  while (currPos.right !== null && (currPos.right.deleted === true || currPos.right.content.constructor === ContentFormat && equalAttrs(
    negatedAttributes.get(
      /** @type {ContentFormat} */
      currPos.right.content.key
    ),
    /** @type {ContentFormat} */
    currPos.right.content.value
  ))) {
    if (!currPos.right.deleted) {
      negatedAttributes.delete(
        /** @type {ContentFormat} */
        currPos.right.content.key
      );
    }
    currPos.forward();
  }
  const doc4 = transaction.doc;
  const ownClientId = doc4.clientID;
  negatedAttributes.forEach((val, key2) => {
    const left = currPos.left;
    const right = currPos.right;
    const nextFormat = new Item(createID(ownClientId, getState(doc4.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key2, val));
    nextFormat.integrate(transaction, 0);
    currPos.right = nextFormat;
    currPos.forward();
  });
};
var updateCurrentAttributes = (currentAttributes, format) => {
  const { key: key2, value } = format;
  if (value === null) {
    currentAttributes.delete(key2);
  } else {
    currentAttributes.set(key2, value);
  }
};
var minimizeAttributeChanges = (currPos, attributes) => {
  while (true) {
    if (currPos.right === null) {
      break;
    } 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 {
      break;
    }
    currPos.forward();
  }
};
var insertAttributes = (transaction, parent, currPos, attributes) => {
  const doc4 = transaction.doc;
  const ownClientId = doc4.clientID;
  const negatedAttributes = /* @__PURE__ */ new Map();
  for (const key2 in attributes) {
    const val = attributes[key2];
    const currentVal = currPos.currentAttributes.get(key2) ?? null;
    if (!equalAttrs(currentVal, val)) {
      negatedAttributes.set(key2, currentVal);
      const { left, right } = currPos;
      currPos.right = new Item(createID(ownClientId, getState(doc4.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key2, val));
      currPos.right.integrate(transaction, 0);
      currPos.forward();
    }
  }
  return negatedAttributes;
};
var insertText = (transaction, parent, currPos, text10, attributes) => {
  currPos.currentAttributes.forEach((_val, key2) => {
    if (attributes[key2] === void 0) {
      attributes[key2] = null;
    }
  });
  const doc4 = transaction.doc;
  const ownClientId = doc4.clientID;
  minimizeAttributeChanges(currPos, attributes);
  const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);
  const content5 = text10.constructor === String ? new ContentString(
    /** @type {string} */
    text10
  ) : text10 instanceof AbstractType ? new ContentType(text10) : new ContentEmbed(text10);
  let { left, right, index: index4 } = currPos;
  if (parent._searchMarker) {
    updateMarkerChanges(parent._searchMarker, currPos.index, content5.getLength());
  }
  right = new Item(createID(ownClientId, getState(doc4.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content5);
  right.integrate(transaction, 0);
  currPos.right = right;
  currPos.index = index4;
  currPos.forward();
  insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);
};
var formatText = (transaction, parent, currPos, length2, attributes) => {
  const doc4 = transaction.doc;
  const ownClientId = doc4.clientID;
  minimizeAttributeChanges(currPos, attributes);
  const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);
  iterationLoop: while (currPos.right !== null && (length2 > 0 || negatedAttributes.size > 0 && (currPos.right.deleted || currPos.right.content.constructor === ContentFormat))) {
    if (!currPos.right.deleted) {
      switch (currPos.right.content.constructor) {
        case ContentFormat: {
          const { key: key2, value } = (
            /** @type {ContentFormat} */
            currPos.right.content
          );
          const attr2 = attributes[key2];
          if (attr2 !== void 0) {
            if (equalAttrs(attr2, value)) {
              negatedAttributes.delete(key2);
            } else {
              if (length2 === 0) {
                break iterationLoop;
              }
              negatedAttributes.set(key2, value);
            }
            currPos.right.delete(transaction);
          } else {
            currPos.currentAttributes.set(key2, value);
          }
          break;
        }
        default:
          if (length2 < currPos.right.length) {
            getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2));
          }
          length2 -= currPos.right.length;
          break;
      }
    }
    currPos.forward();
  }
  if (length2 > 0) {
    let newlines = "";
    for (; length2 > 0; length2--) {
      newlines += "\n";
    }
    currPos.right = new Item(createID(ownClientId, getState(doc4.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines));
    currPos.right.integrate(transaction, 0);
    currPos.forward();
  }
  insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);
};
var cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => {
  let end = start;
  const endFormats = create();
  while (end && (!end.countable || end.deleted)) {
    if (!end.deleted && end.content.constructor === ContentFormat) {
      const cf = (
        /** @type {ContentFormat} */
        end.content
      );
      endFormats.set(cf.key, cf);
    }
    end = end.right;
  }
  let cleanups = 0;
  let reachedCurr = false;
  while (start !== end) {
    if (curr === start) {
      reachedCurr = true;
    }
    if (!start.deleted) {
      const content5 = start.content;
      switch (content5.constructor) {
        case ContentFormat: {
          const { key: key2, value } = (
            /** @type {ContentFormat} */
            content5
          );
          const startAttrValue = startAttributes.get(key2) ?? null;
          if (endFormats.get(key2) !== content5 || startAttrValue === value) {
            start.delete(transaction);
            cleanups++;
            if (!reachedCurr && (currAttributes.get(key2) ?? null) === value && startAttrValue !== value) {
              if (startAttrValue === null) {
                currAttributes.delete(key2);
              } else {
                currAttributes.set(key2, startAttrValue);
              }
            }
          }
          if (!reachedCurr && !start.deleted) {
            updateCurrentAttributes(
              currAttributes,
              /** @type {ContentFormat} */
              content5
            );
          }
          break;
        }
      }
    }
    start = /** @type {Item} */
    start.right;
  }
  return cleanups;
};
var cleanupContextlessFormattingGap = (transaction, item) => {
  while (item && item.right && (item.right.deleted || !item.right.countable)) {
    item = item.right;
  }
  const attrs = /* @__PURE__ */ new Set();
  while (item && (item.deleted || !item.countable)) {
    if (!item.deleted && item.content.constructor === ContentFormat) {
      const key2 = (
        /** @type {ContentFormat} */
        item.content.key
      );
      if (attrs.has(key2)) {
        item.delete(transaction);
      } else {
        attrs.add(key2);
      }
    }
    item = item.left;
  }
};
var cleanupYTextFormatting = (type) => {
  let res = 0;
  transact(
    /** @type {Doc} */
    type.doc,
    (transaction) => {
      let start = (
        /** @type {Item} */
        type._start
      );
      let end = type._start;
      let startAttributes = create();
      const currentAttributes = copy2(startAttributes);
      while (end) {
        if (end.deleted === false) {
          switch (end.content.constructor) {
            case ContentFormat:
              updateCurrentAttributes(
                currentAttributes,
                /** @type {ContentFormat} */
                end.content
              );
              break;
            default:
              res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes);
              startAttributes = copy2(currentAttributes);
              start = end;
              break;
          }
        }
        end = end.right;
      }
    }
  );
  return res;
};
var cleanupYTextAfterTransaction = (transaction) => {
  const needFullCleanup = /* @__PURE__ */ new Set();
  const doc4 = transaction.doc;
  for (const [client, afterClock] of transaction.afterState.entries()) {
    const clock = transaction.beforeState.get(client) || 0;
    if (afterClock === clock) {
      continue;
    }
    iterateStructs(
      transaction,
      /** @type {Array<Item|GC>} */
      doc4.store.clients.get(client),
      clock,
      afterClock,
      (item) => {
        if (!item.deleted && /** @type {Item} */
        item.content.constructor === ContentFormat && item.constructor !== GC) {
          needFullCleanup.add(
            /** @type {any} */
            item.parent
          );
        }
      }
    );
  }
  transact(doc4, (t2) => {
    iterateDeletedStructs(transaction, transaction.deleteSet, (item) => {
      if (item instanceof GC || !/** @type {YText} */
      item.parent._hasFormatting || needFullCleanup.has(
        /** @type {YText} */
        item.parent
      )) {
        return;
      }
      const parent = (
        /** @type {YText} */
        item.parent
      );
      if (item.content.constructor === ContentFormat) {
        needFullCleanup.add(parent);
      } else {
        cleanupContextlessFormattingGap(t2, item);
      }
    });
    for (const yText of needFullCleanup) {
      cleanupYTextFormatting(yText);
    }
  });
};
var deleteText = (transaction, currPos, length2) => {
  const startLength = length2;
  const startAttrs = copy2(currPos.currentAttributes);
  const start = currPos.right;
  while (length2 > 0 && currPos.right !== null) {
    if (currPos.right.deleted === false) {
      switch (currPos.right.content.constructor) {
        case ContentType:
        case ContentEmbed:
        case ContentString:
          if (length2 < currPos.right.length) {
            getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2));
          }
          length2 -= currPos.right.length;
          currPos.right.delete(transaction);
          break;
      }
    }
    currPos.forward();
  }
  if (start) {
    cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes);
  }
  const parent = (
    /** @type {AbstractType<any>} */
    /** @type {Item} */
    (currPos.left || currPos.right).parent
  );
  if (parent._searchMarker) {
    updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length2);
  }
  return currPos;
};
var YTextEvent = class extends YEvent {
  /**
   * @param {YText} ytext
   * @param {Transaction} transaction
   * @param {Set<any>} subs The keys that changed
   */
  constructor(ytext, transaction, subs) {
    super(ytext, transaction);
    this.childListChanged = false;
    this.keysChanged = /* @__PURE__ */ new Set();
    subs.forEach((sub) => {
      if (sub === null) {
        this.childListChanged = true;
      } else {
        this.keysChanged.add(sub);
      }
    });
  }
  /**
   * @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}>}}
   */
  get changes() {
    if (this._changes === null) {
      const changes = {
        keys: this.keys,
        delta: this.delta,
        added: /* @__PURE__ */ new Set(),
        deleted: /* @__PURE__ */ new Set()
      };
      this._changes = changes;
    }
    return (
      /** @type {any} */
      this._changes
    );
  }
  /**
   * Compute the changes in the delta format.
   * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.
   *
   * @type {Array<{insert?:string|object|AbstractType<any>, delete?:number, retain?:number, attributes?: Object<string,any>}>}
   *
   * @public
   */
  get delta() {
    if (this._delta === null) {
      const y3 = (
        /** @type {Doc} */
        this.target.doc
      );
      const delta = [];
      transact(y3, (transaction) => {
        const currentAttributes = /* @__PURE__ */ new Map();
        const oldAttributes = /* @__PURE__ */ new Map();
        let item = this.target._start;
        let action = null;
        const attributes = {};
        let insert = "";
        let retain = 0;
        let deleteLen = 0;
        const addOp = () => {
          if (action !== null) {
            let op = null;
            switch (action) {
              case "delete":
                if (deleteLen > 0) {
                  op = { delete: deleteLen };
                }
                deleteLen = 0;
                break;
              case "insert":
                if (typeof insert === "object" || insert.length > 0) {
                  op = { insert };
                  if (currentAttributes.size > 0) {
                    op.attributes = {};
                    currentAttributes.forEach((value, key2) => {
                      if (value !== null) {
                        op.attributes[key2] = value;
                      }
                    });
                  }
                }
                insert = "";
                break;
              case "retain":
                if (retain > 0) {
                  op = { retain };
                  if (!isEmpty(attributes)) {
                    op.attributes = assign({}, attributes);
                  }
                }
                retain = 0;
                break;
            }
            if (op) delta.push(op);
            action = null;
          }
        };
        while (item !== null) {
          switch (item.content.constructor) {
            case ContentType:
            case ContentEmbed:
              if (this.adds(item)) {
                if (!this.deletes(item)) {
                  addOp();
                  action = "insert";
                  insert = item.content.getContent()[0];
                  addOp();
                }
              } else if (this.deletes(item)) {
                if (action !== "delete") {
                  addOp();
                  action = "delete";
                }
                deleteLen += 1;
              } else if (!item.deleted) {
                if (action !== "retain") {
                  addOp();
                  action = "retain";
                }
                retain += 1;
              }
              break;
            case ContentString:
              if (this.adds(item)) {
                if (!this.deletes(item)) {
                  if (action !== "insert") {
                    addOp();
                    action = "insert";
                  }
                  insert += /** @type {ContentString} */
                  item.content.str;
                }
              } else if (this.deletes(item)) {
                if (action !== "delete") {
                  addOp();
                  action = "delete";
                }
                deleteLen += item.length;
              } else if (!item.deleted) {
                if (action !== "retain") {
                  addOp();
                  action = "retain";
                }
                retain += item.length;
              }
              break;
            case ContentFormat: {
              const { key: key2, value } = (
                /** @type {ContentFormat} */
                item.content
              );
              if (this.adds(item)) {
                if (!this.deletes(item)) {
                  const curVal = currentAttributes.get(key2) ?? null;
                  if (!equalAttrs(curVal, value)) {
                    if (action === "retain") {
                      addOp();
                    }
                    if (equalAttrs(value, oldAttributes.get(key2) ?? null)) {
                      delete attributes[key2];
                    } else {
                      attributes[key2] = value;
                    }
                  } else if (value !== null) {
                    item.delete(transaction);
                  }
                }
              } else if (this.deletes(item)) {
                oldAttributes.set(key2, value);
                const curVal = currentAttributes.get(key2) ?? null;
                if (!equalAttrs(curVal, value)) {
                  if (action === "retain") {
                    addOp();
                  }
                  attributes[key2] = curVal;
                }
              } else if (!item.deleted) {
                oldAttributes.set(key2, value);
                const attr2 = attributes[key2];
                if (attr2 !== void 0) {
                  if (!equalAttrs(attr2, value)) {
                    if (action === "retain") {
                      addOp();
                    }
                    if (value === null) {
                      delete attributes[key2];
                    } else {
                      attributes[key2] = value;
                    }
                  } else if (attr2 !== null) {
                    item.delete(transaction);
                  }
                }
              }
              if (!item.deleted) {
                if (action === "insert") {
                  addOp();
                }
                updateCurrentAttributes(
                  currentAttributes,
                  /** @type {ContentFormat} */
                  item.content
                );
              }
              break;
            }
          }
          item = item.right;
        }
        addOp();
        while (delta.length > 0) {
          const lastOp = delta[delta.length - 1];
          if (lastOp.retain !== void 0 && lastOp.attributes === void 0) {
            delta.pop();
          } else {
            break;
          }
        }
      });
      this._delta = delta;
    }
    return (
      /** @type {any} */
      this._delta
    );
  }
};
var YText = class _YText extends AbstractType {
  /**
   * @param {String} [string] The initial value of the YText.
   */
  constructor(string3) {
    super();
    this._pending = string3 !== void 0 ? [() => this.insert(0, string3)] : [];
    this._searchMarker = [];
    this._hasFormatting = false;
  }
  /**
   * Number of characters of this text type.
   *
   * @type {number}
   */
  get length() {
    this.doc ?? warnPrematureAccess();
    return this._length;
  }
  /**
   * @param {Doc} y
   * @param {Item} item
   */
  _integrate(y3, item) {
    super._integrate(y3, item);
    try {
      this._pending.forEach((f6) => f6());
    } catch (e2) {
      console.error(e2);
    }
    this._pending = null;
  }
  _copy() {
    return new _YText();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YText}
   */
  clone() {
    const text10 = new _YText();
    text10.applyDelta(this.toDelta());
    return text10;
  }
  /**
   * Creates YTextEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(transaction, parentSubs) {
    super._callObserver(transaction, parentSubs);
    const event = new YTextEvent(this, transaction, parentSubs);
    callTypeObservers(this, transaction, event);
    if (!transaction.local && this._hasFormatting) {
      transaction._needFormattingCleanup = true;
    }
  }
  /**
   * Returns the unformatted string representation of this YText type.
   *
   * @public
   */
  toString() {
    this.doc ?? warnPrematureAccess();
    let str = "";
    let n = this._start;
    while (n !== null) {
      if (!n.deleted && n.countable && n.content.constructor === ContentString) {
        str += /** @type {ContentString} */
        n.content.str;
      }
      n = n.right;
    }
    return str;
  }
  /**
   * Returns the unformatted string representation of this YText type.
   *
   * @return {string}
   * @public
   */
  toJSON() {
    return this.toString();
  }
  /**
   * Apply a {@link Delta} on this shared YText type.
   *
   * @param {Array<any>} delta The changes to apply on this element.
   * @param {object}  opts
   * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.
   *
   *
   * @public
   */
  applyDelta(delta, { sanitize = true } = {}) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        const currPos = new ItemTextListPosition(null, this._start, 0, /* @__PURE__ */ new Map());
        for (let i3 = 0; i3 < delta.length; i3++) {
          const op = delta[i3];
          if (op.insert !== void 0) {
            const ins = !sanitize && typeof op.insert === "string" && i3 === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === "\n" ? op.insert.slice(0, -1) : op.insert;
            if (typeof ins !== "string" || ins.length > 0) {
              insertText(transaction, this, currPos, ins, op.attributes || {});
            }
          } else if (op.retain !== void 0) {
            formatText(transaction, this, currPos, op.retain, op.attributes || {});
          } else if (op.delete !== void 0) {
            deleteText(transaction, currPos, op.delete);
          }
        }
      });
    } else {
      this._pending.push(() => this.applyDelta(delta));
    }
  }
  /**
   * Returns the Delta representation of this YText type.
   *
   * @param {Snapshot} [snapshot]
   * @param {Snapshot} [prevSnapshot]
   * @param {function('removed' | 'added', ID):any} [computeYChange]
   * @return {any} The Delta representation of this type.
   *
   * @public
   */
  toDelta(snapshot2, prevSnapshot, computeYChange) {
    this.doc ?? warnPrematureAccess();
    const ops = [];
    const currentAttributes = /* @__PURE__ */ new Map();
    const doc4 = (
      /** @type {Doc} */
      this.doc
    );
    let str = "";
    let n = this._start;
    function packStr() {
      if (str.length > 0) {
        const attributes = {};
        let addAttributes = false;
        currentAttributes.forEach((value, key2) => {
          addAttributes = true;
          attributes[key2] = value;
        });
        const op = { insert: str };
        if (addAttributes) {
          op.attributes = attributes;
        }
        ops.push(op);
        str = "";
      }
    }
    const computeDelta = () => {
      while (n !== null) {
        if (isVisible(n, snapshot2) || prevSnapshot !== void 0 && isVisible(n, prevSnapshot)) {
          switch (n.content.constructor) {
            case ContentString: {
              const cur = currentAttributes.get("ychange");
              if (snapshot2 !== void 0 && !isVisible(n, snapshot2)) {
                if (cur === void 0 || cur.user !== n.id.client || cur.type !== "removed") {
                  packStr();
                  currentAttributes.set("ychange", computeYChange ? computeYChange("removed", n.id) : { type: "removed" });
                }
              } else if (prevSnapshot !== void 0 && !isVisible(n, prevSnapshot)) {
                if (cur === void 0 || cur.user !== n.id.client || cur.type !== "added") {
                  packStr();
                  currentAttributes.set("ychange", computeYChange ? computeYChange("added", n.id) : { type: "added" });
                }
              } else if (cur !== void 0) {
                packStr();
                currentAttributes.delete("ychange");
              }
              str += /** @type {ContentString} */
              n.content.str;
              break;
            }
            case ContentType:
            case ContentEmbed: {
              packStr();
              const op = {
                insert: n.content.getContent()[0]
              };
              if (currentAttributes.size > 0) {
                const attrs = (
                  /** @type {Object<string,any>} */
                  {}
                );
                op.attributes = attrs;
                currentAttributes.forEach((value, key2) => {
                  attrs[key2] = value;
                });
              }
              ops.push(op);
              break;
            }
            case ContentFormat:
              if (isVisible(n, snapshot2)) {
                packStr();
                updateCurrentAttributes(
                  currentAttributes,
                  /** @type {ContentFormat} */
                  n.content
                );
              }
              break;
          }
        }
        n = n.right;
      }
      packStr();
    };
    if (snapshot2 || prevSnapshot) {
      transact(doc4, (transaction) => {
        if (snapshot2) {
          splitSnapshotAffectedStructs(transaction, snapshot2);
        }
        if (prevSnapshot) {
          splitSnapshotAffectedStructs(transaction, prevSnapshot);
        }
        computeDelta();
      }, "cleanup");
    } else {
      computeDelta();
    }
    return ops;
  }
  /**
   * Insert text at a given index.
   *
   * @param {number} index The index at which to start inserting.
   * @param {String} text The text to insert at the specified position.
   * @param {TextAttributes} [attributes] Optionally define some formatting
   *                                    information to apply on the inserted
   *                                    Text.
   * @public
   */
  insert(index4, text10, attributes) {
    if (text10.length <= 0) {
      return;
    }
    const y3 = this.doc;
    if (y3 !== null) {
      transact(y3, (transaction) => {
        const pos = findPosition(transaction, this, index4, !attributes);
        if (!attributes) {
          attributes = {};
          pos.currentAttributes.forEach((v8, k3) => {
            attributes[k3] = v8;
          });
        }
        insertText(transaction, this, pos, text10, attributes);
      });
    } else {
      this._pending.push(() => this.insert(index4, text10, attributes));
    }
  }
  /**
   * Inserts an embed at a index.
   *
   * @param {number} index The index to insert the embed at.
   * @param {Object | AbstractType<any>} embed The Object that represents the embed.
   * @param {TextAttributes} [attributes] Attribute information to apply on the
   *                                    embed
   *
   * @public
   */
  insertEmbed(index4, embed, attributes) {
    const y3 = this.doc;
    if (y3 !== null) {
      transact(y3, (transaction) => {
        const pos = findPosition(transaction, this, index4, !attributes);
        insertText(transaction, this, pos, embed, attributes || {});
      });
    } else {
      this._pending.push(() => this.insertEmbed(index4, embed, attributes || {}));
    }
  }
  /**
   * Deletes text starting from an index.
   *
   * @param {number} index Index at which to start deleting.
   * @param {number} length The number of characters to remove. Defaults to 1.
   *
   * @public
   */
  delete(index4, length2) {
    if (length2 === 0) {
      return;
    }
    const y3 = this.doc;
    if (y3 !== null) {
      transact(y3, (transaction) => {
        deleteText(transaction, findPosition(transaction, this, index4, true), length2);
      });
    } else {
      this._pending.push(() => this.delete(index4, length2));
    }
  }
  /**
   * Assigns properties to a range of text.
   *
   * @param {number} index The position where to start formatting.
   * @param {number} length The amount of characters to assign properties to.
   * @param {TextAttributes} attributes Attribute information to apply on the
   *                                    text.
   *
   * @public
   */
  format(index4, length2, attributes) {
    if (length2 === 0) {
      return;
    }
    const y3 = this.doc;
    if (y3 !== null) {
      transact(y3, (transaction) => {
        const pos = findPosition(transaction, this, index4, false);
        if (pos.right === null) {
          return;
        }
        formatText(transaction, this, pos, length2, attributes);
      });
    } else {
      this._pending.push(() => this.format(index4, length2, attributes));
    }
  }
  /**
   * Removes an attribute.
   *
   * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
   *
   * @param {String} attributeName The attribute name that is to be removed.
   *
   * @public
   */
  removeAttribute(attributeName) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapDelete(transaction, this, attributeName);
      });
    } else {
      this._pending.push(() => this.removeAttribute(attributeName));
    }
  }
  /**
   * Sets or updates an attribute.
   *
   * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
   *
   * @param {String} attributeName The attribute name that is to be set.
   * @param {any} attributeValue The attribute value that is to be set.
   *
   * @public
   */
  setAttribute(attributeName, attributeValue) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapSet(transaction, this, attributeName, attributeValue);
      });
    } else {
      this._pending.push(() => this.setAttribute(attributeName, attributeValue));
    }
  }
  /**
   * Returns an attribute value that belongs to the attribute name.
   *
   * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
   *
   * @param {String} attributeName The attribute name that identifies the
   *                               queried value.
   * @return {any} The queried attribute value.
   *
   * @public
   */
  getAttribute(attributeName) {
    return (
      /** @type {any} */
      typeMapGet(this, attributeName)
    );
  }
  /**
   * Returns all attribute name/value pairs in a JSON Object.
   *
   * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
   *
   * @return {Object<string, any>} A JSON Object that describes the attributes.
   *
   * @public
   */
  getAttributes() {
    return typeMapGetAll(this);
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(encoder) {
    encoder.writeTypeRef(YTextRefID);
  }
};
var readYText = (_decoder) => new YText();
var YXmlTreeWalker = class {
  /**
   * @param {YXmlFragment | YXmlElement} root
   * @param {function(AbstractType<any>):boolean} [f]
   */
  constructor(root6, f6 = () => true) {
    this._filter = f6;
    this._root = root6;
    this._currentNode = /** @type {Item} */
    root6._start;
    this._firstCall = true;
    root6.doc ?? warnPrematureAccess();
  }
  [Symbol.iterator]() {
    return this;
  }
  /**
   * Get the next node.
   *
   * @return {IteratorResult<YXmlElement|YXmlText|YXmlHook>} The next node.
   *
   * @public
   */
  next() {
    let n = this._currentNode;
    let type = n && n.content && /** @type {any} */
    n.content.type;
    if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) {
      do {
        type = /** @type {any} */
        n.content.type;
        if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {
          n = type._start;
        } else {
          while (n !== null) {
            const nxt = n.next;
            if (nxt !== null) {
              n = nxt;
              break;
            } else if (n.parent === this._root) {
              n = null;
            } else {
              n = /** @type {AbstractType<any>} */
              n.parent._item;
            }
          }
        }
      } while (n !== null && (n.deleted || !this._filter(
        /** @type {ContentType} */
        n.content.type
      )));
    }
    this._firstCall = false;
    if (n === null) {
      return { value: void 0, done: true };
    }
    this._currentNode = n;
    return { value: (
      /** @type {any} */
      n.content.type
    ), done: false };
  }
};
var YXmlFragment = class _YXmlFragment extends AbstractType {
  constructor() {
    super();
    this._prelimContent = [];
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get firstChild() {
    const first2 = this._first;
    return first2 ? first2.content.getContent()[0] : null;
  }
  /**
   * Integrate this type into the Yjs instance.
   *
   * * Save this struct in the os
   * * This type is sent to other client
   * * Observer functions are fired
   *
   * @param {Doc} y The Yjs instance
   * @param {Item} item
   */
  _integrate(y3, item) {
    super._integrate(y3, item);
    this.insert(
      0,
      /** @type {Array<any>} */
      this._prelimContent
    );
    this._prelimContent = null;
  }
  _copy() {
    return new _YXmlFragment();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YXmlFragment}
   */
  clone() {
    const el2 = new _YXmlFragment();
    el2.insert(0, this.toArray().map((item) => item instanceof AbstractType ? item.clone() : item));
    return el2;
  }
  get length() {
    this.doc ?? warnPrematureAccess();
    return this._prelimContent === null ? this._length : this._prelimContent.length;
  }
  /**
   * Create a subtree of childNodes.
   *
   * @example
   * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')
   * for (let node in walker) {
   *   // `node` is a div node
   *   nop(node)
   * }
   *
   * @param {function(AbstractType<any>):boolean} filter Function that is called on each child element and
   *                          returns a Boolean indicating whether the child
   *                          is to be included in the subtree.
   * @return {YXmlTreeWalker} A subtree and a position within it.
   *
   * @public
   */
  createTreeWalker(filter) {
    return new YXmlTreeWalker(this, filter);
  }
  /**
   * Returns the first YXmlElement that matches the query.
   * Similar to DOM's {@link querySelector}.
   *
   * Query support:
   *   - tagname
   * TODO:
   *   - id
   *   - attribute
   *
   * @param {CSS_Selector} query The query on the children.
   * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.
   *
   * @public
   */
  querySelector(query) {
    query = query.toUpperCase();
    const iterator = new YXmlTreeWalker(this, (element7) => element7.nodeName && element7.nodeName.toUpperCase() === query);
    const next2 = iterator.next();
    if (next2.done) {
      return null;
    } else {
      return next2.value;
    }
  }
  /**
   * Returns all YXmlElements that match the query.
   * Similar to Dom's {@link querySelectorAll}.
   *
   * @todo Does not yet support all queries. Currently only query by tagName.
   *
   * @param {CSS_Selector} query The query on the children
   * @return {Array<YXmlElement|YXmlText|YXmlHook|null>} The elements that match this query.
   *
   * @public
   */
  querySelectorAll(query) {
    query = query.toUpperCase();
    return from2(new YXmlTreeWalker(this, (element7) => element7.nodeName && element7.nodeName.toUpperCase() === query));
  }
  /**
   * Creates YXmlEvent and calls observers.
   *
   * @param {Transaction} transaction
   * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
   */
  _callObserver(transaction, parentSubs) {
    callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction));
  }
  /**
   * Get the string representation of all the children of this YXmlFragment.
   *
   * @return {string} The string representation of all children.
   */
  toString() {
    return typeListMap(this, (xml2) => xml2.toString()).join("");
  }
  /**
   * @return {string}
   */
  toJSON() {
    return this.toString();
  }
  /**
   * Creates a Dom Element that mirrors this YXmlElement.
   *
   * @param {Document} [_document=document] The document object (you must define
   *                                        this when calling this method in
   *                                        nodejs)
   * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks
   *                                             are presented in the DOM
   * @param {any} [binding] You should not set this property. This is
   *                               used if DomBinding wants to create a
   *                               association to the created DOM type.
   * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
   *
   * @public
   */
  toDOM(_document = document, hooks = {}, binding) {
    const fragment = _document.createDocumentFragment();
    if (binding !== void 0) {
      binding._createAssociation(fragment, this);
    }
    typeListForEach(this, (xmlType) => {
      fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null);
    });
    return fragment;
  }
  /**
   * Inserts new content at an index.
   *
   * @example
   *  // Insert character 'a' at position 0
   *  xml.insert(0, [new Y.XmlText('text')])
   *
   * @param {number} index The index to insert content at
   * @param {Array<YXmlElement|YXmlText>} content The array of content
   */
  insert(index4, content5) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListInsertGenerics(transaction, this, index4, content5);
      });
    } else {
      this._prelimContent.splice(index4, 0, ...content5);
    }
  }
  /**
   * Inserts new content at an index.
   *
   * @example
   *  // Insert character 'a' at position 0
   *  xml.insert(0, [new Y.XmlText('text')])
   *
   * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at
   * @param {Array<YXmlElement|YXmlText>} content The array of content
   */
  insertAfter(ref, content5) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        const refItem = ref && ref instanceof AbstractType ? ref._item : ref;
        typeListInsertGenericsAfter(transaction, this, refItem, content5);
      });
    } else {
      const pc = (
        /** @type {Array<any>} */
        this._prelimContent
      );
      const index4 = ref === null ? 0 : pc.findIndex((el2) => el2 === ref) + 1;
      if (index4 === 0 && ref !== null) {
        throw create3("Reference item not found");
      }
      pc.splice(index4, 0, ...content5);
    }
  }
  /**
   * Deletes elements starting from an index.
   *
   * @param {number} index Index at which to start deleting elements
   * @param {number} [length=1] The number of elements to remove. Defaults to 1.
   */
  delete(index4, length2 = 1) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeListDelete(transaction, this, index4, length2);
      });
    } else {
      this._prelimContent.splice(index4, length2);
    }
  }
  /**
   * Transforms this YArray to a JavaScript Array.
   *
   * @return {Array<YXmlElement|YXmlText|YXmlHook>}
   */
  toArray() {
    return typeListToArray(this);
  }
  /**
   * Appends content to this YArray.
   *
   * @param {Array<YXmlElement|YXmlText>} content Array of content to append.
   */
  push(content5) {
    this.insert(this.length, content5);
  }
  /**
   * Prepends content to this YArray.
   *
   * @param {Array<YXmlElement|YXmlText>} content Array of content to prepend.
   */
  unshift(content5) {
    this.insert(0, content5);
  }
  /**
   * Returns the i-th element from a YArray.
   *
   * @param {number} index The index of the element to return from the YArray
   * @return {YXmlElement|YXmlText}
   */
  get(index4) {
    return typeListGet(this, index4);
  }
  /**
   * Returns a portion of this YXmlFragment into a JavaScript Array selected
   * from start to end (end not included).
   *
   * @param {number} [start]
   * @param {number} [end]
   * @return {Array<YXmlElement|YXmlText>}
   */
  slice(start = 0, end = this.length) {
    return typeListSlice(this, start, end);
  }
  /**
   * Executes a provided function on once on every child element.
   *
   * @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray.
   */
  forEach(f6) {
    typeListForEach(this, f6);
  }
  /**
   * Transform the properties of this type to binary and write it to an
   * BinaryEncoder.
   *
   * This is called when this Item is sent to a remote peer.
   *
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   */
  _write(encoder) {
    encoder.writeTypeRef(YXmlFragmentRefID);
  }
};
var readYXmlFragment = (_decoder) => new YXmlFragment();
var YXmlElement = class _YXmlElement extends YXmlFragment {
  constructor(nodeName = "UNDEFINED") {
    super();
    this.nodeName = nodeName;
    this._prelimAttrs = /* @__PURE__ */ new Map();
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get nextSibling() {
    const n = this._item ? this._item.next : null;
    return n ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      n.content.type
    ) : null;
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get prevSibling() {
    const n = this._item ? this._item.prev : null;
    return n ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      n.content.type
    ) : null;
  }
  /**
   * Integrate this type into the Yjs instance.
   *
   * * Save this struct in the os
   * * This type is sent to other client
   * * Observer functions are fired
   *
   * @param {Doc} y The Yjs instance
   * @param {Item} item
   */
  _integrate(y3, item) {
    super._integrate(y3, item);
    /** @type {Map<string, any>} */
    this._prelimAttrs.forEach((value, key2) => {
      this.setAttribute(key2, value);
    });
    this._prelimAttrs = null;
  }
  /**
   * Creates an Item with the same effect as this Item (without position effect)
   *
   * @return {YXmlElement}
   */
  _copy() {
    return new _YXmlElement(this.nodeName);
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YXmlElement<KV>}
   */
  clone() {
    const el2 = new _YXmlElement(this.nodeName);
    const attrs = this.getAttributes();
    forEach(attrs, (value, key2) => {
      el2.setAttribute(
        key2,
        /** @type {any} */
        value
      );
    });
    el2.insert(0, this.toArray().map((v8) => v8 instanceof AbstractType ? v8.clone() : v8));
    return el2;
  }
  /**
   * Returns the XML serialization of this YXmlElement.
   * The attributes are ordered by attribute-name, so you can easily use this
   * method to compare YXmlElements
   *
   * @return {string} The string representation of this type.
   *
   * @public
   */
  toString() {
    const attrs = this.getAttributes();
    const stringBuilder = [];
    const keys5 = [];
    for (const key2 in attrs) {
      keys5.push(key2);
    }
    keys5.sort();
    const keysLen = keys5.length;
    for (let i3 = 0; i3 < keysLen; i3++) {
      const key2 = keys5[i3];
      stringBuilder.push(key2 + '="' + attrs[key2] + '"');
    }
    const nodeName = this.nodeName.toLocaleLowerCase();
    const attrsString = stringBuilder.length > 0 ? " " + stringBuilder.join(" ") : "";
    return `<${nodeName}${attrsString}>${super.toString()}</${nodeName}>`;
  }
  /**
   * Removes an attribute from this YXmlElement.
   *
   * @param {string} attributeName The attribute name that is to be removed.
   *
   * @public
   */
  removeAttribute(attributeName) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapDelete(transaction, this, attributeName);
      });
    } else {
      this._prelimAttrs.delete(attributeName);
    }
  }
  /**
   * Sets or updates an attribute.
   *
   * @template {keyof KV & string} KEY
   *
   * @param {KEY} attributeName The attribute name that is to be set.
   * @param {KV[KEY]} attributeValue The attribute value that is to be set.
   *
   * @public
   */
  setAttribute(attributeName, attributeValue) {
    if (this.doc !== null) {
      transact(this.doc, (transaction) => {
        typeMapSet(transaction, this, attributeName, attributeValue);
      });
    } else {
      this._prelimAttrs.set(attributeName, attributeValue);
    }
  }
  /**
   * Returns an attribute value that belongs to the attribute name.
   *
   * @template {keyof KV & string} KEY
   *
   * @param {KEY} attributeName The attribute name that identifies the
   *                               queried value.
   * @return {KV[KEY]|undefined} The queried attribute value.
   *
   * @public
   */
  getAttribute(attributeName) {
    return (
      /** @type {any} */
      typeMapGet(this, attributeName)
    );
  }
  /**
   * Returns whether an attribute exists
   *
   * @param {string} attributeName The attribute name to check for existence.
   * @return {boolean} whether the attribute exists.
   *
   * @public
   */
  hasAttribute(attributeName) {
    return (
      /** @type {any} */
      typeMapHas(this, attributeName)
    );
  }
  /**
   * Returns all attribute name/value pairs in a JSON Object.
   *
   * @param {Snapshot} [snapshot]
   * @return {{ [Key in Extract<keyof KV,string>]?: KV[Key]}} A JSON Object that describes the attributes.
   *
   * @public
   */
  getAttributes(snapshot2) {
    return (
      /** @type {any} */
      snapshot2 ? typeMapGetAllSnapshot(this, snapshot2) : typeMapGetAll(this)
    );
  }
  /**
   * Creates a Dom Element that mirrors this YXmlElement.
   *
   * @param {Document} [_document=document] The document object (you must define
   *                                        this when calling this method in
   *                                        nodejs)
   * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks
   *                                             are presented in the DOM
   * @param {any} [binding] You should not set this property. This is
   *                               used if DomBinding wants to create a
   *                               association to the created DOM type.
   * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
   *
   * @public
   */
  toDOM(_document = document, hooks = {}, binding) {
    const dom = _document.createElement(this.nodeName);
    const attrs = this.getAttributes();
    for (const key2 in attrs) {
      const value = attrs[key2];
      if (typeof value === "string") {
        dom.setAttribute(key2, value);
      }
    }
    typeListForEach(this, (yxml) => {
      dom.appendChild(yxml.toDOM(_document, hooks, binding));
    });
    if (binding !== void 0) {
      binding._createAssociation(dom, this);
    }
    return dom;
  }
  /**
   * Transform the properties of this type to binary and write it to an
   * BinaryEncoder.
   *
   * This is called when this Item is sent to a remote peer.
   *
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   */
  _write(encoder) {
    encoder.writeTypeRef(YXmlElementRefID);
    encoder.writeKey(this.nodeName);
  }
};
var readYXmlElement = (decoder) => new YXmlElement(decoder.readKey());
var YXmlEvent = class extends YEvent {
  /**
   * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created.
   * @param {Set<string|null>} subs The set of changed attributes. `null` is included if the
   *                   child list changed.
   * @param {Transaction} transaction The transaction instance with which the
   *                                  change was created.
   */
  constructor(target, subs, transaction) {
    super(target, transaction);
    this.childListChanged = false;
    this.attributesChanged = /* @__PURE__ */ new Set();
    subs.forEach((sub) => {
      if (sub === null) {
        this.childListChanged = true;
      } else {
        this.attributesChanged.add(sub);
      }
    });
  }
};
var YXmlHook = class _YXmlHook extends YMap {
  /**
   * @param {string} hookName nodeName of the Dom Node.
   */
  constructor(hookName) {
    super();
    this.hookName = hookName;
  }
  /**
   * Creates an Item with the same effect as this Item (without position effect)
   */
  _copy() {
    return new _YXmlHook(this.hookName);
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YXmlHook}
   */
  clone() {
    const el2 = new _YXmlHook(this.hookName);
    this.forEach((value, key2) => {
      el2.set(key2, value);
    });
    return el2;
  }
  /**
   * Creates a Dom Element that mirrors this YXmlElement.
   *
   * @param {Document} [_document=document] The document object (you must define
   *                                        this when calling this method in
   *                                        nodejs)
   * @param {Object.<string, any>} [hooks] Optional property to customize how hooks
   *                                             are presented in the DOM
   * @param {any} [binding] You should not set this property. This is
   *                               used if DomBinding wants to create a
   *                               association to the created DOM type
   * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
   *
   * @public
   */
  toDOM(_document = document, hooks = {}, binding) {
    const hook = hooks[this.hookName];
    let dom;
    if (hook !== void 0) {
      dom = hook.createDom(this);
    } else {
      dom = document.createElement(this.hookName);
    }
    dom.setAttribute("data-yjs-hook", this.hookName);
    if (binding !== void 0) {
      binding._createAssociation(dom, this);
    }
    return dom;
  }
  /**
   * Transform the properties of this type to binary and write it to an
   * BinaryEncoder.
   *
   * This is called when this Item is sent to a remote peer.
   *
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   */
  _write(encoder) {
    encoder.writeTypeRef(YXmlHookRefID);
    encoder.writeKey(this.hookName);
  }
};
var readYXmlHook = (decoder) => new YXmlHook(decoder.readKey());
var YXmlText = class _YXmlText extends YText {
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get nextSibling() {
    const n = this._item ? this._item.next : null;
    return n ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      n.content.type
    ) : null;
  }
  /**
   * @type {YXmlElement|YXmlText|null}
   */
  get prevSibling() {
    const n = this._item ? this._item.prev : null;
    return n ? (
      /** @type {YXmlElement|YXmlText} */
      /** @type {ContentType} */
      n.content.type
    ) : null;
  }
  _copy() {
    return new _YXmlText();
  }
  /**
   * Makes a copy of this data type that can be included somewhere else.
   *
   * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
   *
   * @return {YXmlText}
   */
  clone() {
    const text10 = new _YXmlText();
    text10.applyDelta(this.toDelta());
    return text10;
  }
  /**
   * Creates a Dom Element that mirrors this YXmlText.
   *
   * @param {Document} [_document=document] The document object (you must define
   *                                        this when calling this method in
   *                                        nodejs)
   * @param {Object<string, any>} [hooks] Optional property to customize how hooks
   *                                             are presented in the DOM
   * @param {any} [binding] You should not set this property. This is
   *                               used if DomBinding wants to create a
   *                               association to the created DOM type.
   * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
   *
   * @public
   */
  toDOM(_document = document, hooks, binding) {
    const dom = _document.createTextNode(this.toString());
    if (binding !== void 0) {
      binding._createAssociation(dom, this);
    }
    return dom;
  }
  toString() {
    return this.toDelta().map((delta) => {
      const nestedNodes = [];
      for (const nodeName in delta.attributes) {
        const attrs = [];
        for (const key2 in delta.attributes[nodeName]) {
          attrs.push({ key: key2, value: delta.attributes[nodeName][key2] });
        }
        attrs.sort((a3, b4) => a3.key < b4.key ? -1 : 1);
        nestedNodes.push({ nodeName, attrs });
      }
      nestedNodes.sort((a3, b4) => a3.nodeName < b4.nodeName ? -1 : 1);
      let str = "";
      for (let i3 = 0; i3 < nestedNodes.length; i3++) {
        const node2 = nestedNodes[i3];
        str += `<${node2.nodeName}`;
        for (let j4 = 0; j4 < node2.attrs.length; j4++) {
          const attr2 = node2.attrs[j4];
          str += ` ${attr2.key}="${attr2.value}"`;
        }
        str += ">";
      }
      str += delta.insert;
      for (let i3 = nestedNodes.length - 1; i3 >= 0; i3--) {
        str += `</${nestedNodes[i3].nodeName}>`;
      }
      return str;
    }).join("");
  }
  /**
   * @return {string}
   */
  toJSON() {
    return this.toString();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   */
  _write(encoder) {
    encoder.writeTypeRef(YXmlTextRefID);
  }
};
var readYXmlText = (decoder) => new YXmlText();
var AbstractStruct = class {
  /**
   * @param {ID} id
   * @param {number} length
   */
  constructor(id2, length2) {
    this.id = id2;
    this.length = length2;
  }
  /**
   * @type {boolean}
   */
  get deleted() {
    throw methodUnimplemented();
  }
  /**
   * Merge this struct with the item to the right.
   * This method is already assuming that `this.id.clock + this.length === this.id.clock`.
   * Also this method does *not* remove right from StructStore!
   * @param {AbstractStruct} right
   * @return {boolean} whether this merged with right
   */
  mergeWith(right) {
    return false;
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   * @param {number} offset
   * @param {number} encodingRef
   */
  write(encoder, offset4, encodingRef) {
    throw methodUnimplemented();
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(transaction, offset4) {
    throw methodUnimplemented();
  }
};
var structGCRefNumber = 0;
var GC = class extends AbstractStruct {
  get deleted() {
    return true;
  }
  delete() {
  }
  /**
   * @param {GC} right
   * @return {boolean}
   */
  mergeWith(right) {
    if (this.constructor !== right.constructor) {
      return false;
    }
    this.length += right.length;
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(transaction, offset4) {
    if (offset4 > 0) {
      this.id.clock += offset4;
      this.length -= offset4;
    }
    addStruct(transaction.doc.store, this);
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    encoder.writeInfo(structGCRefNumber);
    encoder.writeLen(this.length - offset4);
  }
  /**
   * @param {Transaction} transaction
   * @param {StructStore} store
   * @return {null | number}
   */
  getMissing(transaction, store) {
    return null;
  }
};
var ContentBinary = class _ContentBinary {
  /**
   * @param {Uint8Array} content
   */
  constructor(content5) {
    this.content = content5;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.content];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentBinary}
   */
  copy() {
    return new _ContentBinary(this.content);
  }
  /**
   * @param {number} offset
   * @return {ContentBinary}
   */
  splice(offset4) {
    throw methodUnimplemented();
  }
  /**
   * @param {ContentBinary} right
   * @return {boolean}
   */
  mergeWith(right) {
    return false;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    encoder.writeBuf(this.content);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 3;
  }
};
var readContentBinary = (decoder) => new ContentBinary(decoder.readBuf());
var ContentDeleted = class _ContentDeleted {
  /**
   * @param {number} len
   */
  constructor(len) {
    this.len = len;
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.len;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return false;
  }
  /**
   * @return {ContentDeleted}
   */
  copy() {
    return new _ContentDeleted(this.len);
  }
  /**
   * @param {number} offset
   * @return {ContentDeleted}
   */
  splice(offset4) {
    const right = new _ContentDeleted(this.len - offset4);
    this.len = offset4;
    return right;
  }
  /**
   * @param {ContentDeleted} right
   * @return {boolean}
   */
  mergeWith(right) {
    this.len += right.len;
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
    addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len);
    item.markDeleted();
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    encoder.writeLen(this.len - offset4);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 1;
  }
};
var readContentDeleted = (decoder) => new ContentDeleted(decoder.readLen());
var createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false });
var ContentDoc = class _ContentDoc {
  /**
   * @param {Doc} doc
   */
  constructor(doc4) {
    if (doc4._item) {
      console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid.");
    }
    this.doc = doc4;
    const opts = {};
    this.opts = opts;
    if (!doc4.gc) {
      opts.gc = false;
    }
    if (doc4.autoLoad) {
      opts.autoLoad = true;
    }
    if (doc4.meta !== null) {
      opts.meta = doc4.meta;
    }
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.doc];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentDoc}
   */
  copy() {
    return new _ContentDoc(createDocFromOpts(this.doc.guid, this.opts));
  }
  /**
   * @param {number} offset
   * @return {ContentDoc}
   */
  splice(offset4) {
    throw methodUnimplemented();
  }
  /**
   * @param {ContentDoc} right
   * @return {boolean}
   */
  mergeWith(right) {
    return false;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
    this.doc._item = item;
    transaction.subdocsAdded.add(this.doc);
    if (this.doc.shouldLoad) {
      transaction.subdocsLoaded.add(this.doc);
    }
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
    if (transaction.subdocsAdded.has(this.doc)) {
      transaction.subdocsAdded.delete(this.doc);
    } else {
      transaction.subdocsRemoved.add(this.doc);
    }
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    encoder.writeString(this.doc.guid);
    encoder.writeAny(this.opts);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 9;
  }
};
var readContentDoc = (decoder) => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny()));
var ContentEmbed = class _ContentEmbed {
  /**
   * @param {Object} embed
   */
  constructor(embed) {
    this.embed = embed;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.embed];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentEmbed}
   */
  copy() {
    return new _ContentEmbed(this.embed);
  }
  /**
   * @param {number} offset
   * @return {ContentEmbed}
   */
  splice(offset4) {
    throw methodUnimplemented();
  }
  /**
   * @param {ContentEmbed} right
   * @return {boolean}
   */
  mergeWith(right) {
    return false;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    encoder.writeJSON(this.embed);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 5;
  }
};
var readContentEmbed = (decoder) => new ContentEmbed(decoder.readJSON());
var ContentFormat = class _ContentFormat {
  /**
   * @param {string} key
   * @param {Object} value
   */
  constructor(key2, value) {
    this.key = key2;
    this.value = value;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return false;
  }
  /**
   * @return {ContentFormat}
   */
  copy() {
    return new _ContentFormat(this.key, this.value);
  }
  /**
   * @param {number} _offset
   * @return {ContentFormat}
   */
  splice(_offset) {
    throw methodUnimplemented();
  }
  /**
   * @param {ContentFormat} _right
   * @return {boolean}
   */
  mergeWith(_right) {
    return false;
  }
  /**
   * @param {Transaction} _transaction
   * @param {Item} item
   */
  integrate(_transaction, item) {
    const p4 = (
      /** @type {YText} */
      item.parent
    );
    p4._searchMarker = null;
    p4._hasFormatting = true;
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    encoder.writeKey(this.key);
    encoder.writeJSON(this.value);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 6;
  }
};
var readContentFormat = (decoder) => new ContentFormat(decoder.readKey(), decoder.readJSON());
var ContentJSON = class _ContentJSON {
  /**
   * @param {Array<any>} arr
   */
  constructor(arr) {
    this.arr = arr;
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.arr.length;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return this.arr;
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentJSON}
   */
  copy() {
    return new _ContentJSON(this.arr);
  }
  /**
   * @param {number} offset
   * @return {ContentJSON}
   */
  splice(offset4) {
    const right = new _ContentJSON(this.arr.slice(offset4));
    this.arr = this.arr.slice(0, offset4);
    return right;
  }
  /**
   * @param {ContentJSON} right
   * @return {boolean}
   */
  mergeWith(right) {
    this.arr = this.arr.concat(right.arr);
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    const len = this.arr.length;
    encoder.writeLen(len - offset4);
    for (let i3 = offset4; i3 < len; i3++) {
      const c3 = this.arr[i3];
      encoder.writeString(c3 === void 0 ? "undefined" : JSON.stringify(c3));
    }
  }
  /**
   * @return {number}
   */
  getRef() {
    return 2;
  }
};
var readContentJSON = (decoder) => {
  const len = decoder.readLen();
  const cs = [];
  for (let i3 = 0; i3 < len; i3++) {
    const c3 = decoder.readString();
    if (c3 === "undefined") {
      cs.push(void 0);
    } else {
      cs.push(JSON.parse(c3));
    }
  }
  return new ContentJSON(cs);
};
var isDevMode = getVariable("node_env") === "development";
var ContentAny = class _ContentAny {
  /**
   * @param {Array<any>} arr
   */
  constructor(arr) {
    this.arr = arr;
    isDevMode && deepFreeze(arr);
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.arr.length;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return this.arr;
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentAny}
   */
  copy() {
    return new _ContentAny(this.arr);
  }
  /**
   * @param {number} offset
   * @return {ContentAny}
   */
  splice(offset4) {
    const right = new _ContentAny(this.arr.slice(offset4));
    this.arr = this.arr.slice(0, offset4);
    return right;
  }
  /**
   * @param {ContentAny} right
   * @return {boolean}
   */
  mergeWith(right) {
    this.arr = this.arr.concat(right.arr);
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    const len = this.arr.length;
    encoder.writeLen(len - offset4);
    for (let i3 = offset4; i3 < len; i3++) {
      const c3 = this.arr[i3];
      encoder.writeAny(c3);
    }
  }
  /**
   * @return {number}
   */
  getRef() {
    return 8;
  }
};
var readContentAny = (decoder) => {
  const len = decoder.readLen();
  const cs = [];
  for (let i3 = 0; i3 < len; i3++) {
    cs.push(decoder.readAny());
  }
  return new ContentAny(cs);
};
var ContentString = class _ContentString {
  /**
   * @param {string} str
   */
  constructor(str) {
    this.str = str;
  }
  /**
   * @return {number}
   */
  getLength() {
    return this.str.length;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return this.str.split("");
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentString}
   */
  copy() {
    return new _ContentString(this.str);
  }
  /**
   * @param {number} offset
   * @return {ContentString}
   */
  splice(offset4) {
    const right = new _ContentString(this.str.slice(offset4));
    this.str = this.str.slice(0, offset4);
    const firstCharCode = this.str.charCodeAt(offset4 - 1);
    if (firstCharCode >= 55296 && firstCharCode <= 56319) {
      this.str = this.str.slice(0, offset4 - 1) + "�";
      right.str = "�" + right.str.slice(1);
    }
    return right;
  }
  /**
   * @param {ContentString} right
   * @return {boolean}
   */
  mergeWith(right) {
    this.str += right.str;
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    encoder.writeString(offset4 === 0 ? this.str : this.str.slice(offset4));
  }
  /**
   * @return {number}
   */
  getRef() {
    return 4;
  }
};
var readContentString = (decoder) => new ContentString(decoder.readString());
var typeRefs = [
  readYArray,
  readYMap,
  readYText,
  readYXmlElement,
  readYXmlFragment,
  readYXmlHook,
  readYXmlText
];
var YArrayRefID = 0;
var YMapRefID = 1;
var YTextRefID = 2;
var YXmlElementRefID = 3;
var YXmlFragmentRefID = 4;
var YXmlHookRefID = 5;
var YXmlTextRefID = 6;
var ContentType = class _ContentType {
  /**
   * @param {AbstractType<any>} type
   */
  constructor(type) {
    this.type = type;
  }
  /**
   * @return {number}
   */
  getLength() {
    return 1;
  }
  /**
   * @return {Array<any>}
   */
  getContent() {
    return [this.type];
  }
  /**
   * @return {boolean}
   */
  isCountable() {
    return true;
  }
  /**
   * @return {ContentType}
   */
  copy() {
    return new _ContentType(this.type._copy());
  }
  /**
   * @param {number} offset
   * @return {ContentType}
   */
  splice(offset4) {
    throw methodUnimplemented();
  }
  /**
   * @param {ContentType} right
   * @return {boolean}
   */
  mergeWith(right) {
    return false;
  }
  /**
   * @param {Transaction} transaction
   * @param {Item} item
   */
  integrate(transaction, item) {
    this.type._integrate(transaction.doc, item);
  }
  /**
   * @param {Transaction} transaction
   */
  delete(transaction) {
    let item = this.type._start;
    while (item !== null) {
      if (!item.deleted) {
        item.delete(transaction);
      } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {
        transaction._mergeStructs.push(item);
      }
      item = item.right;
    }
    this.type._map.forEach((item2) => {
      if (!item2.deleted) {
        item2.delete(transaction);
      } else if (item2.id.clock < (transaction.beforeState.get(item2.id.client) || 0)) {
        transaction._mergeStructs.push(item2);
      }
    });
    transaction.changed.delete(this.type);
  }
  /**
   * @param {StructStore} store
   */
  gc(store) {
    let item = this.type._start;
    while (item !== null) {
      item.gc(store, true);
      item = item.right;
    }
    this.type._start = null;
    this.type._map.forEach(
      /** @param {Item | null} item */
      (item2) => {
        while (item2 !== null) {
          item2.gc(store, true);
          item2 = item2.left;
        }
      }
    );
    this.type._map = /* @__PURE__ */ new Map();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    this.type._write(encoder);
  }
  /**
   * @return {number}
   */
  getRef() {
    return 7;
  }
};
var readContentType = (decoder) => new ContentType(typeRefs[decoder.readTypeRef()](decoder));
var followRedone = (store, id2) => {
  let nextID = id2;
  let diff = 0;
  let item;
  do {
    if (diff > 0) {
      nextID = createID(nextID.client, nextID.clock + diff);
    }
    item = getItem(store, nextID);
    diff = nextID.clock - item.id.clock;
    nextID = item.redone;
  } while (nextID !== null && item instanceof Item);
  return {
    item,
    diff
  };
};
var keepItem = (item, keep) => {
  while (item !== null && item.keep !== keep) {
    item.keep = keep;
    item = /** @type {AbstractType<any>} */
    item.parent._item;
  }
};
var splitItem = (transaction, leftItem, diff) => {
  const { client, clock } = leftItem.id;
  const rightItem = new Item(
    createID(client, clock + diff),
    leftItem,
    createID(client, clock + diff - 1),
    leftItem.right,
    leftItem.rightOrigin,
    leftItem.parent,
    leftItem.parentSub,
    leftItem.content.splice(diff)
  );
  if (leftItem.deleted) {
    rightItem.markDeleted();
  }
  if (leftItem.keep) {
    rightItem.keep = true;
  }
  if (leftItem.redone !== null) {
    rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff);
  }
  leftItem.right = rightItem;
  if (rightItem.right !== null) {
    rightItem.right.left = rightItem;
  }
  transaction._mergeStructs.push(rightItem);
  if (rightItem.parentSub !== null && rightItem.right === null) {
    rightItem.parent._map.set(rightItem.parentSub, rightItem);
  }
  leftItem.length = diff;
  return rightItem;
};
var isDeletedByUndoStack = (stack, id2) => some(
  stack,
  /** @param {StackItem} s */
  (s2) => isDeleted(s2.deletions, id2)
);
var redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) => {
  const doc4 = transaction.doc;
  const store = doc4.store;
  const ownClientID = doc4.clientID;
  const redone = item.redone;
  if (redone !== null) {
    return getItemCleanStart(transaction, redone);
  }
  let parentItem = (
    /** @type {AbstractType<any>} */
    item.parent._item
  );
  let left = null;
  let right;
  if (parentItem !== null && parentItem.deleted === true) {
    if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) === null)) {
      return null;
    }
    while (parentItem.redone !== null) {
      parentItem = getItemCleanStart(transaction, parentItem.redone);
    }
  }
  const parentType = parentItem === null ? (
    /** @type {AbstractType<any>} */
    item.parent
  ) : (
    /** @type {ContentType} */
    parentItem.content.type
  );
  if (item.parentSub === null) {
    left = item.left;
    right = item;
    while (left !== null) {
      let leftTrace = left;
      while (leftTrace !== null && /** @type {AbstractType<any>} */
      leftTrace.parent._item !== parentItem) {
        leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone);
      }
      if (leftTrace !== null && /** @type {AbstractType<any>} */
      leftTrace.parent._item === parentItem) {
        left = leftTrace;
        break;
      }
      left = left.left;
    }
    while (right !== null) {
      let rightTrace = right;
      while (rightTrace !== null && /** @type {AbstractType<any>} */
      rightTrace.parent._item !== parentItem) {
        rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone);
      }
      if (rightTrace !== null && /** @type {AbstractType<any>} */
      rightTrace.parent._item === parentItem) {
        right = rightTrace;
        break;
      }
      right = right.right;
    }
  } else {
    right = null;
    if (item.right && !ignoreRemoteMapChanges) {
      left = item;
      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))) {
        left = left.right;
        while (left.redone) left = getItemCleanStart(transaction, left.redone);
      }
      if (left && left.right !== null) {
        return null;
      }
    } else {
      left = parentType._map.get(item.parentSub) || null;
    }
  }
  const nextClock = getState(store, ownClientID);
  const nextId = createID(ownClientID, nextClock);
  const redoneItem = new Item(
    nextId,
    left,
    left && left.lastId,
    right,
    right && right.id,
    parentType,
    item.parentSub,
    item.content.copy()
  );
  item.redone = nextId;
  keepItem(redoneItem, true);
  redoneItem.integrate(transaction, 0);
  return redoneItem;
};
var Item = class _Item extends AbstractStruct {
  /**
   * @param {ID} id
   * @param {Item | null} left
   * @param {ID | null} origin
   * @param {Item | null} right
   * @param {ID | null} rightOrigin
   * @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.
   * @param {string | null} parentSub
   * @param {AbstractContent} content
   */
  constructor(id2, left, origin, right, rightOrigin, parent, parentSub, content5) {
    super(id2, content5.getLength());
    this.origin = origin;
    this.left = left;
    this.right = right;
    this.rightOrigin = rightOrigin;
    this.parent = parent;
    this.parentSub = parentSub;
    this.redone = null;
    this.content = content5;
    this.info = this.content.isCountable() ? BIT2 : 0;
  }
  /**
   * This is used to mark the item as an indexed fast-search marker
   *
   * @type {boolean}
   */
  set marker(isMarked) {
    if ((this.info & BIT4) > 0 !== isMarked) {
      this.info ^= BIT4;
    }
  }
  get marker() {
    return (this.info & BIT4) > 0;
  }
  /**
   * If true, do not garbage collect this Item.
   */
  get keep() {
    return (this.info & BIT1) > 0;
  }
  set keep(doKeep) {
    if (this.keep !== doKeep) {
      this.info ^= BIT1;
    }
  }
  get countable() {
    return (this.info & BIT2) > 0;
  }
  /**
   * Whether this item was deleted or not.
   * @type {Boolean}
   */
  get deleted() {
    return (this.info & BIT3) > 0;
  }
  set deleted(doDelete) {
    if (this.deleted !== doDelete) {
      this.info ^= BIT3;
    }
  }
  markDeleted() {
    this.info |= BIT3;
  }
  /**
   * Return the creator clientID of the missing op or define missing items and return null.
   *
   * @param {Transaction} transaction
   * @param {StructStore} store
   * @return {null | number}
   */
  getMissing(transaction, store) {
    if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store, this.origin.client)) {
      return this.origin.client;
    }
    if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store, this.rightOrigin.client)) {
      return this.rightOrigin.client;
    }
    if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store, this.parent.client)) {
      return this.parent.client;
    }
    if (this.origin) {
      this.left = getItemCleanEnd(transaction, store, this.origin);
      this.origin = this.left.lastId;
    }
    if (this.rightOrigin) {
      this.right = getItemCleanStart(transaction, this.rightOrigin);
      this.rightOrigin = this.right.id;
    }
    if (this.left && this.left.constructor === GC || this.right && this.right.constructor === GC) {
      this.parent = null;
    } else if (!this.parent) {
      if (this.left && this.left.constructor === _Item) {
        this.parent = this.left.parent;
        this.parentSub = this.left.parentSub;
      } else if (this.right && this.right.constructor === _Item) {
        this.parent = this.right.parent;
        this.parentSub = this.right.parentSub;
      }
    } else if (this.parent.constructor === ID) {
      const parentItem = getItem(store, this.parent);
      if (parentItem.constructor === GC) {
        this.parent = null;
      } else {
        this.parent = /** @type {ContentType} */
        parentItem.content.type;
      }
    }
    return null;
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(transaction, offset4) {
    if (offset4 > 0) {
      this.id.clock += offset4;
      this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1));
      this.origin = this.left.lastId;
      this.content = this.content.splice(offset4);
      this.length -= offset4;
    }
    if (this.parent) {
      if (!this.left && (!this.right || this.right.left !== null) || this.left && this.left.right !== this.right) {
        let left = this.left;
        let o2;
        if (left !== null) {
          o2 = left.right;
        } else if (this.parentSub !== null) {
          o2 = /** @type {AbstractType<any>} */
          this.parent._map.get(this.parentSub) || null;
          while (o2 !== null && o2.left !== null) {
            o2 = o2.left;
          }
        } else {
          o2 = /** @type {AbstractType<any>} */
          this.parent._start;
        }
        const conflictingItems = /* @__PURE__ */ new Set();
        const itemsBeforeOrigin = /* @__PURE__ */ new Set();
        while (o2 !== null && o2 !== this.right) {
          itemsBeforeOrigin.add(o2);
          conflictingItems.add(o2);
          if (compareIDs(this.origin, o2.origin)) {
            if (o2.id.client < this.id.client) {
              left = o2;
              conflictingItems.clear();
            } else if (compareIDs(this.rightOrigin, o2.rightOrigin)) {
              break;
            }
          } else if (o2.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o2.origin))) {
            if (!conflictingItems.has(getItem(transaction.doc.store, o2.origin))) {
              left = o2;
              conflictingItems.clear();
            }
          } else {
            break;
          }
          o2 = o2.right;
        }
        this.left = left;
      }
      if (this.left !== null) {
        const right = this.left.right;
        this.right = right;
        this.left.right = this;
      } else {
        let r4;
        if (this.parentSub !== null) {
          r4 = /** @type {AbstractType<any>} */
          this.parent._map.get(this.parentSub) || null;
          while (r4 !== null && r4.left !== null) {
            r4 = r4.left;
          }
        } else {
          r4 = /** @type {AbstractType<any>} */
          this.parent._start;
          this.parent._start = this;
        }
        this.right = r4;
      }
      if (this.right !== null) {
        this.right.left = this;
      } else if (this.parentSub !== null) {
        this.parent._map.set(this.parentSub, this);
        if (this.left !== null) {
          this.left.delete(transaction);
        }
      }
      if (this.parentSub === null && this.countable && !this.deleted) {
        this.parent._length += this.length;
      }
      addStruct(transaction.doc.store, this);
      this.content.integrate(transaction, this);
      addChangedTypeToTransaction(
        transaction,
        /** @type {AbstractType<any>} */
        this.parent,
        this.parentSub
      );
      if (
        /** @type {AbstractType<any>} */
        this.parent._item !== null && /** @type {AbstractType<any>} */
        this.parent._item.deleted || this.parentSub !== null && this.right !== null
      ) {
        this.delete(transaction);
      }
    } else {
      new GC(this.id, this.length).integrate(transaction, 0);
    }
  }
  /**
   * Returns the next non-deleted item
   */
  get next() {
    let n = this.right;
    while (n !== null && n.deleted) {
      n = n.right;
    }
    return n;
  }
  /**
   * Returns the previous non-deleted item
   */
  get prev() {
    let n = this.left;
    while (n !== null && n.deleted) {
      n = n.left;
    }
    return n;
  }
  /**
   * Computes the last content address of this Item.
   */
  get lastId() {
    return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1);
  }
  /**
   * Try to merge two items
   *
   * @param {Item} right
   * @return {boolean}
   */
  mergeWith(right) {
    if (this.constructor === right.constructor && compareIDs(right.origin, this.lastId) && this.right === right && compareIDs(this.rightOrigin, right.rightOrigin) && this.id.client === right.id.client && this.id.clock + this.length === right.id.clock && this.deleted === right.deleted && this.redone === null && right.redone === null && this.content.constructor === right.content.constructor && this.content.mergeWith(right.content)) {
      const searchMarker = (
        /** @type {AbstractType<any>} */
        this.parent._searchMarker
      );
      if (searchMarker) {
        searchMarker.forEach((marker) => {
          if (marker.p === right) {
            marker.p = this;
            if (!this.deleted && this.countable) {
              marker.index -= this.length;
            }
          }
        });
      }
      if (right.keep) {
        this.keep = true;
      }
      this.right = right.right;
      if (this.right !== null) {
        this.right.left = this;
      }
      this.length += right.length;
      return true;
    }
    return false;
  }
  /**
   * Mark this Item as deleted.
   *
   * @param {Transaction} transaction
   */
  delete(transaction) {
    if (!this.deleted) {
      const parent = (
        /** @type {AbstractType<any>} */
        this.parent
      );
      if (this.countable && this.parentSub === null) {
        parent._length -= this.length;
      }
      this.markDeleted();
      addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length);
      addChangedTypeToTransaction(transaction, parent, this.parentSub);
      this.content.delete(transaction);
    }
  }
  /**
   * @param {StructStore} store
   * @param {boolean} parentGCd
   */
  gc(store, parentGCd) {
    if (!this.deleted) {
      throw unexpectedCase();
    }
    this.content.gc(store);
    if (parentGCd) {
      replaceStruct(store, this, new GC(this.id, this.length));
    } else {
      this.content = new ContentDeleted(this.length);
    }
  }
  /**
   * Transform the properties of this type to binary and write it to an
   * BinaryEncoder.
   *
   * This is called when this Item is sent to a remote peer.
   *
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
   * @param {number} offset
   */
  write(encoder, offset4) {
    const origin = offset4 > 0 ? createID(this.id.client, this.id.clock + offset4 - 1) : this.origin;
    const rightOrigin = this.rightOrigin;
    const parentSub = this.parentSub;
    const info = this.content.getRef() & BITS5 | (origin === null ? 0 : BIT8) | // origin is defined
    (rightOrigin === null ? 0 : BIT7) | // right origin is defined
    (parentSub === null ? 0 : BIT6);
    encoder.writeInfo(info);
    if (origin !== null) {
      encoder.writeLeftID(origin);
    }
    if (rightOrigin !== null) {
      encoder.writeRightID(rightOrigin);
    }
    if (origin === null && rightOrigin === null) {
      const parent = (
        /** @type {AbstractType<any>} */
        this.parent
      );
      if (parent._item !== void 0) {
        const parentItem = parent._item;
        if (parentItem === null) {
          const ykey = findRootTypeKey(parent);
          encoder.writeParentInfo(true);
          encoder.writeString(ykey);
        } else {
          encoder.writeParentInfo(false);
          encoder.writeLeftID(parentItem.id);
        }
      } else if (parent.constructor === String) {
        encoder.writeParentInfo(true);
        encoder.writeString(parent);
      } else if (parent.constructor === ID) {
        encoder.writeParentInfo(false);
        encoder.writeLeftID(parent);
      } else {
        unexpectedCase();
      }
      if (parentSub !== null) {
        encoder.writeString(parentSub);
      }
    }
    this.content.write(encoder, offset4);
  }
};
var readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder);
var contentRefs = [
  () => {
    unexpectedCase();
  },
  // GC is not ItemContent
  readContentDeleted,
  // 1
  readContentJSON,
  // 2
  readContentBinary,
  // 3
  readContentString,
  // 4
  readContentEmbed,
  // 5
  readContentFormat,
  // 6
  readContentType,
  // 7
  readContentAny,
  // 8
  readContentDoc,
  // 9
  () => {
    unexpectedCase();
  }
  // 10 - Skip is not ItemContent
];
var structSkipRefNumber = 10;
var Skip = class extends AbstractStruct {
  get deleted() {
    return true;
  }
  delete() {
  }
  /**
   * @param {Skip} right
   * @return {boolean}
   */
  mergeWith(right) {
    if (this.constructor !== right.constructor) {
      return false;
    }
    this.length += right.length;
    return true;
  }
  /**
   * @param {Transaction} transaction
   * @param {number} offset
   */
  integrate(transaction, offset4) {
    unexpectedCase();
  }
  /**
   * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
   * @param {number} offset
   */
  write(encoder, offset4) {
    encoder.writeInfo(structSkipRefNumber);
    writeVarUint(encoder.restEncoder, this.length - offset4);
  }
  /**
   * @param {Transaction} transaction
   * @param {StructStore} store
   * @return {null | number}
   */
  getMissing(transaction, store) {
    return null;
  }
};
var glo = (
  /** @type {any} */
  typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}
);
var importIdentifier = "__ $YJS$ __";
if (glo[importIdentifier] === true) {
  console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");
}
glo[importIdentifier] = true;

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/mutex.js
var createMutex = () => {
  let token = true;
  return (f6, g) => {
    if (token) {
      token = false;
      try {
        f6();
      } finally {
        token = true;
      }
    } else if (g !== void 0) {
      g();
    }
  };
};

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/diff.js
var highSurrogateRegex = /[\uD800-\uDBFF]/;
var lowSurrogateRegex = /[\uDC00-\uDFFF]/;
var simpleDiffString = (a3, b4) => {
  let left = 0;
  let right = 0;
  while (left < a3.length && left < b4.length && a3[left] === b4[left]) {
    left++;
  }
  if (left > 0 && highSurrogateRegex.test(a3[left - 1])) left--;
  while (right + left < a3.length && right + left < b4.length && a3[a3.length - right - 1] === b4[b4.length - right - 1]) {
    right++;
  }
  if (right > 0 && lowSurrogateRegex.test(a3[a3.length - right])) right--;
  return {
    index: left,
    remove: a3.length - left - right,
    insert: b4.slice(left, b4.length - right)
  };
};
var simpleDiff = simpleDiffString;

// ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/plugins/keys.js
var ySyncPluginKey = new PluginKey("y-sync");
var yUndoPluginKey = new PluginKey("y-undo");
var yCursorPluginKey = new PluginKey("yjs-cursor");

// ../../node_modules/.pnpm/lib0@0.2.116/node_modules/lib0/hash/sha256.js
var rotr = (w3, shift5) => w3 >>> shift5 | w3 << 32 - shift5;
var sum0to256 = (x5) => rotr(x5, 2) ^ rotr(x5, 13) ^ rotr(x5, 22);
var sum1to256 = (x5) => rotr(x5, 6) ^ rotr(x5, 11) ^ rotr(x5, 25);
var sigma0to256 = (x5) => rotr(x5, 7) ^ rotr(x5, 18) ^ x5 >>> 3;
var sigma1to256 = (x5) => rotr(x5, 17) ^ rotr(x5, 19) ^ x5 >>> 10;
var K = new Uint32Array([
  1116352408,
  1899447441,
  3049323471,
  3921009573,
  961987163,
  1508970993,
  2453635748,
  2870763221,
  3624381080,
  310598401,
  607225278,
  1426881987,
  1925078388,
  2162078206,
  2614888103,
  3248222580,
  3835390401,
  4022224774,
  264347078,
  604807628,
  770255983,
  1249150122,
  1555081692,
  1996064986,
  2554220882,
  2821834349,
  2952996808,
  3210313671,
  3336571891,
  3584528711,
  113926993,
  338241895,
  666307205,
  773529912,
  1294757372,
  1396182291,
  1695183700,
  1986661051,
  2177026350,
  2456956037,
  2730485921,
  2820302411,
  3259730800,
  3345764771,
  3516065817,
  3600352804,
  4094571909,
  275423344,
  430227734,
  506948616,
  659060556,
  883997877,
  958139571,
  1322822218,
  1537002063,
  1747873779,
  1955562222,
  2024104815,
  2227730452,
  2361852424,
  2428436474,
  2756734187,
  3204031479,
  3329325298
]);
var HINIT = new Uint32Array([
  1779033703,
  3144134277,
  1013904242,
  2773480762,
  1359893119,
  2600822924,
  528734635,
  1541459225
]);
var Hasher = class {
  constructor() {
    const buf = new ArrayBuffer(64 + 64 * 4);
    this._H = new Uint32Array(buf, 0, 8);
    this._H.set(HINIT);
    this._W = new Uint32Array(buf, 64, 64);
  }
  _updateHash() {
    const H4 = this._H;
    const W3 = this._W;
    for (let t2 = 16; t2 < 64; t2++) {
      W3[t2] = sigma1to256(W3[t2 - 2]) + W3[t2 - 7] + sigma0to256(W3[t2 - 15]) + W3[t2 - 16];
    }
    let a3 = H4[0];
    let b4 = H4[1];
    let c3 = H4[2];
    let d = H4[3];
    let e2 = H4[4];
    let f6 = H4[5];
    let g = H4[6];
    let h7 = H4[7];
    for (let tt3 = 0, T1, T22; tt3 < 64; tt3++) {
      T1 = h7 + sum1to256(e2) + (e2 & f6 ^ ~e2 & g) + K[tt3] + W3[tt3] >>> 0;
      T22 = sum0to256(a3) + (a3 & b4 ^ a3 & c3 ^ b4 & c3) >>> 0;
      h7 = g;
      g = f6;
      f6 = e2;
      e2 = d + T1 >>> 0;
      d = c3;
      c3 = b4;
      b4 = a3;
      a3 = T1 + T22 >>> 0;
    }
    H4[0] += a3;
    H4[1] += b4;
    H4[2] += c3;
    H4[3] += d;
    H4[4] += e2;
    H4[5] += f6;
    H4[6] += g;
    H4[7] += h7;
  }
  /**
   * Returns a 32-byte hash.
   *
   * @param {Uint8Array} data
   */
  digest(data) {
    let i3 = 0;
    for (; i3 + 56 <= data.length; ) {
      let j5 = 0;
      for (; j5 < 16 && i3 + 3 < data.length; j5++) {
        this._W[j5] = data[i3++] << 24 | data[i3++] << 16 | data[i3++] << 8 | data[i3++];
      }
      if (i3 % 64 !== 0) {
        this._W.fill(0, j5, 16);
        while (i3 < data.length) {
          this._W[j5] |= data[i3] << (3 - i3 % 4) * 8;
          i3++;
        }
        this._W[j5] |= BIT8 << (3 - i3 % 4) * 8;
      }
      this._updateHash();
    }
    const isPaddedWith1 = i3 % 64 !== 0;
    this._W.fill(0, 0, 16);
    let j4 = 0;
    for (; i3 < data.length; j4++) {
      for (let ci2 = 3; ci2 >= 0 && i3 < data.length; ci2--) {
        this._W[j4] |= data[i3++] << ci2 * 8;
      }
    }
    if (!isPaddedWith1) {
      this._W[j4 - (i3 % 4 === 0 ? 0 : 1)] |= BIT8 << (3 - i3 % 4) * 8;
    }
    this._W[14] = data.byteLength / BIT30;
    this._W[15] = data.byteLength * 8;
    this._updateHash();
    const dv = new Uint8Array(32);
    for (let i4 = 0; i4 < this._H.length; i4++) {
      for (let ci2 = 0; ci2 < 4; ci2++) {
        dv[i4 * 4 + ci2] = this._H[i4] >>> (3 - ci2) * 8;
      }
    }
    return dv;
  }
};
var digest = (data) => new Hasher().digest(data);

// ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/utils.js
var _convolute = (digest2) => {
  const N3 = 6;
  for (let i3 = N3; i3 < digest2.length; i3++) {
    digest2[i3 % N3] = digest2[i3 % N3] ^ digest2[i3];
  }
  return digest2.slice(0, N3);
};
var hashOfJSON = (json) => toBase64(_convolute(digest(encodeAny(json))));

// ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/plugins/sync-plugin.js
var isVisible2 = (item, snapshot2) => snapshot2 === void 0 ? !item.deleted : snapshot2.sv.has(item.id.client) && /** @type {number} */
snapshot2.sv.get(item.id.client) > item.id.clock && !isDeleted(snapshot2.ds, item.id);
var defaultColors = [{ light: "#ecd44433", dark: "#ecd444" }];
var getUserColor = (colorMapping, colors, user) => {
  if (!colorMapping.has(user)) {
    if (colorMapping.size < colors.length) {
      const usedColors = create2();
      colorMapping.forEach((color2) => usedColors.add(color2));
      colors = colors.filter((color2) => !usedColors.has(color2));
    }
    colorMapping.set(user, oneOf(colors));
  }
  return (
    /** @type {ColorDef} */
    colorMapping.get(user)
  );
};
var ySyncPlugin = (yXmlFragment, {
  colors = defaultColors,
  colorMapping = /* @__PURE__ */ new Map(),
  permanentUserData = null,
  onFirstRender = () => {
  },
  mapping
} = {}) => {
  let initialContentChanged = false;
  const binding = new ProsemirrorBinding(yXmlFragment, mapping);
  const plugin = new Plugin({
    props: {
      editable: (state) => {
        const syncState = ySyncPluginKey.getState(state);
        return syncState.snapshot == null && syncState.prevSnapshot == null;
      }
    },
    key: ySyncPluginKey,
    state: {
      /**
       * @returns {any}
       */
      init: (_initargs, _state) => {
        return {
          type: yXmlFragment,
          doc: yXmlFragment.doc,
          binding,
          snapshot: null,
          prevSnapshot: null,
          isChangeOrigin: false,
          isUndoRedoOperation: false,
          addToHistory: true,
          colors,
          colorMapping,
          permanentUserData
        };
      },
      apply: (tr4, pluginState) => {
        const change = tr4.getMeta(ySyncPluginKey);
        if (change !== void 0) {
          pluginState = Object.assign({}, pluginState);
          for (const key2 in change) {
            pluginState[key2] = change[key2];
          }
        }
        pluginState.addToHistory = tr4.getMeta("addToHistory") !== false;
        pluginState.isChangeOrigin = change !== void 0 && !!change.isChangeOrigin;
        pluginState.isUndoRedoOperation = change !== void 0 && !!change.isChangeOrigin && !!change.isUndoRedoOperation;
        if (binding.prosemirrorView !== null) {
          if (change !== void 0 && (change.snapshot != null || change.prevSnapshot != null)) {
            timeout(0, () => {
              if (binding.prosemirrorView == null) {
                return;
              }
              if (change.restore == null) {
                binding._renderSnapshot(
                  change.snapshot,
                  change.prevSnapshot,
                  pluginState
                );
              } else {
                binding._renderSnapshot(
                  change.snapshot,
                  change.snapshot,
                  pluginState
                );
                delete pluginState.restore;
                delete pluginState.snapshot;
                delete pluginState.prevSnapshot;
                binding.mux(() => {
                  binding._prosemirrorChanged(
                    binding.prosemirrorView.state.doc
                  );
                });
              }
            });
          }
        }
        return pluginState;
      }
    },
    view: (view) => {
      binding.initView(view);
      if (mapping == null) {
        binding._forceRerender();
      }
      onFirstRender();
      return {
        update: () => {
          const pluginState = plugin.getState(view.state);
          if (pluginState.snapshot == null && pluginState.prevSnapshot == null) {
            if (
              // If the content doesn't change initially, we don't render anything to Yjs
              // If the content was cleared by a user action, we want to catch the change and
              // represent it in Yjs
              initialContentChanged || view.state.doc.content.findDiffStart(
                view.state.doc.type.createAndFill().content
              ) !== null
            ) {
              initialContentChanged = true;
              if (pluginState.addToHistory === false && !pluginState.isChangeOrigin) {
                const yUndoPluginState = yUndoPluginKey.getState(view.state);
                const um = yUndoPluginState && yUndoPluginState.undoManager;
                if (um) {
                  um.stopCapturing();
                }
              }
              binding.mux(() => {
                pluginState.doc.transact((tr4) => {
                  tr4.meta.set("addToHistory", pluginState.addToHistory);
                  binding._prosemirrorChanged(view.state.doc);
                }, ySyncPluginKey);
              });
            }
          }
        },
        destroy: () => {
          binding.destroy();
        }
      };
    }
  });
  return plugin;
};
var restoreRelativeSelection = (tr4, relSel, binding) => {
  if (relSel !== null && relSel.anchor !== null && relSel.head !== null) {
    if (relSel.type === "all") {
      tr4.setSelection(new AllSelection(tr4.doc));
    } else if (relSel.type === "node") {
      const anchor = relativePositionToAbsolutePosition(
        binding.doc,
        binding.type,
        relSel.anchor,
        binding.mapping
      );
      tr4.setSelection(NodeSelection.create(tr4.doc, anchor));
    } else {
      const anchor = relativePositionToAbsolutePosition(
        binding.doc,
        binding.type,
        relSel.anchor,
        binding.mapping
      );
      const head2 = relativePositionToAbsolutePosition(
        binding.doc,
        binding.type,
        relSel.head,
        binding.mapping
      );
      if (anchor !== null && head2 !== null) {
        const sel = TextSelection.between(tr4.doc.resolve(anchor), tr4.doc.resolve(head2));
        tr4.setSelection(sel);
      }
    }
  }
};
var getRelativeSelection = (pmbinding, state) => ({
  type: (
    /** @type {any} */
    state.selection.jsonID
  ),
  anchor: absolutePositionToRelativePosition(
    state.selection.anchor,
    pmbinding.type,
    pmbinding.mapping
  ),
  head: absolutePositionToRelativePosition(
    state.selection.head,
    pmbinding.type,
    pmbinding.mapping
  )
});
var ProsemirrorBinding = class {
  /**
   * @param {Y.XmlFragment} yXmlFragment The bind source
   * @param {ProsemirrorMapping} mapping
   */
  constructor(yXmlFragment, mapping = /* @__PURE__ */ new Map()) {
    this.type = yXmlFragment;
    this.prosemirrorView = null;
    this.mux = createMutex();
    this.mapping = mapping;
    this.isOMark = /* @__PURE__ */ new Map();
    this._observeFunction = this._typeChanged.bind(this);
    this.doc = yXmlFragment.doc;
    this.beforeTransactionSelection = null;
    this.beforeAllTransactions = () => {
      if (this.beforeTransactionSelection === null && this.prosemirrorView != null) {
        this.beforeTransactionSelection = getRelativeSelection(
          this,
          this.prosemirrorView.state
        );
      }
    };
    this.afterAllTransactions = () => {
      this.beforeTransactionSelection = null;
    };
    this._domSelectionInView = null;
  }
  /**
   * Create a transaction for changing the prosemirror state.
   *
   * @returns
   */
  get _tr() {
    return this.prosemirrorView.state.tr.setMeta("addToHistory", false);
  }
  _isLocalCursorInView() {
    if (!this.prosemirrorView.hasFocus()) return false;
    if (isBrowser && this._domSelectionInView === null) {
      timeout(0, () => {
        this._domSelectionInView = null;
      });
      this._domSelectionInView = this._isDomSelectionInView();
    }
    return this._domSelectionInView;
  }
  _isDomSelectionInView() {
    const selection = this.prosemirrorView._root.getSelection();
    if (selection == null || selection.anchorNode == null) return false;
    const range = this.prosemirrorView._root.createRange();
    range.setStart(selection.anchorNode, selection.anchorOffset);
    range.setEnd(selection.focusNode, selection.focusOffset);
    const rects = range.getClientRects();
    if (rects.length === 0) {
      if (range.startContainer && range.collapsed) {
        range.selectNodeContents(range.startContainer);
      }
    }
    const bounding = range.getBoundingClientRect();
    const documentElement = doc3.documentElement;
    return bounding.bottom >= 0 && bounding.right >= 0 && bounding.left <= (window.innerWidth || documentElement.clientWidth || 0) && bounding.top <= (window.innerHeight || documentElement.clientHeight || 0);
  }
  /**
   * @param {Y.Snapshot} snapshot
   * @param {Y.Snapshot} prevSnapshot
   */
  renderSnapshot(snapshot2, prevSnapshot) {
    if (!prevSnapshot) {
      prevSnapshot = createSnapshot(createDeleteSet(), /* @__PURE__ */ new Map());
    }
    this.prosemirrorView.dispatch(
      this._tr.setMeta(ySyncPluginKey, { snapshot: snapshot2, prevSnapshot })
    );
  }
  unrenderSnapshot() {
    this.mapping.clear();
    this.mux(() => {
      const fragmentContent = this.type.toArray().map(
        (t2) => createNodeFromYElement(
          /** @type {Y.XmlElement} */
          t2,
          this.prosemirrorView.state.schema,
          this
        )
      ).filter((n) => n !== null);
      const tr4 = this._tr.replace(
        0,
        this.prosemirrorView.state.doc.content.size,
        new Slice(Fragment.from(fragmentContent), 0, 0)
      );
      tr4.setMeta(ySyncPluginKey, { snapshot: null, prevSnapshot: null });
      this.prosemirrorView.dispatch(tr4);
    });
  }
  _forceRerender() {
    this.mapping.clear();
    this.mux(() => {
      const sel = this.beforeTransactionSelection !== null ? null : this.prosemirrorView.state.selection;
      const fragmentContent = this.type.toArray().map(
        (t2) => createNodeFromYElement(
          /** @type {Y.XmlElement} */
          t2,
          this.prosemirrorView.state.schema,
          this
        )
      ).filter((n) => n !== null);
      const tr4 = this._tr.replace(
        0,
        this.prosemirrorView.state.doc.content.size,
        new Slice(Fragment.from(fragmentContent), 0, 0)
      );
      if (sel) {
        const clampedAnchor = min(max(sel.anchor, 0), tr4.doc.content.size);
        const clampedHead = min(max(sel.head, 0), tr4.doc.content.size);
        tr4.setSelection(TextSelection.create(tr4.doc, clampedAnchor, clampedHead));
      }
      this.prosemirrorView.dispatch(
        tr4.setMeta(ySyncPluginKey, { isChangeOrigin: true, binding: this })
      );
    });
  }
  /**
   * @param {Y.Snapshot|Uint8Array} snapshot
   * @param {Y.Snapshot|Uint8Array} prevSnapshot
   * @param {Object} pluginState
   */
  _renderSnapshot(snapshot2, prevSnapshot, pluginState) {
    let historyDoc = this.doc;
    let historyType = this.type;
    if (!snapshot2) {
      snapshot2 = snapshot(this.doc);
    }
    if (snapshot2 instanceof Uint8Array || prevSnapshot instanceof Uint8Array) {
      if (!(snapshot2 instanceof Uint8Array) || !(prevSnapshot instanceof Uint8Array)) {
        unexpectedCase();
      }
      historyDoc = new Doc({ gc: false });
      applyUpdateV2(historyDoc, prevSnapshot);
      prevSnapshot = snapshot(historyDoc);
      applyUpdateV2(historyDoc, snapshot2);
      snapshot2 = snapshot(historyDoc);
      if (historyType._item === null) {
        const rootKey = Array.from(this.doc.share.keys()).find(
          (key2) => this.doc.share.get(key2) === this.type
        );
        historyType = historyDoc.getXmlFragment(rootKey);
      } else {
        const historyStructs = historyDoc.store.clients.get(historyType._item.id.client) ?? [];
        const itemIndex = findIndexSS(
          historyStructs,
          historyType._item.id.clock
        );
        const item = (
          /** @type {Y.Item} */
          historyStructs[itemIndex]
        );
        const content5 = (
          /** @type {Y.ContentType} */
          item.content
        );
        historyType = /** @type {Y.XmlFragment} */
        content5.type;
      }
    }
    this.mapping.clear();
    this.mux(() => {
      historyDoc.transact((transaction) => {
        const pud = pluginState.permanentUserData;
        if (pud) {
          pud.dss.forEach((ds) => {
            iterateDeletedStructs(transaction, ds, (_item) => {
            });
          });
        }
        const computeYChange = (type, id2) => {
          const user = type === "added" ? pud.getUserByClientId(id2.client) : pud.getUserByDeletedId(id2);
          return {
            user,
            type,
            color: getUserColor(
              pluginState.colorMapping,
              pluginState.colors,
              user
            )
          };
        };
        const fragmentContent = typeListToArraySnapshot(
          historyType,
          new Snapshot(prevSnapshot.ds, snapshot2.sv)
        ).map((t2) => {
          if (!t2._item.deleted || isVisible2(t2._item, snapshot2) || isVisible2(t2._item, prevSnapshot)) {
            return createNodeFromYElement(
              t2,
              this.prosemirrorView.state.schema,
              { mapping: /* @__PURE__ */ new Map(), isOMark: /* @__PURE__ */ new Map() },
              snapshot2,
              prevSnapshot,
              computeYChange
            );
          } else {
            return null;
          }
        }).filter((n) => n !== null);
        const tr4 = this._tr.replace(
          0,
          this.prosemirrorView.state.doc.content.size,
          new Slice(Fragment.from(fragmentContent), 0, 0)
        );
        this.prosemirrorView.dispatch(
          tr4.setMeta(ySyncPluginKey, { isChangeOrigin: true })
        );
      }, ySyncPluginKey);
    });
  }
  /**
   * @param {Array<Y.YEvent<any>>} events
   * @param {Y.Transaction} transaction
   */
  _typeChanged(events, transaction) {
    if (this.prosemirrorView == null) return;
    const syncState = ySyncPluginKey.getState(this.prosemirrorView.state);
    if (events.length === 0 || syncState.snapshot != null || syncState.prevSnapshot != null) {
      this.renderSnapshot(syncState.snapshot, syncState.prevSnapshot);
      return;
    }
    this.mux(() => {
      const delType = (_2, type) => this.mapping.delete(type);
      iterateDeletedStructs(
        transaction,
        transaction.deleteSet,
        (struct) => {
          if (struct.constructor === Item) {
            const type = (
              /** @type {Y.ContentType} */
              /** @type {Y.Item} */
              struct.content.type
            );
            type && this.mapping.delete(type);
          }
        }
      );
      transaction.changed.forEach(delType);
      transaction.changedParentTypes.forEach(delType);
      const fragmentContent = this.type.toArray().map(
        (t2) => createNodeIfNotExists(
          /** @type {Y.XmlElement | Y.XmlHook} */
          t2,
          this.prosemirrorView.state.schema,
          this
        )
      ).filter((n) => n !== null);
      let tr4 = this._tr.replace(
        0,
        this.prosemirrorView.state.doc.content.size,
        new Slice(Fragment.from(fragmentContent), 0, 0)
      );
      restoreRelativeSelection(tr4, this.beforeTransactionSelection, this);
      tr4 = tr4.setMeta(ySyncPluginKey, { isChangeOrigin: true, isUndoRedoOperation: transaction.origin instanceof UndoManager });
      if (this.beforeTransactionSelection !== null && this._isLocalCursorInView()) {
        tr4.scrollIntoView();
      }
      this.prosemirrorView.dispatch(tr4);
    });
  }
  /**
   * @param {import('prosemirror-model').Node} doc
   */
  _prosemirrorChanged(doc4) {
    this.doc.transact(() => {
      updateYFragment(this.doc, this.type, doc4, this);
      this.beforeTransactionSelection = getRelativeSelection(
        this,
        this.prosemirrorView.state
      );
    }, ySyncPluginKey);
  }
  /**
   * View is ready to listen to changes. Register observers.
   * @param {any} prosemirrorView
   */
  initView(prosemirrorView) {
    if (this.prosemirrorView != null) this.destroy();
    this.prosemirrorView = prosemirrorView;
    this.doc.on("beforeAllTransactions", this.beforeAllTransactions);
    this.doc.on("afterAllTransactions", this.afterAllTransactions);
    this.type.observeDeep(this._observeFunction);
  }
  destroy() {
    if (this.prosemirrorView == null) return;
    this.prosemirrorView = null;
    this.type.unobserveDeep(this._observeFunction);
    this.doc.off("beforeAllTransactions", this.beforeAllTransactions);
    this.doc.off("afterAllTransactions", this.afterAllTransactions);
  }
};
var createNodeIfNotExists = (el2, schema, meta2, snapshot2, prevSnapshot, computeYChange) => {
  const node2 = (
    /** @type {PModel.Node} */
    meta2.mapping.get(el2)
  );
  if (node2 === void 0) {
    if (el2 instanceof YXmlElement) {
      return createNodeFromYElement(
        el2,
        schema,
        meta2,
        snapshot2,
        prevSnapshot,
        computeYChange
      );
    } else {
      throw methodUnimplemented();
    }
  }
  return node2;
};
var createNodeFromYElement = (el2, schema, meta2, snapshot2, prevSnapshot, computeYChange) => {
  const children = [];
  const createChildren = (type) => {
    var _a2, _b;
    if (type instanceof YXmlElement) {
      const n = createNodeIfNotExists(
        type,
        schema,
        meta2,
        snapshot2,
        prevSnapshot,
        computeYChange
      );
      if (n !== null) {
        children.push(n);
      }
    } else {
      const nextytext = (
        /** @type {Y.ContentType} */
        (_b = (_a2 = type._item.right) == null ? void 0 : _a2.content) == null ? void 0 : _b.type
      );
      if (nextytext instanceof YText && !nextytext._item.deleted && nextytext._item.id.client === nextytext.doc.clientID) {
        type.applyDelta([
          { retain: type.length },
          ...nextytext.toDelta()
        ]);
        nextytext.doc.transact((tr4) => {
          nextytext._item.delete(tr4);
        });
      }
      const ns = createTextNodesFromYText(
        type,
        schema,
        meta2,
        snapshot2,
        prevSnapshot,
        computeYChange
      );
      if (ns !== null) {
        ns.forEach((textchild) => {
          if (textchild !== null) {
            children.push(textchild);
          }
        });
      }
    }
  };
  if (snapshot2 === void 0 || prevSnapshot === void 0) {
    el2.toArray().forEach(createChildren);
  } else {
    typeListToArraySnapshot(el2, new Snapshot(prevSnapshot.ds, snapshot2.sv)).forEach(createChildren);
  }
  try {
    const attrs = el2.getAttributes(snapshot2);
    if (snapshot2 !== void 0) {
      if (!isVisible2(
        /** @type {Y.Item} */
        el2._item,
        snapshot2
      )) {
        attrs.ychange = computeYChange ? computeYChange(
          "removed",
          /** @type {Y.Item} */
          el2._item.id
        ) : { type: "removed" };
      } else if (!isVisible2(
        /** @type {Y.Item} */
        el2._item,
        prevSnapshot
      )) {
        attrs.ychange = computeYChange ? computeYChange(
          "added",
          /** @type {Y.Item} */
          el2._item.id
        ) : { type: "added" };
      }
    }
    const node2 = schema.node(el2.nodeName, attrs, children);
    meta2.mapping.set(el2, node2);
    return node2;
  } catch (e2) {
    el2.doc.transact((transaction) => {
      el2._item.delete(transaction);
    }, ySyncPluginKey);
    meta2.mapping.delete(el2);
    return null;
  }
};
var createTextNodesFromYText = (text10, schema, _meta, snapshot2, prevSnapshot, computeYChange) => {
  const nodes = [];
  const deltas = text10.toDelta(snapshot2, prevSnapshot, computeYChange);
  try {
    for (let i3 = 0; i3 < deltas.length; i3++) {
      const delta = deltas[i3];
      nodes.push(schema.text(delta.insert, attributesToMarks(delta.attributes, schema)));
    }
  } catch (e2) {
    text10.doc.transact((transaction) => {
      text10._item.delete(transaction);
    }, ySyncPluginKey);
    return null;
  }
  return nodes;
};
var createTypeFromTextNodes = (nodes, meta2) => {
  const type = new YXmlText();
  const delta = nodes.map((node2) => ({
    // @ts-ignore
    insert: node2.text,
    attributes: marksToAttributes(node2.marks, meta2)
  }));
  type.applyDelta(delta);
  meta2.mapping.set(type, nodes);
  return type;
};
var createTypeFromElementNode = (node2, meta2) => {
  const type = new YXmlElement(node2.type.name);
  for (const key2 in node2.attrs) {
    const val = node2.attrs[key2];
    if (val !== null && key2 !== "ychange") {
      type.setAttribute(key2, val);
    }
  }
  type.insert(
    0,
    normalizePNodeContent(node2).map(
      (n) => createTypeFromTextOrElementNode(n, meta2)
    )
  );
  meta2.mapping.set(type, node2);
  return type;
};
var createTypeFromTextOrElementNode = (node2, meta2) => node2 instanceof Array ? createTypeFromTextNodes(node2, meta2) : createTypeFromElementNode(node2, meta2);
var isObject2 = (val) => typeof val === "object" && val !== null;
var equalAttrs2 = (pattrs, yattrs) => {
  const keys5 = Object.keys(pattrs).filter((key2) => pattrs[key2] !== null);
  let eq = keys5.length === (yattrs == null ? 0 : Object.keys(yattrs).filter((key2) => yattrs[key2] !== null).length);
  for (let i3 = 0; i3 < keys5.length && eq; i3++) {
    const key2 = keys5[i3];
    const l2 = pattrs[key2];
    const r4 = yattrs[key2];
    eq = key2 === "ychange" || l2 === r4 || isObject2(l2) && isObject2(r4) && equalAttrs2(l2, r4);
  }
  return eq;
};
var normalizePNodeContent = (pnode) => {
  const c3 = pnode.content.content;
  const res = [];
  for (let i3 = 0; i3 < c3.length; i3++) {
    const n = c3[i3];
    if (n.isText) {
      const textNodes = [];
      for (let tnode = c3[i3]; i3 < c3.length && tnode.isText; tnode = c3[++i3]) {
        textNodes.push(tnode);
      }
      i3--;
      res.push(textNodes);
    } else {
      res.push(n);
    }
  }
  return res;
};
var equalYTextPText = (ytext, ptexts) => {
  const delta = ytext.toDelta();
  return delta.length === ptexts.length && delta.every(
    /** @type {(d:any,i:number) => boolean} */
    (d, i3) => d.insert === /** @type {any} */
    ptexts[i3].text && keys2(d.attributes || {}).length === ptexts[i3].marks.length && every2(d.attributes, (attr2, yattrname) => {
      var _a2;
      const markname = yattr2markname(yattrname);
      const pmarks = ptexts[i3].marks;
      return equalAttrs2(attr2, (_a2 = pmarks.find(
        /** @param {any} mark */
        (mark2) => mark2.type.name === markname
      )) == null ? void 0 : _a2.attrs);
    })
  );
};
var equalYTypePNode = (ytype, pnode) => {
  if (ytype instanceof YXmlElement && !(pnode instanceof Array) && matchNodeName(ytype, pnode)) {
    const normalizedContent = normalizePNodeContent(pnode);
    return ytype._length === normalizedContent.length && equalAttrs2(ytype.getAttributes(), pnode.attrs) && ytype.toArray().every(
      (ychild, i3) => equalYTypePNode(ychild, normalizedContent[i3])
    );
  }
  return ytype instanceof YXmlText && pnode instanceof Array && equalYTextPText(ytype, pnode);
};
var mappedIdentity = (mapped, pcontent) => mapped === pcontent || mapped instanceof Array && pcontent instanceof Array && mapped.length === pcontent.length && mapped.every(
  (a3, i3) => pcontent[i3] === a3
);
var computeChildEqualityFactor = (ytype, pnode, meta2) => {
  const yChildren = ytype.toArray();
  const pChildren = normalizePNodeContent(pnode);
  const pChildCnt = pChildren.length;
  const yChildCnt = yChildren.length;
  const minCnt = min(yChildCnt, pChildCnt);
  let left = 0;
  let right = 0;
  let foundMappedChild = false;
  for (; left < minCnt; left++) {
    const leftY = yChildren[left];
    const leftP = pChildren[left];
    if (mappedIdentity(meta2.mapping.get(leftY), leftP)) {
      foundMappedChild = true;
    } else if (!equalYTypePNode(leftY, leftP)) {
      break;
    }
  }
  for (; left + right < minCnt; right++) {
    const rightY = yChildren[yChildCnt - right - 1];
    const rightP = pChildren[pChildCnt - right - 1];
    if (mappedIdentity(meta2.mapping.get(rightY), rightP)) {
      foundMappedChild = true;
    } else if (!equalYTypePNode(rightY, rightP)) {
      break;
    }
  }
  return {
    equalityFactor: left + right,
    foundMappedChild
  };
};
var ytextTrans = (ytext) => {
  let str = "";
  let n = ytext._start;
  const nAttrs = {};
  while (n !== null) {
    if (!n.deleted) {
      if (n.countable && n.content instanceof ContentString) {
        str += n.content.str;
      } else if (n.content instanceof ContentFormat) {
        nAttrs[n.content.key] = null;
      }
    }
    n = n.right;
  }
  return {
    str,
    nAttrs
  };
};
var updateYText = (ytext, ptexts, meta2) => {
  meta2.mapping.set(ytext, ptexts);
  const { nAttrs, str } = ytextTrans(ytext);
  const content5 = ptexts.map((p4) => ({
    insert: (
      /** @type {any} */
      p4.text
    ),
    attributes: Object.assign({}, nAttrs, marksToAttributes(p4.marks, meta2))
  }));
  const { insert, remove, index: index4 } = simpleDiff(
    str,
    content5.map((c3) => c3.insert).join("")
  );
  ytext.delete(index4, remove);
  ytext.insert(index4, insert);
  ytext.applyDelta(
    content5.map((c3) => ({ retain: c3.insert.length, attributes: c3.attributes }))
  );
};
var hashedMarkNameRegex = /(.*)(--[a-zA-Z0-9+/=]{8})$/;
var yattr2markname = (attrName) => {
  var _a2;
  return ((_a2 = hashedMarkNameRegex.exec(attrName)) == null ? void 0 : _a2[1]) ?? attrName;
};
var attributesToMarks = (attrs, schema) => {
  const marks = [];
  for (const markName in attrs) {
    marks.push(schema.mark(yattr2markname(markName), attrs[markName]));
  }
  return marks;
};
var marksToAttributes = (marks, meta2) => {
  const pattrs = {};
  marks.forEach((mark2) => {
    if (mark2.type.name !== "ychange") {
      const isOverlapping = setIfUndefined(meta2.isOMark, mark2.type, () => !mark2.type.excludes(mark2.type));
      pattrs[isOverlapping ? `${mark2.type.name}--${hashOfJSON(mark2.toJSON())}` : mark2.type.name] = mark2.attrs;
    }
  });
  return pattrs;
};
var updateYFragment = (y3, yDomFragment, pNode, meta2) => {
  if (yDomFragment instanceof YXmlElement && yDomFragment.nodeName !== pNode.type.name) {
    throw new Error("node name mismatch!");
  }
  meta2.mapping.set(yDomFragment, pNode);
  if (yDomFragment instanceof YXmlElement) {
    const yDomAttrs = yDomFragment.getAttributes();
    const pAttrs = pNode.attrs;
    for (const key2 in pAttrs) {
      if (pAttrs[key2] !== null) {
        if (yDomAttrs[key2] !== pAttrs[key2] && key2 !== "ychange") {
          yDomFragment.setAttribute(key2, pAttrs[key2]);
        }
      } else {
        yDomFragment.removeAttribute(key2);
      }
    }
    for (const key2 in yDomAttrs) {
      if (pAttrs[key2] === void 0) {
        yDomFragment.removeAttribute(key2);
      }
    }
  }
  const pChildren = normalizePNodeContent(pNode);
  const pChildCnt = pChildren.length;
  const yChildren = yDomFragment.toArray();
  const yChildCnt = yChildren.length;
  const minCnt = min(pChildCnt, yChildCnt);
  let left = 0;
  let right = 0;
  for (; left < minCnt; left++) {
    const leftY = yChildren[left];
    const leftP = pChildren[left];
    if (!mappedIdentity(meta2.mapping.get(leftY), leftP)) {
      if (equalYTypePNode(leftY, leftP)) {
        meta2.mapping.set(leftY, leftP);
      } else {
        break;
      }
    }
  }
  for (; right + left < minCnt; right++) {
    const rightY = yChildren[yChildCnt - right - 1];
    const rightP = pChildren[pChildCnt - right - 1];
    if (!mappedIdentity(meta2.mapping.get(rightY), rightP)) {
      if (equalYTypePNode(rightY, rightP)) {
        meta2.mapping.set(rightY, rightP);
      } else {
        break;
      }
    }
  }
  y3.transact(() => {
    while (yChildCnt - left - right > 0 && pChildCnt - left - right > 0) {
      const leftY = yChildren[left];
      const leftP = pChildren[left];
      const rightY = yChildren[yChildCnt - right - 1];
      const rightP = pChildren[pChildCnt - right - 1];
      if (leftY instanceof YXmlText && leftP instanceof Array) {
        if (!equalYTextPText(leftY, leftP)) {
          updateYText(leftY, leftP, meta2);
        }
        left += 1;
      } else {
        let updateLeft = leftY instanceof YXmlElement && matchNodeName(leftY, leftP);
        let updateRight = rightY instanceof YXmlElement && matchNodeName(rightY, rightP);
        if (updateLeft && updateRight) {
          const equalityLeft = computeChildEqualityFactor(
            /** @type {Y.XmlElement} */
            leftY,
            /** @type {PModel.Node} */
            leftP,
            meta2
          );
          const equalityRight = computeChildEqualityFactor(
            /** @type {Y.XmlElement} */
            rightY,
            /** @type {PModel.Node} */
            rightP,
            meta2
          );
          if (equalityLeft.foundMappedChild && !equalityRight.foundMappedChild) {
            updateRight = false;
          } else if (!equalityLeft.foundMappedChild && equalityRight.foundMappedChild) {
            updateLeft = false;
          } else if (equalityLeft.equalityFactor < equalityRight.equalityFactor) {
            updateLeft = false;
          } else {
            updateRight = false;
          }
        }
        if (updateLeft) {
          updateYFragment(
            y3,
            /** @type {Y.XmlFragment} */
            leftY,
            /** @type {PModel.Node} */
            leftP,
            meta2
          );
          left += 1;
        } else if (updateRight) {
          updateYFragment(
            y3,
            /** @type {Y.XmlFragment} */
            rightY,
            /** @type {PModel.Node} */
            rightP,
            meta2
          );
          right += 1;
        } else {
          meta2.mapping.delete(yDomFragment.get(left));
          yDomFragment.delete(left, 1);
          yDomFragment.insert(left, [
            createTypeFromTextOrElementNode(leftP, meta2)
          ]);
          left += 1;
        }
      }
    }
    const yDelLen = yChildCnt - left - right;
    if (yChildCnt === 1 && pChildCnt === 0 && yChildren[0] instanceof YXmlText) {
      meta2.mapping.delete(yChildren[0]);
      yChildren[0].delete(0, yChildren[0].length);
    } else if (yDelLen > 0) {
      yDomFragment.slice(left, left + yDelLen).forEach((type) => meta2.mapping.delete(type));
      yDomFragment.delete(left, yDelLen);
    }
    if (left + right < pChildCnt) {
      const ins = [];
      for (let i3 = left; i3 < pChildCnt - right; i3++) {
        ins.push(createTypeFromTextOrElementNode(pChildren[i3], meta2));
      }
      yDomFragment.insert(left, ins);
    }
  }, ySyncPluginKey);
};
var matchNodeName = (yElement, pNode) => !(pNode instanceof Array) && yElement.nodeName === pNode.type.name;

// ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/lib.js
var viewsToUpdate = null;
var updateMetas = () => {
  const ups = (
    /** @type {Map<EditorView, Map<any, any>>} */
    viewsToUpdate
  );
  viewsToUpdate = null;
  ups.forEach((metas, view) => {
    const tr4 = view.state.tr;
    const syncState = ySyncPluginKey.getState(view.state);
    if (syncState && syncState.binding && !syncState.binding.isDestroyed) {
      metas.forEach((val, key2) => {
        tr4.setMeta(key2, val);
      });
      view.dispatch(tr4);
    }
  });
};
var setMeta = (view, key2, value) => {
  if (!viewsToUpdate) {
    viewsToUpdate = /* @__PURE__ */ new Map();
    timeout(0, updateMetas);
  }
  setIfUndefined(viewsToUpdate, view, create).set(key2, value);
};
var absolutePositionToRelativePosition = (pos, type, mapping) => {
  if (pos === 0) {
    return createRelativePositionFromTypeIndex(type, 0, type.length === 0 ? -1 : 0);
  }
  let n = type._first === null ? null : (
    /** @type {Y.ContentType} */
    type._first.content.type
  );
  while (n !== null && type !== n) {
    if (n instanceof YXmlText) {
      if (n._length >= pos) {
        return createRelativePositionFromTypeIndex(n, pos, type.length === 0 ? -1 : 0);
      } else {
        pos -= n._length;
      }
      if (n._item !== null && n._item.next !== null) {
        n = /** @type {Y.ContentType} */
        n._item.next.content.type;
      } else {
        do {
          n = n._item === null ? null : n._item.parent;
          pos--;
        } while (n !== type && n !== null && n._item !== null && n._item.next === null);
        if (n !== null && n !== type) {
          n = n._item === null ? null : (
            /** @type {Y.ContentType} */
            /** @type Y.Item */
            n._item.next.content.type
          );
        }
      }
    } else {
      const pNodeSize = (
        /** @type {any} */
        (mapping.get(n) || { nodeSize: 0 }).nodeSize
      );
      if (n._first !== null && pos < pNodeSize) {
        n = /** @type {Y.ContentType} */
        n._first.content.type;
        pos--;
      } else {
        if (pos === 1 && n._length === 0 && pNodeSize > 1) {
          return new RelativePosition(n._item === null ? null : n._item.id, n._item === null ? findRootTypeKey(n) : null, null);
        }
        pos -= pNodeSize;
        if (n._item !== null && n._item.next !== null) {
          n = /** @type {Y.ContentType} */
          n._item.next.content.type;
        } else {
          if (pos === 0) {
            n = n._item === null ? n : n._item.parent;
            return new RelativePosition(n._item === null ? null : n._item.id, n._item === null ? findRootTypeKey(n) : null, null);
          }
          do {
            n = /** @type {Y.Item} */
            n._item.parent;
            pos--;
          } while (n !== type && /** @type {Y.Item} */
          n._item.next === null);
          if (n !== type) {
            n = /** @type {Y.ContentType} */
            /** @type {Y.Item} */
            /** @type {Y.Item} */
            n._item.next.content.type;
          }
        }
      }
    }
    if (n === null) {
      throw unexpectedCase();
    }
    if (pos === 0 && n.constructor !== YXmlText && n !== type) {
      return createRelativePosition2(n._item.parent, n._item);
    }
  }
  return createRelativePositionFromTypeIndex(type, type._length, type.length === 0 ? -1 : 0);
};
var createRelativePosition2 = (type, item) => {
  let typeid = null;
  let tname = null;
  if (type._item === null) {
    tname = findRootTypeKey(type);
  } else {
    typeid = createID(type._item.id.client, type._item.id.clock);
  }
  return new RelativePosition(typeid, tname, item.id);
};
var relativePositionToAbsolutePosition = (y3, documentType, relPos, mapping) => {
  const decodedPos = createAbsolutePositionFromRelativePosition(relPos, y3);
  if (decodedPos === null || decodedPos.type !== documentType && !isParentOf(documentType, decodedPos.type._item)) {
    return null;
  }
  let type = decodedPos.type;
  let pos = 0;
  if (type.constructor === YXmlText) {
    pos = decodedPos.index;
  } else if (type._item === null || !type._item.deleted) {
    let n = type._first;
    let i3 = 0;
    while (i3 < type._length && i3 < decodedPos.index && n !== null) {
      if (!n.deleted) {
        const t2 = (
          /** @type {Y.ContentType} */
          n.content.type
        );
        i3++;
        if (t2 instanceof YXmlText) {
          pos += t2._length;
        } else {
          pos += /** @type {any} */
          mapping.get(t2).nodeSize;
        }
      }
      n = /** @type {Y.Item} */
      n.right;
    }
    pos += 1;
  }
  while (type !== documentType && type._item !== null) {
    const parent = type._item.parent;
    if (parent._item === null || !parent._item.deleted) {
      pos += 1;
      let n = (
        /** @type {Y.AbstractType} */
        parent._first
      );
      while (n !== null) {
        const contentType = (
          /** @type {Y.ContentType} */
          n.content.type
        );
        if (contentType === type) {
          break;
        }
        if (!n.deleted) {
          if (contentType instanceof YXmlText) {
            pos += contentType._length;
          } else {
            pos += /** @type {any} */
            mapping.get(contentType).nodeSize;
          }
        }
        n = n.right;
      }
    }
    type = /** @type {Y.AbstractType} */
    parent;
  }
  return pos - 1;
};

// ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/plugins/cursor-plugin.js
var defaultAwarenessStateFilter = (currentClientId, userClientId, _user) => currentClientId !== userClientId;
var defaultCursorBuilder = (user) => {
  const cursor = document.createElement("span");
  cursor.classList.add("ProseMirror-yjs-cursor");
  cursor.setAttribute("style", `border-color: ${user.color}`);
  const userDiv = document.createElement("div");
  userDiv.setAttribute("style", `background-color: ${user.color}`);
  userDiv.insertBefore(document.createTextNode(user.name), null);
  const nonbreakingSpace1 = document.createTextNode("⁠");
  const nonbreakingSpace2 = document.createTextNode("⁠");
  cursor.insertBefore(nonbreakingSpace1, null);
  cursor.insertBefore(userDiv, null);
  cursor.insertBefore(nonbreakingSpace2, null);
  return cursor;
};
var defaultSelectionBuilder = (user) => {
  return {
    style: `background-color: ${user.color}70`,
    class: "ProseMirror-yjs-selection"
  };
};
var rxValidColor = /^#[0-9a-fA-F]{6}$/;
var createDecorations = (state, awareness, awarenessFilter, createCursor, createSelection) => {
  const ystate = ySyncPluginKey.getState(state);
  const y3 = ystate.doc;
  const decorations = [];
  if (ystate.snapshot != null || ystate.prevSnapshot != null || ystate.binding.mapping.size === 0) {
    return DecorationSet.create(state.doc, []);
  }
  awareness.getStates().forEach((aw, clientId) => {
    if (!awarenessFilter(y3.clientID, clientId, aw)) {
      return;
    }
    if (aw.cursor != null) {
      const user = aw.user || {};
      if (user.color == null) {
        user.color = "#ffa500";
      } else if (!rxValidColor.test(user.color)) {
        console.warn("A user uses an unsupported color format", user);
      }
      if (user.name == null) {
        user.name = `User: ${clientId}`;
      }
      let anchor = relativePositionToAbsolutePosition(
        y3,
        ystate.type,
        createRelativePositionFromJSON(aw.cursor.anchor),
        ystate.binding.mapping
      );
      let head2 = relativePositionToAbsolutePosition(
        y3,
        ystate.type,
        createRelativePositionFromJSON(aw.cursor.head),
        ystate.binding.mapping
      );
      if (anchor !== null && head2 !== null) {
        const maxsize = max(state.doc.content.size - 1, 0);
        anchor = min(anchor, maxsize);
        head2 = min(head2, maxsize);
        decorations.push(
          Decoration.widget(head2, () => createCursor(user, clientId), {
            key: clientId + "",
            side: 10
          })
        );
        const from4 = min(anchor, head2);
        const to2 = max(anchor, head2);
        decorations.push(
          Decoration.inline(from4, to2, createSelection(user, clientId), {
            inclusiveEnd: true,
            inclusiveStart: false
          })
        );
      }
    }
  });
  return DecorationSet.create(state.doc, decorations);
};
var yCursorPlugin = (awareness, {
  awarenessStateFilter = defaultAwarenessStateFilter,
  cursorBuilder = defaultCursorBuilder,
  selectionBuilder = defaultSelectionBuilder,
  getSelection: getSelection2 = (state) => state.selection
} = {}, cursorStateField = "cursor") => new Plugin({
  key: yCursorPluginKey,
  state: {
    init(_2, state) {
      return createDecorations(
        state,
        awareness,
        awarenessStateFilter,
        cursorBuilder,
        selectionBuilder
      );
    },
    apply(tr4, prevState, _oldState, newState) {
      const ystate = ySyncPluginKey.getState(newState);
      const yCursorState = tr4.getMeta(yCursorPluginKey);
      if (ystate && ystate.isChangeOrigin || yCursorState && yCursorState.awarenessUpdated) {
        return createDecorations(
          newState,
          awareness,
          awarenessStateFilter,
          cursorBuilder,
          selectionBuilder
        );
      }
      return prevState.map(tr4.mapping, tr4.doc);
    }
  },
  props: {
    decorations: (state) => {
      return yCursorPluginKey.getState(state);
    }
  },
  view: (view) => {
    const awarenessListener = () => {
      if (view.docView) {
        setMeta(view, yCursorPluginKey, { awarenessUpdated: true });
      }
    };
    const updateCursorInfo = () => {
      const ystate = ySyncPluginKey.getState(view.state);
      const current = awareness.getLocalState() || {};
      if (view.hasFocus()) {
        const selection = getSelection2(view.state);
        const anchor = absolutePositionToRelativePosition(
          selection.anchor,
          ystate.type,
          ystate.binding.mapping
        );
        const head2 = absolutePositionToRelativePosition(
          selection.head,
          ystate.type,
          ystate.binding.mapping
        );
        if (current.cursor == null || !compareRelativePositions(
          createRelativePositionFromJSON(current.cursor.anchor),
          anchor
        ) || !compareRelativePositions(
          createRelativePositionFromJSON(current.cursor.head),
          head2
        )) {
          awareness.setLocalStateField(cursorStateField, {
            anchor,
            head: head2
          });
        }
      } else if (current.cursor != null && relativePositionToAbsolutePosition(
        ystate.doc,
        ystate.type,
        createRelativePositionFromJSON(current.cursor.anchor),
        ystate.binding.mapping
      ) !== null) {
        awareness.setLocalStateField(cursorStateField, null);
      }
    };
    awareness.on("change", awarenessListener);
    view.dom.addEventListener("focusin", updateCursorInfo);
    view.dom.addEventListener("focusout", updateCursorInfo);
    return {
      update: updateCursorInfo,
      destroy: () => {
        view.dom.removeEventListener("focusin", updateCursorInfo);
        view.dom.removeEventListener("focusout", updateCursorInfo);
        awareness.off("change", awarenessListener);
        awareness.setLocalStateField(cursorStateField, null);
      }
    };
  }
});

// ../../node_modules/.pnpm/y-prosemirror@1.3.7_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1_e54c9754f6d3499b891ad5a3a7f4fd0d/node_modules/y-prosemirror/src/plugins/undo-plugin.js
var undo = (state) => {
  var _a2, _b;
  return ((_b = (_a2 = yUndoPluginKey.getState(state)) == null ? void 0 : _a2.undoManager) == null ? void 0 : _b.undo()) != null;
};
var redo = (state) => {
  var _a2, _b;
  return ((_b = (_a2 = yUndoPluginKey.getState(state)) == null ? void 0 : _a2.undoManager) == null ? void 0 : _b.redo()) != null;
};
var undoCommand = (state, dispatch) => {
  var _a2, _b;
  return dispatch == null ? (_b = (_a2 = yUndoPluginKey.getState(state)) == null ? void 0 : _a2.undoManager) == null ? void 0 : _b.canUndo() : undo(state);
};
var redoCommand = (state, dispatch) => {
  var _a2, _b;
  return dispatch == null ? (_b = (_a2 = yUndoPluginKey.getState(state)) == null ? void 0 : _a2.undoManager) == null ? void 0 : _b.canRedo() : redo(state);
};
var defaultProtectedNodes = /* @__PURE__ */ new Set(["paragraph"]);
var defaultDeleteFilter = (item, protectedNodes) => !(item instanceof Item) || !(item.content instanceof ContentType) || !(item.content.type instanceof YText || item.content.type instanceof YXmlElement && protectedNodes.has(item.content.type.nodeName)) || item.content.type._length === 0;
var yUndoPlugin = ({ protectedNodes = defaultProtectedNodes, trackedOrigins = [], undoManager = null } = {}) => new Plugin({
  key: yUndoPluginKey,
  state: {
    init: (initargs, state) => {
      const ystate = ySyncPluginKey.getState(state);
      const _undoManager = undoManager || new UndoManager(ystate.type, {
        trackedOrigins: new Set([ySyncPluginKey].concat(trackedOrigins)),
        deleteFilter: (item) => defaultDeleteFilter(item, protectedNodes),
        captureTransaction: (tr4) => tr4.meta.get("addToHistory") !== false
      });
      return {
        undoManager: _undoManager,
        prevSel: null,
        hasUndoOps: _undoManager.undoStack.length > 0,
        hasRedoOps: _undoManager.redoStack.length > 0
      };
    },
    apply: (tr4, val, oldState, state) => {
      const binding = ySyncPluginKey.getState(state).binding;
      const undoManager2 = val.undoManager;
      const hasUndoOps = undoManager2.undoStack.length > 0;
      const hasRedoOps = undoManager2.redoStack.length > 0;
      if (binding) {
        return {
          undoManager: undoManager2,
          prevSel: getRelativeSelection(binding, oldState),
          hasUndoOps,
          hasRedoOps
        };
      } else {
        if (hasUndoOps !== val.hasUndoOps || hasRedoOps !== val.hasRedoOps) {
          return Object.assign({}, val, {
            hasUndoOps: undoManager2.undoStack.length > 0,
            hasRedoOps: undoManager2.redoStack.length > 0
          });
        } else {
          return val;
        }
      }
    }
  },
  view: (view) => {
    const ystate = ySyncPluginKey.getState(view.state);
    const undoManager2 = yUndoPluginKey.getState(view.state).undoManager;
    undoManager2.on("stack-item-added", ({ stackItem }) => {
      const binding = ystate.binding;
      if (binding) {
        stackItem.meta.set(binding, yUndoPluginKey.getState(view.state).prevSel);
      }
    });
    undoManager2.on("stack-item-popped", ({ stackItem }) => {
      const binding = ystate.binding;
      if (binding) {
        binding.beforeTransactionSelection = stackItem.meta.get(binding) || binding.beforeTransactionSelection;
      }
    });
    return {
      destroy: () => {
        undoManager2.destroy();
      }
    };
  }
});

// ../../node_modules/.pnpm/@tanstack+store@0.7.7/node_modules/@tanstack/store/dist/esm/scheduler.js
var __storeToDerived = /* @__PURE__ */ new WeakMap();
var __derivedToStore = /* @__PURE__ */ new WeakMap();
var __depsThatHaveWrittenThisTick = {
  current: []
};
var __isFlushing = false;
var __batchDepth = 0;
var __pendingUpdates = /* @__PURE__ */ new Set();
var __initialBatchValues = /* @__PURE__ */ new Map();
function __flush_internals(relatedVals) {
  const sorted = Array.from(relatedVals).sort((a3, b4) => {
    if (a3 instanceof Derived && a3.options.deps.includes(b4)) return 1;
    if (b4 instanceof Derived && b4.options.deps.includes(a3)) return -1;
    return 0;
  });
  for (const derived of sorted) {
    if (__depsThatHaveWrittenThisTick.current.includes(derived)) {
      continue;
    }
    __depsThatHaveWrittenThisTick.current.push(derived);
    derived.recompute();
    const stores = __derivedToStore.get(derived);
    if (stores) {
      for (const store of stores) {
        const relatedLinkedDerivedVals = __storeToDerived.get(store);
        if (!relatedLinkedDerivedVals) continue;
        __flush_internals(relatedLinkedDerivedVals);
      }
    }
  }
}
function __notifyListeners(store) {
  const value = {
    prevVal: store.prevState,
    currentVal: store.state
  };
  for (const listener of store.listeners) {
    listener(value);
  }
}
function __notifyDerivedListeners(derived) {
  const value = {
    prevVal: derived.prevState,
    currentVal: derived.state
  };
  for (const listener of derived.listeners) {
    listener(value);
  }
}
function __flush(store) {
  if (__batchDepth > 0 && !__initialBatchValues.has(store)) {
    __initialBatchValues.set(store, store.prevState);
  }
  __pendingUpdates.add(store);
  if (__batchDepth > 0) return;
  if (__isFlushing) return;
  try {
    __isFlushing = true;
    while (__pendingUpdates.size > 0) {
      const stores = Array.from(__pendingUpdates);
      __pendingUpdates.clear();
      for (const store2 of stores) {
        const prevState = __initialBatchValues.get(store2) ?? store2.prevState;
        store2.prevState = prevState;
        __notifyListeners(store2);
      }
      for (const store2 of stores) {
        const derivedVals = __storeToDerived.get(store2);
        if (!derivedVals) continue;
        __depsThatHaveWrittenThisTick.current.push(store2);
        __flush_internals(derivedVals);
      }
      for (const store2 of stores) {
        const derivedVals = __storeToDerived.get(store2);
        if (!derivedVals) continue;
        for (const derived of derivedVals) {
          __notifyDerivedListeners(derived);
        }
      }
    }
  } finally {
    __isFlushing = false;
    __depsThatHaveWrittenThisTick.current = [];
    __initialBatchValues.clear();
  }
}

// ../../node_modules/.pnpm/@tanstack+store@0.7.7/node_modules/@tanstack/store/dist/esm/types.js
function isUpdaterFunction(updater) {
  return typeof updater === "function";
}

// ../../node_modules/.pnpm/@tanstack+store@0.7.7/node_modules/@tanstack/store/dist/esm/store.js
var Store = class {
  constructor(initialState, options2) {
    this.listeners = /* @__PURE__ */ new Set();
    this.subscribe = (listener) => {
      var _a2, _b;
      this.listeners.add(listener);
      const unsub = (_b = (_a2 = this.options) == null ? void 0 : _a2.onSubscribe) == null ? void 0 : _b.call(_a2, listener, this);
      return () => {
        this.listeners.delete(listener);
        unsub == null ? void 0 : unsub();
      };
    };
    this.prevState = initialState;
    this.state = initialState;
    this.options = options2;
  }
  setState(updater) {
    var _a2, _b, _c;
    this.prevState = this.state;
    if ((_a2 = this.options) == null ? void 0 : _a2.updateFn) {
      this.state = this.options.updateFn(this.prevState)(updater);
    } else {
      if (isUpdaterFunction(updater)) {
        this.state = updater(this.prevState);
      } else {
        this.state = updater;
      }
    }
    (_c = (_b = this.options) == null ? void 0 : _b.onUpdate) == null ? void 0 : _c.call(_b);
    __flush(this);
  }
};

// ../../node_modules/.pnpm/@tanstack+store@0.7.7/node_modules/@tanstack/store/dist/esm/derived.js
var Derived = class _Derived {
  constructor(options2) {
    this.listeners = /* @__PURE__ */ new Set();
    this._subscriptions = [];
    this.lastSeenDepValues = [];
    this.getDepVals = () => {
      const l2 = this.options.deps.length;
      const prevDepVals = new Array(l2);
      const currDepVals = new Array(l2);
      for (let i3 = 0; i3 < l2; i3++) {
        const dep = this.options.deps[i3];
        prevDepVals[i3] = dep.prevState;
        currDepVals[i3] = dep.state;
      }
      this.lastSeenDepValues = currDepVals;
      return {
        prevDepVals,
        currDepVals,
        prevVal: this.prevState ?? void 0
      };
    };
    this.recompute = () => {
      var _a2, _b;
      this.prevState = this.state;
      const depVals = this.getDepVals();
      this.state = this.options.fn(depVals);
      (_b = (_a2 = this.options).onUpdate) == null ? void 0 : _b.call(_a2);
    };
    this.checkIfRecalculationNeededDeeply = () => {
      for (const dep of this.options.deps) {
        if (dep instanceof _Derived) {
          dep.checkIfRecalculationNeededDeeply();
        }
      }
      let shouldRecompute = false;
      const lastSeenDepValues = this.lastSeenDepValues;
      const { currDepVals } = this.getDepVals();
      for (let i3 = 0; i3 < currDepVals.length; i3++) {
        if (currDepVals[i3] !== lastSeenDepValues[i3]) {
          shouldRecompute = true;
          break;
        }
      }
      if (shouldRecompute) {
        this.recompute();
      }
    };
    this.mount = () => {
      this.registerOnGraph();
      this.checkIfRecalculationNeededDeeply();
      return () => {
        this.unregisterFromGraph();
        for (const cleanup2 of this._subscriptions) {
          cleanup2();
        }
      };
    };
    this.subscribe = (listener) => {
      var _a2, _b;
      this.listeners.add(listener);
      const unsub = (_b = (_a2 = this.options).onSubscribe) == null ? void 0 : _b.call(_a2, listener, this);
      return () => {
        this.listeners.delete(listener);
        unsub == null ? void 0 : unsub();
      };
    };
    this.options = options2;
    this.state = options2.fn({
      prevDepVals: void 0,
      prevVal: void 0,
      currDepVals: this.getDepVals().currDepVals
    });
  }
  registerOnGraph(deps = this.options.deps) {
    for (const dep of deps) {
      if (dep instanceof _Derived) {
        dep.registerOnGraph();
        this.registerOnGraph(dep.options.deps);
      } else if (dep instanceof Store) {
        let relatedLinkedDerivedVals = __storeToDerived.get(dep);
        if (!relatedLinkedDerivedVals) {
          relatedLinkedDerivedVals = /* @__PURE__ */ new Set();
          __storeToDerived.set(dep, relatedLinkedDerivedVals);
        }
        relatedLinkedDerivedVals.add(this);
        let relatedStores = __derivedToStore.get(this);
        if (!relatedStores) {
          relatedStores = /* @__PURE__ */ new Set();
          __derivedToStore.set(this, relatedStores);
        }
        relatedStores.add(dep);
      }
    }
  }
  unregisterFromGraph(deps = this.options.deps) {
    for (const dep of deps) {
      if (dep instanceof _Derived) {
        this.unregisterFromGraph(dep.options.deps);
      } else if (dep instanceof Store) {
        const relatedLinkedDerivedVals = __storeToDerived.get(dep);
        if (relatedLinkedDerivedVals) {
          relatedLinkedDerivedVals.delete(this);
        }
        const relatedStores = __derivedToStore.get(this);
        if (relatedStores) {
          relatedStores.delete(dep);
        }
      }
    }
  }
};

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/BlockNoteExtension-C2X7LW-V.js
var r = Symbol("originalFactory");
function a(n) {
  if (typeof n == "object" && "key" in n)
    return function t2() {
      return n[r] = t2, n;
    };
  if (typeof n != "function")
    throw new Error("factory must be a function");
  return function t2(e2) {
    return (i3) => {
      const o2 = n({ editor: i3.editor, options: e2 });
      return o2[r] = t2, o2;
    };
  };
}
function f(n, t2) {
  return new Store(n, t2);
}

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/ShowSelection-Dz-NEase.js
var r2 = new PluginKey("blocknote-show-selection");
var f2 = a(({ editor: s2 }) => {
  const t2 = f(
    { enabled: false },
    {
      onUpdate() {
        s2.transact((e2) => e2.setMeta(r2, {}));
      }
    }
  );
  return {
    key: "showSelection",
    store: t2,
    prosemirrorPlugins: [
      new Plugin({
        key: r2,
        props: {
          decorations: (e2) => {
            const { doc: a3, selection: o2 } = e2;
            if (!t2.state.enabled)
              return DecorationSet.empty;
            const c3 = Decoration.inline(o2.from, o2.to, {
              "data-show-selection": "true"
            });
            return DecorationSet.create(a3, [c3]);
          }
        }
      })
    ],
    /**
     * Show or hide the selection decoration
     */
    showSelection(e2) {
      t2.setState({ enabled: e2 });
    }
  };
});

// ../../node_modules/.pnpm/prosemirror-commands@1.7.1/node_modules/prosemirror-commands/dist/index.js
var deleteSelection = (state, dispatch) => {
  if (state.selection.empty)
    return false;
  if (dispatch)
    dispatch(state.tr.deleteSelection().scrollIntoView());
  return true;
};
function atBlockStart(state, view) {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0))
    return null;
  return $cursor;
}
var joinBackward = (state, dispatch, view) => {
  let $cursor = atBlockStart(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutBefore($cursor);
  if (!$cut) {
    let range = $cursor.blockRange(), target = range && liftTarget(range);
    if (target == null)
      return false;
    if (dispatch)
      dispatch(state.tr.lift(range, target).scrollIntoView());
    return true;
  }
  let before = $cut.nodeBefore;
  if (deleteBarrier(state, $cut, dispatch, -1))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || NodeSelection.isSelectable(before))) {
    for (let depth = $cursor.depth; ; depth--) {
      let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);
      if (delStep && delStep.slice.size < delStep.to - delStep.from) {
        if (dispatch) {
          let tr4 = state.tr.step(delStep);
          tr4.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr4.doc.resolve(tr4.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr4.doc, $cut.pos - before.nodeSize));
          dispatch(tr4.scrollIntoView());
        }
        return true;
      }
      if (depth == 1 || $cursor.node(depth - 1).childCount > 1)
        break;
    }
  }
  if (before.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());
    return true;
  }
  return false;
};
var joinTextblockBackward = (state, dispatch, view) => {
  let $cursor = atBlockStart(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutBefore($cursor);
  return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
};
var joinTextblockForward = (state, dispatch, view) => {
  let $cursor = atBlockEnd(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutAfter($cursor);
  return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
};
function joinTextblocksAround(state, $cut, dispatch) {
  let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;
  for (; !beforeText.isTextblock; beforePos--) {
    if (beforeText.type.spec.isolating)
      return false;
    let child = beforeText.lastChild;
    if (!child)
      return false;
    beforeText = child;
  }
  let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;
  for (; !afterText.isTextblock; afterPos++) {
    if (afterText.type.spec.isolating)
      return false;
    let child = afterText.firstChild;
    if (!child)
      return false;
    afterText = child;
  }
  let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);
  if (!step || step.from != beforePos || step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)
    return false;
  if (dispatch) {
    let tr4 = state.tr.step(step);
    tr4.setSelection(TextSelection.create(tr4.doc, beforePos));
    dispatch(tr4.scrollIntoView());
  }
  return true;
}
function textblockAt(node2, side, only = false) {
  for (let scan = node2; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) {
    if (scan.isTextblock)
      return true;
    if (only && scan.childCount != 1)
      return false;
  }
  return false;
}
var selectNodeBackward = (state, dispatch, view) => {
  let { $head, empty: empty4 } = state.selection, $cut = $head;
  if (!empty4)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0)
      return false;
    $cut = findCutBefore($head);
  }
  let node2 = $cut && $cut.nodeBefore;
  if (!node2 || !NodeSelection.isSelectable(node2))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node2.nodeSize)).scrollIntoView());
  return true;
};
function findCutBefore($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i3 = $pos.depth - 1; i3 >= 0; i3--) {
      if ($pos.index(i3) > 0)
        return $pos.doc.resolve($pos.before(i3 + 1));
      if ($pos.node(i3).type.spec.isolating)
        break;
    }
  return null;
}
function atBlockEnd(state, view) {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size))
    return null;
  return $cursor;
}
var joinForward = (state, dispatch, view) => {
  let $cursor = atBlockEnd(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutAfter($cursor);
  if (!$cut)
    return false;
  let after = $cut.nodeAfter;
  if (deleteBarrier(state, $cut, dispatch, 1))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || NodeSelection.isSelectable(after))) {
    let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
    if (delStep && delStep.slice.size < delStep.to - delStep.from) {
      if (dispatch) {
        let tr4 = state.tr.step(delStep);
        tr4.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr4.doc.resolve(tr4.mapping.map($cut.pos)), 1) : NodeSelection.create(tr4.doc, tr4.mapping.map($cut.pos)));
        dispatch(tr4.scrollIntoView());
      }
      return true;
    }
  }
  if (after.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());
    return true;
  }
  return false;
};
var selectNodeForward = (state, dispatch, view) => {
  let { $head, empty: empty4 } = state.selection, $cut = $head;
  if (!empty4)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size)
      return false;
    $cut = findCutAfter($head);
  }
  let node2 = $cut && $cut.nodeAfter;
  if (!node2 || !NodeSelection.isSelectable(node2))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());
  return true;
};
function findCutAfter($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i3 = $pos.depth - 1; i3 >= 0; i3--) {
      let parent = $pos.node(i3);
      if ($pos.index(i3) + 1 < parent.childCount)
        return $pos.doc.resolve($pos.after(i3 + 1));
      if (parent.type.spec.isolating)
        break;
    }
  return null;
}
var joinUp = (state, dispatch) => {
  let sel = state.selection, nodeSel = sel instanceof NodeSelection, point5;
  if (nodeSel) {
    if (sel.node.isTextblock || !canJoin(state.doc, sel.from))
      return false;
    point5 = sel.from;
  } else {
    point5 = joinPoint(state.doc, sel.from, -1);
    if (point5 == null)
      return false;
  }
  if (dispatch) {
    let tr4 = state.tr.join(point5);
    if (nodeSel)
      tr4.setSelection(NodeSelection.create(tr4.doc, point5 - state.doc.resolve(point5).nodeBefore.nodeSize));
    dispatch(tr4.scrollIntoView());
  }
  return true;
};
var joinDown = (state, dispatch) => {
  let sel = state.selection, point5;
  if (sel instanceof NodeSelection) {
    if (sel.node.isTextblock || !canJoin(state.doc, sel.to))
      return false;
    point5 = sel.to;
  } else {
    point5 = joinPoint(state.doc, sel.to, 1);
    if (point5 == null)
      return false;
  }
  if (dispatch)
    dispatch(state.tr.join(point5).scrollIntoView());
  return true;
};
var lift2 = (state, dispatch) => {
  let { $from, $to } = state.selection;
  let range = $from.blockRange($to), target = range && liftTarget(range);
  if (target == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range, target).scrollIntoView());
  return true;
};
var newlineInCode = (state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  if (dispatch)
    dispatch(state.tr.insertText("\n").scrollIntoView());
  return true;
};
function defaultBlockAt(match2) {
  for (let i3 = 0; i3 < match2.edgeCount; i3++) {
    let { type } = match2.edge(i3);
    if (type.isTextblock && !type.hasRequiredAttrs())
      return type;
  }
  return null;
}
var exitCode = (state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));
  if (!type || !above.canReplaceWith(after, after, type))
    return false;
  if (dispatch) {
    let pos = $head.after(), tr4 = state.tr.replaceWith(pos, pos, type.createAndFill());
    tr4.setSelection(Selection.near(tr4.doc.resolve(pos), 1));
    dispatch(tr4.scrollIntoView());
  }
  return true;
};
var createParagraphNear = (state, dispatch) => {
  let sel = state.selection, { $from, $to } = sel;
  if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)
    return false;
  let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));
  if (!type || !type.isTextblock)
    return false;
  if (dispatch) {
    let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;
    let tr4 = state.tr.insert(side, type.createAndFill());
    tr4.setSelection(TextSelection.create(tr4.doc, side + 1));
    dispatch(tr4.scrollIntoView());
  }
  return true;
};
var liftEmptyBlock = (state, dispatch) => {
  let { $cursor } = state.selection;
  if (!$cursor || $cursor.parent.content.size)
    return false;
  if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {
    let before = $cursor.before();
    if (canSplit(state.doc, before)) {
      if (dispatch)
        dispatch(state.tr.split(before).scrollIntoView());
      return true;
    }
  }
  let range = $cursor.blockRange(), target = range && liftTarget(range);
  if (target == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range, target).scrollIntoView());
  return true;
};
function splitBlockAs(splitNode) {
  return (state, dispatch) => {
    let { $from, $to } = state.selection;
    if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {
      if (!$from.parentOffset || !canSplit(state.doc, $from.pos))
        return false;
      if (dispatch)
        dispatch(state.tr.split($from.pos).scrollIntoView());
      return true;
    }
    if (!$from.depth)
      return false;
    let types2 = [];
    let splitDepth, deflt, atEnd = false, atStart = false;
    for (let d = $from.depth; ; d--) {
      let node2 = $from.node(d);
      if (node2.isBlock) {
        atEnd = $from.end(d) == $from.pos + ($from.depth - d);
        atStart = $from.start(d) == $from.pos - ($from.depth - d);
        deflt = defaultBlockAt($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1)));
        let splitType = splitNode && splitNode($to.parent, atEnd, $from);
        types2.unshift(splitType || (atEnd && deflt ? { type: deflt } : null));
        splitDepth = d;
        break;
      } else {
        if (d == 1)
          return false;
        types2.unshift(null);
      }
    }
    let tr4 = state.tr;
    if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)
      tr4.deleteSelection();
    let splitPos = tr4.mapping.map($from.pos);
    let can = canSplit(tr4.doc, splitPos, types2.length, types2);
    if (!can) {
      types2[0] = deflt ? { type: deflt } : null;
      can = canSplit(tr4.doc, splitPos, types2.length, types2);
    }
    if (!can)
      return false;
    tr4.split(splitPos, types2.length, types2);
    if (!atEnd && atStart && $from.node(splitDepth).type != deflt) {
      let first2 = tr4.mapping.map($from.before(splitDepth)), $first = tr4.doc.resolve(first2);
      if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt))
        tr4.setNodeMarkup(tr4.mapping.map($from.before(splitDepth)), deflt);
    }
    if (dispatch)
      dispatch(tr4.scrollIntoView());
    return true;
  };
}
var splitBlock = splitBlockAs();
var selectParentNode = (state, dispatch) => {
  let { $from, to: to2 } = state.selection, pos;
  let same = $from.sharedDepth(to2);
  if (same == 0)
    return false;
  pos = $from.before(same);
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));
  return true;
};
var selectAll = (state, dispatch) => {
  if (dispatch)
    dispatch(state.tr.setSelection(new AllSelection(state.doc)));
  return true;
};
function joinMaybeClear(state, $pos, dispatch) {
  let before = $pos.nodeBefore, after = $pos.nodeAfter, index4 = $pos.index();
  if (!before || !after || !before.type.compatibleContent(after.type))
    return false;
  if (!before.content.size && $pos.parent.canReplace(index4 - 1, index4)) {
    if (dispatch)
      dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());
    return true;
  }
  if (!$pos.parent.canReplace(index4, index4 + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))
    return false;
  if (dispatch)
    dispatch(state.tr.join($pos.pos).scrollIntoView());
  return true;
}
function deleteBarrier(state, $cut, dispatch, dir) {
  let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match2;
  let isolated = before.type.spec.isolating || after.type.spec.isolating;
  if (!isolated && joinMaybeClear(state, $cut, dispatch))
    return true;
  let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);
  if (canDelAfter && (conn = (match2 = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match2.matchType(conn[0] || after.type).validEnd) {
    if (dispatch) {
      let end = $cut.pos + after.nodeSize, wrap5 = Fragment.empty;
      for (let i3 = conn.length - 1; i3 >= 0; i3--)
        wrap5 = Fragment.from(conn[i3].create(null, wrap5));
      wrap5 = Fragment.from(before.copy(wrap5));
      let tr4 = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap5, 1, 0), conn.length, true));
      let $joinAt = tr4.doc.resolve(end + 2 * conn.length);
      if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr4.doc, $joinAt.pos))
        tr4.join($joinAt.pos);
      dispatch(tr4.scrollIntoView());
    }
    return true;
  }
  let selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : Selection.findFrom($cut, 1);
  let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range);
  if (target != null && target >= $cut.depth) {
    if (dispatch)
      dispatch(state.tr.lift(range, target).scrollIntoView());
    return true;
  }
  if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) {
    let at2 = before, wrap5 = [];
    for (; ; ) {
      wrap5.push(at2);
      if (at2.isTextblock)
        break;
      at2 = at2.lastChild;
    }
    let afterText = after, afterDepth = 1;
    for (; !afterText.isTextblock; afterText = afterText.firstChild)
      afterDepth++;
    if (at2.canReplace(at2.childCount, at2.childCount, afterText.content)) {
      if (dispatch) {
        let end = Fragment.empty;
        for (let i3 = wrap5.length - 1; i3 >= 0; i3--)
          end = Fragment.from(wrap5[i3].copy(end));
        let tr4 = state.tr.step(new ReplaceAroundStep($cut.pos - wrap5.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap5.length, 0), 0, true));
        dispatch(tr4.scrollIntoView());
      }
      return true;
    }
  }
  return false;
}
function selectTextblockSide(side) {
  return function(state, dispatch) {
    let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;
    let depth = $pos.depth;
    while ($pos.node(depth).isInline) {
      if (!depth)
        return false;
      depth--;
    }
    if (!$pos.node(depth).isTextblock)
      return false;
    if (dispatch)
      dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));
    return true;
  };
}
var selectTextblockStart = selectTextblockSide(-1);
var selectTextblockEnd = selectTextblockSide(1);
function wrapIn(nodeType, attrs = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);
    if (!wrapping)
      return false;
    if (dispatch)
      dispatch(state.tr.wrap(range, wrapping).scrollIntoView());
    return true;
  };
}
function setBlockType2(nodeType, attrs = null) {
  return function(state, dispatch) {
    let applicable = false;
    for (let i3 = 0; i3 < state.selection.ranges.length && !applicable; i3++) {
      let { $from: { pos: from4 }, $to: { pos: to2 } } = state.selection.ranges[i3];
      state.doc.nodesBetween(from4, to2, (node2, pos) => {
        if (applicable)
          return false;
        if (!node2.isTextblock || node2.hasMarkup(nodeType, attrs))
          return;
        if (node2.type == nodeType) {
          applicable = true;
        } else {
          let $pos = state.doc.resolve(pos), index4 = $pos.index();
          applicable = $pos.parent.canReplaceWith(index4, index4 + 1, nodeType);
        }
      });
    }
    if (!applicable)
      return false;
    if (dispatch) {
      let tr4 = state.tr;
      for (let i3 = 0; i3 < state.selection.ranges.length; i3++) {
        let { $from: { pos: from4 }, $to: { pos: to2 } } = state.selection.ranges[i3];
        tr4.setBlockType(from4, to2, nodeType, attrs);
      }
      dispatch(tr4.scrollIntoView());
    }
    return true;
  };
}
function chainCommands(...commands) {
  return function(state, dispatch, view) {
    for (let i3 = 0; i3 < commands.length; i3++)
      if (commands[i3](state, dispatch, view))
        return true;
    return false;
  };
}
var backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);
var del = chainCommands(deleteSelection, joinForward, selectNodeForward);
var pcBaseKeymap = {
  "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),
  "Mod-Enter": exitCode,
  "Backspace": backspace,
  "Mod-Backspace": backspace,
  "Shift-Backspace": backspace,
  "Delete": del,
  "Mod-Delete": del,
  "Mod-a": selectAll
};
var macBaseKeymap = {
  "Ctrl-h": pcBaseKeymap["Backspace"],
  "Alt-Backspace": pcBaseKeymap["Mod-Backspace"],
  "Ctrl-d": pcBaseKeymap["Delete"],
  "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"],
  "Alt-Delete": pcBaseKeymap["Mod-Delete"],
  "Alt-d": pcBaseKeymap["Mod-Delete"],
  "Ctrl-a": selectTextblockStart,
  "Ctrl-e": selectTextblockEnd
};
for (let key2 in pcBaseKeymap)
  macBaseKeymap[key2] = pcBaseKeymap[key2];
var mac2 = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false;

// ../../node_modules/.pnpm/prosemirror-schema-list@1.5.1/node_modules/prosemirror-schema-list/dist/index.js
function wrapInList(listType, attrs = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to);
    if (!range)
      return false;
    let tr4 = dispatch ? state.tr : null;
    if (!wrapRangeInList(tr4, range, listType, attrs))
      return false;
    if (dispatch)
      dispatch(tr4.scrollIntoView());
    return true;
  };
}
function wrapRangeInList(tr4, range, listType, attrs = null) {
  let doJoin = false, outerRange = range, doc4 = range.$from.doc;
  if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {
    if (range.$from.index(range.depth - 1) == 0)
      return false;
    let $insert = doc4.resolve(range.start - 2);
    outerRange = new NodeRange($insert, $insert, range.depth);
    if (range.endIndex < range.parent.childCount)
      range = new NodeRange(range.$from, doc4.resolve(range.$to.end(range.depth)), range.depth);
    doJoin = true;
  }
  let wrap5 = findWrapping(outerRange, listType, attrs, range);
  if (!wrap5)
    return false;
  if (tr4)
    doWrapInList(tr4, range, wrap5, doJoin, listType);
  return true;
}
function doWrapInList(tr4, range, wrappers, joinBefore, listType) {
  let content5 = Fragment.empty;
  for (let i3 = wrappers.length - 1; i3 >= 0; i3--)
    content5 = Fragment.from(wrappers[i3].type.create(wrappers[i3].attrs, content5));
  tr4.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content5, 0, 0), wrappers.length, true));
  let found2 = 0;
  for (let i3 = 0; i3 < wrappers.length; i3++)
    if (wrappers[i3].type == listType)
      found2 = i3 + 1;
  let splitDepth = wrappers.length - found2;
  let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent;
  for (let i3 = range.startIndex, e2 = range.endIndex, first2 = true; i3 < e2; i3++, first2 = false) {
    if (!first2 && canSplit(tr4.doc, splitPos, splitDepth)) {
      tr4.split(splitPos, splitDepth);
      splitPos += 2 * splitDepth;
    }
    splitPos += parent.child(i3).nodeSize;
  }
  return tr4;
}
function liftListItem(itemType) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to, (node2) => node2.childCount > 0 && node2.firstChild.type == itemType);
    if (!range)
      return false;
    if (!dispatch)
      return true;
    if ($from.node(range.depth - 1).type == itemType)
      return liftToOuterList(state, dispatch, itemType, range);
    else
      return liftOutOfList(state, dispatch, range);
  };
}
function liftToOuterList(state, dispatch, itemType, range) {
  let tr4 = state.tr, end = range.end, endOfList = range.$to.end(range.depth);
  if (end < endOfList) {
    tr4.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));
    range = new NodeRange(tr4.doc.resolve(range.$from.pos), tr4.doc.resolve(endOfList), range.depth);
  }
  const target = liftTarget(range);
  if (target == null)
    return false;
  tr4.lift(range, target);
  let $after = tr4.doc.resolve(tr4.mapping.map(end, -1) - 1);
  if (canJoin(tr4.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type)
    tr4.join($after.pos);
  dispatch(tr4.scrollIntoView());
  return true;
}
function liftOutOfList(state, dispatch, range) {
  let tr4 = state.tr, list7 = range.parent;
  for (let pos = range.end, i3 = range.endIndex - 1, e2 = range.startIndex; i3 > e2; i3--) {
    pos -= list7.child(i3).nodeSize;
    tr4.delete(pos - 1, pos + 1);
  }
  let $start = tr4.doc.resolve(range.start), item = $start.nodeAfter;
  if (tr4.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize)
    return false;
  let atStart = range.startIndex == 0, atEnd = range.endIndex == list7.childCount;
  let parent = $start.node(-1), indexBefore = $start.index(-1);
  if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list7))))
    return false;
  let start = $start.pos, end = start + item.nodeSize;
  tr4.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list7.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list7.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));
  dispatch(tr4.scrollIntoView());
  return true;
}
function sinkListItem(itemType) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to, (node2) => node2.childCount > 0 && node2.firstChild.type == itemType);
    if (!range)
      return false;
    let startIndex = range.startIndex;
    if (startIndex == 0)
      return false;
    let parent = range.parent, nodeBefore = parent.child(startIndex - 1);
    if (nodeBefore.type != itemType)
      return false;
    if (dispatch) {
      let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;
      let inner = Fragment.from(nestedBefore ? itemType.create() : null);
      let slice2 = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0);
      let before = range.start, after = range.end;
      dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true)).scrollIntoView());
    }
    return true;
  };
}

// ../../node_modules/.pnpm/w3c-keyname@2.2.8/node_modules/w3c-keyname/index.js
var base = {
  8: "Backspace",
  9: "Tab",
  10: "Enter",
  12: "NumLock",
  13: "Enter",
  16: "Shift",
  17: "Control",
  18: "Alt",
  20: "CapsLock",
  27: "Escape",
  32: " ",
  33: "PageUp",
  34: "PageDown",
  35: "End",
  36: "Home",
  37: "ArrowLeft",
  38: "ArrowUp",
  39: "ArrowRight",
  40: "ArrowDown",
  44: "PrintScreen",
  45: "Insert",
  46: "Delete",
  59: ";",
  61: "=",
  91: "Meta",
  92: "Meta",
  106: "*",
  107: "+",
  108: ",",
  109: "-",
  110: ".",
  111: "/",
  144: "NumLock",
  145: "ScrollLock",
  160: "Shift",
  161: "Shift",
  162: "Control",
  163: "Control",
  164: "Alt",
  165: "Alt",
  173: "-",
  186: ";",
  187: "=",
  188: ",",
  189: "-",
  190: ".",
  191: "/",
  192: "`",
  219: "[",
  220: "\\",
  221: "]",
  222: "'"
};
var shift = {
  48: ")",
  49: "!",
  50: "@",
  51: "#",
  52: "$",
  53: "%",
  54: "^",
  55: "&",
  56: "*",
  57: "(",
  59: ":",
  61: "+",
  173: "_",
  186: ":",
  187: "+",
  188: "<",
  189: "_",
  190: ">",
  191: "?",
  192: "~",
  219: "{",
  220: "|",
  221: "}",
  222: '"'
};
var mac3 = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
var ie2 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
for (i3 = 0; i3 < 10; i3++) base[48 + i3] = base[96 + i3] = String(i3);
var i3;
for (i3 = 1; i3 <= 24; i3++) base[i3 + 111] = "F" + i3;
var i3;
for (i3 = 65; i3 <= 90; i3++) {
  base[i3] = String.fromCharCode(i3 + 32);
  shift[i3] = String.fromCharCode(i3);
}
var i3;
for (code5 in base) if (!shift.hasOwnProperty(code5)) shift[code5] = base[code5];
var code5;
function keyName(event) {
  var ignoreKey = mac3 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie2 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
  var name = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified";
  if (name == "Esc") name = "Escape";
  if (name == "Del") name = "Delete";
  if (name == "Left") name = "ArrowLeft";
  if (name == "Up") name = "ArrowUp";
  if (name == "Right") name = "ArrowRight";
  if (name == "Down") name = "ArrowDown";
  return name;
}

// ../../node_modules/.pnpm/prosemirror-keymap@1.2.3/node_modules/prosemirror-keymap/dist/index.js
var mac4 = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
var windows2 = typeof navigator != "undefined" && /Win/.test(navigator.platform);
function normalizeKeyName(name) {
  let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];
  if (result == "Space")
    result = " ";
  let alt, ctrl, shift5, meta2;
  for (let i3 = 0; i3 < parts.length - 1; i3++) {
    let mod = parts[i3];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta2 = true;
    else if (/^a(lt)?$/i.test(mod))
      alt = true;
    else if (/^(c|ctrl|control)$/i.test(mod))
      ctrl = true;
    else if (/^s(hift)?$/i.test(mod))
      shift5 = true;
    else if (/^mod$/i.test(mod)) {
      if (mac4)
        meta2 = true;
      else
        ctrl = true;
    } else
      throw new Error("Unrecognized modifier name: " + mod);
  }
  if (alt)
    result = "Alt-" + result;
  if (ctrl)
    result = "Ctrl-" + result;
  if (meta2)
    result = "Meta-" + result;
  if (shift5)
    result = "Shift-" + result;
  return result;
}
function normalize(map7) {
  let copy3 = /* @__PURE__ */ Object.create(null);
  for (let prop in map7)
    copy3[normalizeKeyName(prop)] = map7[prop];
  return copy3;
}
function modifiers(name, event, shift5 = true) {
  if (event.altKey)
    name = "Alt-" + name;
  if (event.ctrlKey)
    name = "Ctrl-" + name;
  if (event.metaKey)
    name = "Meta-" + name;
  if (shift5 && event.shiftKey)
    name = "Shift-" + name;
  return name;
}
function keymap(bindings) {
  return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });
}
function keydownHandler(bindings) {
  let map7 = normalize(bindings);
  return function(view, event) {
    let name = keyName(event), baseName, direct = map7[modifiers(name, event)];
    if (direct && direct(view.state, view.dispatch, view))
      return true;
    if (name.length == 1 && name != " ") {
      if (event.shiftKey) {
        let noShift = map7[modifiers(name, event, false)];
        if (noShift && noShift(view.state, view.dispatch, view))
          return true;
      }
      if ((event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
      !(windows2 && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name) {
        let fromCode = map7[modifiers(baseName, event)];
        if (fromCode && fromCode(view.state, view.dispatch, view))
          return true;
      }
    }
    return false;
  };
}

// ../../node_modules/.pnpm/@tiptap+core@3.14.0_@tiptap+pm@3.14.0/node_modules/@tiptap/core/dist/index.js
var __defProp = Object.defineProperty;
var __export2 = (target, all9) => {
  for (var name in all9)
    __defProp(target, name, { get: all9[name], enumerable: true });
};
function createChainableState(config) {
  const { state, transaction } = config;
  let { selection } = transaction;
  let { doc: doc4 } = transaction;
  let { storedMarks } = transaction;
  return {
    ...state,
    apply: state.apply.bind(state),
    applyTransaction: state.applyTransaction.bind(state),
    plugins: state.plugins,
    schema: state.schema,
    reconfigure: state.reconfigure.bind(state),
    toJSON: state.toJSON.bind(state),
    get storedMarks() {
      return storedMarks;
    },
    get selection() {
      return selection;
    },
    get doc() {
      return doc4;
    },
    get tr() {
      selection = transaction.selection;
      doc4 = transaction.doc;
      storedMarks = transaction.storedMarks;
      return transaction;
    }
  };
}
var CommandManager = class {
  constructor(props) {
    this.editor = props.editor;
    this.rawCommands = this.editor.extensionManager.commands;
    this.customState = props.state;
  }
  get hasCustomState() {
    return !!this.customState;
  }
  get state() {
    return this.customState || this.editor.state;
  }
  get commands() {
    const { rawCommands, editor, state } = this;
    const { view } = editor;
    const { tr: tr4 } = state;
    const props = this.buildProps(tr4);
    return Object.fromEntries(
      Object.entries(rawCommands).map(([name, command2]) => {
        const method = (...args2) => {
          const callback = command2(...args2)(props);
          if (!tr4.getMeta("preventDispatch") && !this.hasCustomState) {
            view.dispatch(tr4);
          }
          return callback;
        };
        return [name, method];
      })
    );
  }
  get chain() {
    return () => this.createChain();
  }
  get can() {
    return () => this.createCan();
  }
  createChain(startTr, shouldDispatch = true) {
    const { rawCommands, editor, state } = this;
    const { view } = editor;
    const callbacks = [];
    const hasStartTransaction = !!startTr;
    const tr4 = startTr || state.tr;
    const run32 = () => {
      if (!hasStartTransaction && shouldDispatch && !tr4.getMeta("preventDispatch") && !this.hasCustomState) {
        view.dispatch(tr4);
      }
      return callbacks.every((callback) => callback === true);
    };
    const chain = {
      ...Object.fromEntries(
        Object.entries(rawCommands).map(([name, command2]) => {
          const chainedCommand = (...args2) => {
            const props = this.buildProps(tr4, shouldDispatch);
            const callback = command2(...args2)(props);
            callbacks.push(callback);
            return chain;
          };
          return [name, chainedCommand];
        })
      ),
      run: run32
    };
    return chain;
  }
  createCan(startTr) {
    const { rawCommands, state } = this;
    const dispatch = false;
    const tr4 = startTr || state.tr;
    const props = this.buildProps(tr4, dispatch);
    const formattedCommands = Object.fromEntries(
      Object.entries(rawCommands).map(([name, command2]) => {
        return [name, (...args2) => command2(...args2)({ ...props, dispatch: void 0 })];
      })
    );
    return {
      ...formattedCommands,
      chain: () => this.createChain(tr4, dispatch)
    };
  }
  buildProps(tr4, shouldDispatch = true) {
    const { rawCommands, editor, state } = this;
    const { view } = editor;
    const props = {
      tr: tr4,
      editor,
      view,
      state: createChainableState({
        state,
        transaction: tr4
      }),
      dispatch: shouldDispatch ? () => void 0 : void 0,
      chain: () => this.createChain(tr4, shouldDispatch),
      can: () => this.createCan(tr4),
      get commands() {
        return Object.fromEntries(
          Object.entries(rawCommands).map(([name, command2]) => {
            return [name, (...args2) => command2(...args2)(props)];
          })
        );
      }
    };
    return props;
  }
};
var commands_exports = {};
__export2(commands_exports, {
  blur: () => blur,
  clearContent: () => clearContent,
  clearNodes: () => clearNodes,
  command: () => command,
  createParagraphNear: () => createParagraphNear2,
  cut: () => cut,
  deleteCurrentNode: () => deleteCurrentNode,
  deleteNode: () => deleteNode,
  deleteRange: () => deleteRange2,
  deleteSelection: () => deleteSelection2,
  enter: () => enter,
  exitCode: () => exitCode2,
  extendMarkRange: () => extendMarkRange,
  first: () => first,
  focus: () => focus,
  forEach: () => forEach3,
  insertContent: () => insertContent,
  insertContentAt: () => insertContentAt,
  joinBackward: () => joinBackward2,
  joinDown: () => joinDown2,
  joinForward: () => joinForward2,
  joinItemBackward: () => joinItemBackward,
  joinItemForward: () => joinItemForward,
  joinTextblockBackward: () => joinTextblockBackward2,
  joinTextblockForward: () => joinTextblockForward2,
  joinUp: () => joinUp2,
  keyboardShortcut: () => keyboardShortcut,
  lift: () => lift3,
  liftEmptyBlock: () => liftEmptyBlock2,
  liftListItem: () => liftListItem2,
  newlineInCode: () => newlineInCode2,
  resetAttributes: () => resetAttributes,
  scrollIntoView: () => scrollIntoView,
  selectAll: () => selectAll2,
  selectNodeBackward: () => selectNodeBackward2,
  selectNodeForward: () => selectNodeForward2,
  selectParentNode: () => selectParentNode2,
  selectTextblockEnd: () => selectTextblockEnd2,
  selectTextblockStart: () => selectTextblockStart2,
  setContent: () => setContent,
  setMark: () => setMark,
  setMeta: () => setMeta2,
  setNode: () => setNode,
  setNodeSelection: () => setNodeSelection,
  setTextDirection: () => setTextDirection,
  setTextSelection: () => setTextSelection,
  sinkListItem: () => sinkListItem2,
  splitBlock: () => splitBlock2,
  splitListItem: () => splitListItem,
  toggleList: () => toggleList,
  toggleMark: () => toggleMark,
  toggleNode: () => toggleNode,
  toggleWrap: () => toggleWrap,
  undoInputRule: () => undoInputRule,
  unsetAllMarks: () => unsetAllMarks,
  unsetMark: () => unsetMark,
  unsetTextDirection: () => unsetTextDirection,
  updateAttributes: () => updateAttributes,
  wrapIn: () => wrapIn2,
  wrapInList: () => wrapInList2
});
var blur = () => ({ editor, view }) => {
  requestAnimationFrame(() => {
    var _a2;
    if (!editor.isDestroyed) {
      ;
      view.dom.blur();
      (_a2 = window == null ? void 0 : window.getSelection()) == null ? void 0 : _a2.removeAllRanges();
    }
  });
  return true;
};
var clearContent = (emitUpdate = true) => ({ commands }) => {
  return commands.setContent("", { emitUpdate });
};
var clearNodes = () => ({ state, tr: tr4, dispatch }) => {
  const { selection } = tr4;
  const { ranges } = selection;
  if (!dispatch) {
    return true;
  }
  ranges.forEach(({ $from, $to }) => {
    state.doc.nodesBetween($from.pos, $to.pos, (node2, pos) => {
      if (node2.type.isText) {
        return;
      }
      const { doc: doc4, mapping } = tr4;
      const $mappedFrom = doc4.resolve(mapping.map(pos));
      const $mappedTo = doc4.resolve(mapping.map(pos + node2.nodeSize));
      const nodeRange = $mappedFrom.blockRange($mappedTo);
      if (!nodeRange) {
        return;
      }
      const targetLiftDepth = liftTarget(nodeRange);
      if (node2.type.isTextblock) {
        const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index());
        tr4.setNodeMarkup(nodeRange.start, defaultType);
      }
      if (targetLiftDepth || targetLiftDepth === 0) {
        tr4.lift(nodeRange, targetLiftDepth);
      }
    });
  });
  return true;
};
var command = (fn4) => (props) => {
  return fn4(props);
};
var createParagraphNear2 = () => ({ state, dispatch }) => {
  return createParagraphNear(state, dispatch);
};
var cut = (originRange, targetPos) => ({ editor, tr: tr4 }) => {
  const { state } = editor;
  const contentSlice = state.doc.slice(originRange.from, originRange.to);
  tr4.deleteRange(originRange.from, originRange.to);
  const newPos = tr4.mapping.map(targetPos);
  tr4.insert(newPos, contentSlice.content);
  tr4.setSelection(new TextSelection(tr4.doc.resolve(Math.max(newPos - 1, 0))));
  return true;
};
var deleteCurrentNode = () => ({ tr: tr4, dispatch }) => {
  const { selection } = tr4;
  const currentNode = selection.$anchor.node();
  if (currentNode.content.size > 0) {
    return false;
  }
  const $pos = tr4.selection.$anchor;
  for (let depth = $pos.depth; depth > 0; depth -= 1) {
    const node2 = $pos.node(depth);
    if (node2.type === currentNode.type) {
      if (dispatch) {
        const from4 = $pos.before(depth);
        const to2 = $pos.after(depth);
        tr4.delete(from4, to2).scrollIntoView();
      }
      return true;
    }
  }
  return false;
};
function getNodeType(nameOrType, schema) {
  if (typeof nameOrType === "string") {
    if (!schema.nodes[nameOrType]) {
      throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`);
    }
    return schema.nodes[nameOrType];
  }
  return nameOrType;
}
var deleteNode = (typeOrName) => ({ tr: tr4, state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  const $pos = tr4.selection.$anchor;
  for (let depth = $pos.depth; depth > 0; depth -= 1) {
    const node2 = $pos.node(depth);
    if (node2.type === type) {
      if (dispatch) {
        const from4 = $pos.before(depth);
        const to2 = $pos.after(depth);
        tr4.delete(from4, to2).scrollIntoView();
      }
      return true;
    }
  }
  return false;
};
var deleteRange2 = (range) => ({ tr: tr4, dispatch }) => {
  const { from: from4, to: to2 } = range;
  if (dispatch) {
    tr4.delete(from4, to2);
  }
  return true;
};
var deleteSelection2 = () => ({ state, dispatch }) => {
  return deleteSelection(state, dispatch);
};
var enter = () => ({ commands }) => {
  return commands.keyboardShortcut("Enter");
};
var exitCode2 = () => ({ state, dispatch }) => {
  return exitCode(state, dispatch);
};
function isRegExp(value) {
  return Object.prototype.toString.call(value) === "[object RegExp]";
}
function objectIncludes(object1, object2, options2 = { strict: true }) {
  const keys5 = Object.keys(object2);
  if (!keys5.length) {
    return true;
  }
  return keys5.every((key2) => {
    if (options2.strict) {
      return object2[key2] === object1[key2];
    }
    if (isRegExp(object2[key2])) {
      return object2[key2].test(object1[key2]);
    }
    return object2[key2] === object1[key2];
  });
}
function findMarkInSet(marks, type, attributes = {}) {
  return marks.find((item) => {
    return item.type === type && objectIncludes(
      // Only check equality for the attributes that are provided
      Object.fromEntries(Object.keys(attributes).map((k3) => [k3, item.attrs[k3]])),
      attributes
    );
  });
}
function isMarkInSet(marks, type, attributes = {}) {
  return !!findMarkInSet(marks, type, attributes);
}
function getMarkRange($pos, type, attributes) {
  var _a2;
  if (!$pos || !type) {
    return;
  }
  let start = $pos.parent.childAfter($pos.parentOffset);
  if (!start.node || !start.node.marks.some((mark22) => mark22.type === type)) {
    start = $pos.parent.childBefore($pos.parentOffset);
  }
  if (!start.node || !start.node.marks.some((mark22) => mark22.type === type)) {
    return;
  }
  attributes = attributes || ((_a2 = start.node.marks[0]) == null ? void 0 : _a2.attrs);
  const mark2 = findMarkInSet([...start.node.marks], type, attributes);
  if (!mark2) {
    return;
  }
  let startIndex = start.index;
  let startPos = $pos.start() + start.offset;
  let endIndex = startIndex + 1;
  let endPos = startPos + start.node.nodeSize;
  while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {
    startIndex -= 1;
    startPos -= $pos.parent.child(startIndex).nodeSize;
  }
  while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {
    endPos += $pos.parent.child(endIndex).nodeSize;
    endIndex += 1;
  }
  return {
    from: startPos,
    to: endPos
  };
}
function getMarkType(nameOrType, schema) {
  if (typeof nameOrType === "string") {
    if (!schema.marks[nameOrType]) {
      throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`);
    }
    return schema.marks[nameOrType];
  }
  return nameOrType;
}
var extendMarkRange = (typeOrName, attributes = {}) => ({ tr: tr4, state, dispatch }) => {
  const type = getMarkType(typeOrName, state.schema);
  const { doc: doc4, selection } = tr4;
  const { $from, from: from4, to: to2 } = selection;
  if (dispatch) {
    const range = getMarkRange($from, type, attributes);
    if (range && range.from <= from4 && range.to >= to2) {
      const newSelection = TextSelection.create(doc4, range.from, range.to);
      tr4.setSelection(newSelection);
    }
  }
  return true;
};
var first = (commands) => (props) => {
  const items = typeof commands === "function" ? commands(props) : commands;
  for (let i3 = 0; i3 < items.length; i3 += 1) {
    if (items[i3](props)) {
      return true;
    }
  }
  return false;
};
function isTextSelection(value) {
  return value instanceof TextSelection;
}
function minMax(value = 0, min3 = 0, max3 = 0) {
  return Math.min(Math.max(value, min3), max3);
}
function resolveFocusPosition(doc4, position4 = null) {
  if (!position4) {
    return null;
  }
  const selectionAtStart = Selection.atStart(doc4);
  const selectionAtEnd = Selection.atEnd(doc4);
  if (position4 === "start" || position4 === true) {
    return selectionAtStart;
  }
  if (position4 === "end") {
    return selectionAtEnd;
  }
  const minPos = selectionAtStart.from;
  const maxPos = selectionAtEnd.to;
  if (position4 === "all") {
    return TextSelection.create(doc4, minMax(0, minPos, maxPos), minMax(doc4.content.size, minPos, maxPos));
  }
  return TextSelection.create(doc4, minMax(position4, minPos, maxPos), minMax(position4, minPos, maxPos));
}
function isAndroid() {
  return navigator.platform === "Android" || /android/i.test(navigator.userAgent);
}
function isiOS() {
  return ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(navigator.platform) || // iPad on iOS 13 detection
  navigator.userAgent.includes("Mac") && "ontouchend" in document;
}
var focus = (position4 = null, options2 = {}) => ({ editor, view, tr: tr4, dispatch }) => {
  options2 = {
    scrollIntoView: true,
    ...options2
  };
  const delayedFocus = () => {
    if (isiOS() || isAndroid()) {
      ;
      view.dom.focus();
    }
    requestAnimationFrame(() => {
      if (!editor.isDestroyed) {
        view.focus();
        if (options2 == null ? void 0 : options2.scrollIntoView) {
          editor.commands.scrollIntoView();
        }
      }
    });
  };
  if (view.hasFocus() && position4 === null || position4 === false) {
    return true;
  }
  if (dispatch && position4 === null && !isTextSelection(editor.state.selection)) {
    delayedFocus();
    return true;
  }
  const selection = resolveFocusPosition(tr4.doc, position4) || editor.state.selection;
  const isSameSelection = editor.state.selection.eq(selection);
  if (dispatch) {
    if (!isSameSelection) {
      tr4.setSelection(selection);
    }
    if (isSameSelection && tr4.storedMarks) {
      tr4.setStoredMarks(tr4.storedMarks);
    }
    delayedFocus();
  }
  return true;
};
var forEach3 = (items, fn4) => (props) => {
  return items.every((item, index4) => fn4(item, { ...props, index: index4 }));
};
var insertContent = (value, options2) => ({ tr: tr4, commands }) => {
  return commands.insertContentAt({ from: tr4.selection.from, to: tr4.selection.to }, value, options2);
};
var removeWhitespaces = (node2) => {
  const children = node2.childNodes;
  for (let i3 = children.length - 1; i3 >= 0; i3 -= 1) {
    const child = children[i3];
    if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) {
      node2.removeChild(child);
    } else if (child.nodeType === 1) {
      removeWhitespaces(child);
    }
  }
  return node2;
};
function elementFromString(value) {
  if (typeof window === "undefined") {
    throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");
  }
  const wrappedValue = `<body>${value}</body>`;
  const html7 = new window.DOMParser().parseFromString(wrappedValue, "text/html").body;
  return removeWhitespaces(html7);
}
function createNodeFromContent(content5, schema, options2) {
  if (content5 instanceof Node2 || content5 instanceof Fragment) {
    return content5;
  }
  options2 = {
    slice: true,
    parseOptions: {},
    ...options2
  };
  const isJSONContent = typeof content5 === "object" && content5 !== null;
  const isTextContent = typeof content5 === "string";
  if (isJSONContent) {
    try {
      const isArrayContent = Array.isArray(content5) && content5.length > 0;
      if (isArrayContent) {
        return Fragment.fromArray(content5.map((item) => schema.nodeFromJSON(item)));
      }
      const node2 = schema.nodeFromJSON(content5);
      if (options2.errorOnInvalidContent) {
        node2.check();
      }
      return node2;
    } catch (error2) {
      if (options2.errorOnInvalidContent) {
        throw new Error("[tiptap error]: Invalid JSON content", { cause: error2 });
      }
      console.warn("[tiptap warn]: Invalid content.", "Passed value:", content5, "Error:", error2);
      return createNodeFromContent("", schema, options2);
    }
  }
  if (isTextContent) {
    if (options2.errorOnInvalidContent) {
      let hasInvalidContent = false;
      let invalidContent = "";
      const contentCheckSchema = new Schema({
        topNode: schema.spec.topNode,
        marks: schema.spec.marks,
        // Prosemirror's schemas are executed such that: the last to execute, matches last
        // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle
        nodes: schema.spec.nodes.append({
          __tiptap__private__unknown__catch__all__node: {
            content: "inline*",
            group: "block",
            parseDOM: [
              {
                tag: "*",
                getAttrs: (e2) => {
                  hasInvalidContent = true;
                  invalidContent = typeof e2 === "string" ? e2 : e2.outerHTML;
                  return null;
                }
              }
            ]
          }
        })
      });
      if (options2.slice) {
        DOMParser2.fromSchema(contentCheckSchema).parseSlice(elementFromString(content5), options2.parseOptions);
      } else {
        DOMParser2.fromSchema(contentCheckSchema).parse(elementFromString(content5), options2.parseOptions);
      }
      if (options2.errorOnInvalidContent && hasInvalidContent) {
        throw new Error("[tiptap error]: Invalid HTML content", {
          cause: new Error(`Invalid element found: ${invalidContent}`)
        });
      }
    }
    const parser = DOMParser2.fromSchema(schema);
    if (options2.slice) {
      return parser.parseSlice(elementFromString(content5), options2.parseOptions).content;
    }
    return parser.parse(elementFromString(content5), options2.parseOptions);
  }
  return createNodeFromContent("", schema, options2);
}
function selectionToInsertionEnd2(tr4, startLen, bias) {
  const last2 = tr4.steps.length - 1;
  if (last2 < startLen) {
    return;
  }
  const step = tr4.steps[last2];
  if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {
    return;
  }
  const map7 = tr4.mapping.maps[last2];
  let end = 0;
  map7.forEach((_from, _to, _newFrom, newTo) => {
    if (end === 0) {
      end = newTo;
    }
  });
  tr4.setSelection(Selection.near(tr4.doc.resolve(end), bias));
}
var isFragment = (nodeOrFragment) => {
  return !("type" in nodeOrFragment);
};
var insertContentAt = (position4, value, options2) => ({ tr: tr4, dispatch, editor }) => {
  var _a2;
  if (dispatch) {
    options2 = {
      parseOptions: editor.options.parseOptions,
      updateSelection: true,
      applyInputRules: false,
      applyPasteRules: false,
      ...options2
    };
    let content5;
    const emitContentError = (error2) => {
      editor.emit("contentError", {
        editor,
        error: error2,
        disableCollaboration: () => {
          if ("collaboration" in editor.storage && typeof editor.storage.collaboration === "object" && editor.storage.collaboration) {
            ;
            editor.storage.collaboration.isDisabled = true;
          }
        }
      });
    };
    const parseOptions = {
      preserveWhitespace: "full",
      ...options2.parseOptions
    };
    if (!options2.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) {
      try {
        createNodeFromContent(value, editor.schema, {
          parseOptions,
          errorOnInvalidContent: true
        });
      } catch (e2) {
        emitContentError(e2);
      }
    }
    try {
      content5 = createNodeFromContent(value, editor.schema, {
        parseOptions,
        errorOnInvalidContent: (_a2 = options2.errorOnInvalidContent) != null ? _a2 : editor.options.enableContentCheck
      });
    } catch (e2) {
      emitContentError(e2);
      return false;
    }
    let { from: from4, to: to2 } = typeof position4 === "number" ? { from: position4, to: position4 } : { from: position4.from, to: position4.to };
    let isOnlyTextContent = true;
    let isOnlyBlockContent = true;
    const nodes = isFragment(content5) ? content5 : [content5];
    nodes.forEach((node2) => {
      node2.check();
      isOnlyTextContent = isOnlyTextContent ? node2.isText && node2.marks.length === 0 : false;
      isOnlyBlockContent = isOnlyBlockContent ? node2.isBlock : false;
    });
    if (from4 === to2 && isOnlyBlockContent) {
      const { parent } = tr4.doc.resolve(from4);
      const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount;
      if (isEmptyTextBlock) {
        from4 -= 1;
        to2 += 1;
      }
    }
    let newContent;
    if (isOnlyTextContent) {
      if (Array.isArray(value)) {
        newContent = value.map((v8) => v8.text || "").join("");
      } else if (value instanceof Fragment) {
        let text10 = "";
        value.forEach((node2) => {
          if (node2.text) {
            text10 += node2.text;
          }
        });
        newContent = text10;
      } else if (typeof value === "object" && !!value && !!value.text) {
        newContent = value.text;
      } else {
        newContent = value;
      }
      tr4.insertText(newContent, from4, to2);
    } else {
      newContent = content5;
      const $from = tr4.doc.resolve(from4);
      const $fromNode = $from.node();
      const fromSelectionAtStart = $from.parentOffset === 0;
      const isTextSelection2 = $fromNode.isText || $fromNode.isTextblock;
      const hasContent2 = $fromNode.content.size > 0;
      if (fromSelectionAtStart && isTextSelection2 && hasContent2) {
        from4 = Math.max(0, from4 - 1);
      }
      tr4.replaceWith(from4, to2, newContent);
    }
    if (options2.updateSelection) {
      selectionToInsertionEnd2(tr4, tr4.steps.length - 1, -1);
    }
    if (options2.applyInputRules) {
      tr4.setMeta("applyInputRules", { from: from4, text: newContent });
    }
    if (options2.applyPasteRules) {
      tr4.setMeta("applyPasteRules", { from: from4, text: newContent });
    }
  }
  return true;
};
var joinUp2 = () => ({ state, dispatch }) => {
  return joinUp(state, dispatch);
};
var joinDown2 = () => ({ state, dispatch }) => {
  return joinDown(state, dispatch);
};
var joinBackward2 = () => ({ state, dispatch }) => {
  return joinBackward(state, dispatch);
};
var joinForward2 = () => ({ state, dispatch }) => {
  return joinForward(state, dispatch);
};
var joinItemBackward = () => ({ state, dispatch, tr: tr4 }) => {
  try {
    const point5 = joinPoint(state.doc, state.selection.$from.pos, -1);
    if (point5 === null || point5 === void 0) {
      return false;
    }
    tr4.join(point5, 2);
    if (dispatch) {
      dispatch(tr4);
    }
    return true;
  } catch {
    return false;
  }
};
var joinItemForward = () => ({ state, dispatch, tr: tr4 }) => {
  try {
    const point5 = joinPoint(state.doc, state.selection.$from.pos, 1);
    if (point5 === null || point5 === void 0) {
      return false;
    }
    tr4.join(point5, 2);
    if (dispatch) {
      dispatch(tr4);
    }
    return true;
  } catch {
    return false;
  }
};
var joinTextblockBackward2 = () => ({ state, dispatch }) => {
  return joinTextblockBackward(state, dispatch);
};
var joinTextblockForward2 = () => ({ state, dispatch }) => {
  return joinTextblockForward(state, dispatch);
};
function isMacOS() {
  return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
}
function normalizeKeyName2(name) {
  const parts = name.split(/-(?!$)/);
  let result = parts[parts.length - 1];
  if (result === "Space") {
    result = " ";
  }
  let alt;
  let ctrl;
  let shift5;
  let meta2;
  for (let i3 = 0; i3 < parts.length - 1; i3 += 1) {
    const mod = parts[i3];
    if (/^(cmd|meta|m)$/i.test(mod)) {
      meta2 = true;
    } else if (/^a(lt)?$/i.test(mod)) {
      alt = true;
    } else if (/^(c|ctrl|control)$/i.test(mod)) {
      ctrl = true;
    } else if (/^s(hift)?$/i.test(mod)) {
      shift5 = true;
    } else if (/^mod$/i.test(mod)) {
      if (isiOS() || isMacOS()) {
        meta2 = true;
      } else {
        ctrl = true;
      }
    } else {
      throw new Error(`Unrecognized modifier name: ${mod}`);
    }
  }
  if (alt) {
    result = `Alt-${result}`;
  }
  if (ctrl) {
    result = `Ctrl-${result}`;
  }
  if (meta2) {
    result = `Meta-${result}`;
  }
  if (shift5) {
    result = `Shift-${result}`;
  }
  return result;
}
var keyboardShortcut = (name) => ({ editor, view, tr: tr4, dispatch }) => {
  const keys5 = normalizeKeyName2(name).split(/-(?!$)/);
  const key2 = keys5.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item));
  const event = new KeyboardEvent("keydown", {
    key: key2 === "Space" ? " " : key2,
    altKey: keys5.includes("Alt"),
    ctrlKey: keys5.includes("Ctrl"),
    metaKey: keys5.includes("Meta"),
    shiftKey: keys5.includes("Shift"),
    bubbles: true,
    cancelable: true
  });
  const capturedTransaction = editor.captureTransaction(() => {
    view.someProp("handleKeyDown", (f6) => f6(view, event));
  });
  capturedTransaction == null ? void 0 : capturedTransaction.steps.forEach((step) => {
    const newStep = step.map(tr4.mapping);
    if (newStep && dispatch) {
      tr4.maybeStep(newStep);
    }
  });
  return true;
};
function isNodeActive(state, typeOrName, attributes = {}) {
  const { from: from4, to: to2, empty: empty4 } = state.selection;
  const type = typeOrName ? getNodeType(typeOrName, state.schema) : null;
  const nodeRanges = [];
  state.doc.nodesBetween(from4, to2, (node2, pos) => {
    if (node2.isText) {
      return;
    }
    const relativeFrom = Math.max(from4, pos);
    const relativeTo = Math.min(to2, pos + node2.nodeSize);
    nodeRanges.push({
      node: node2,
      from: relativeFrom,
      to: relativeTo
    });
  });
  const selectionRange = to2 - from4;
  const matchedNodeRanges = nodeRanges.filter((nodeRange) => {
    if (!type) {
      return true;
    }
    return type.name === nodeRange.node.type.name;
  }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }));
  if (empty4) {
    return !!matchedNodeRanges.length;
  }
  const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0);
  return range >= selectionRange;
}
var lift3 = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  const isActive2 = isNodeActive(state, type, attributes);
  if (!isActive2) {
    return false;
  }
  return lift2(state, dispatch);
};
var liftEmptyBlock2 = () => ({ state, dispatch }) => {
  return liftEmptyBlock(state, dispatch);
};
var liftListItem2 = (typeOrName) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return liftListItem(type)(state, dispatch);
};
var newlineInCode2 = () => ({ state, dispatch }) => {
  return newlineInCode(state, dispatch);
};
function getSchemaTypeNameByName(name, schema) {
  if (schema.nodes[name]) {
    return "node";
  }
  if (schema.marks[name]) {
    return "mark";
  }
  return null;
}
function deleteProps(obj, propOrProps) {
  const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps;
  return Object.keys(obj).reduce((newObj, prop) => {
    if (!props.includes(prop)) {
      newObj[prop] = obj[prop];
    }
    return newObj;
  }, {});
}
var resetAttributes = (typeOrName, attributes) => ({ tr: tr4, state, dispatch }) => {
  let nodeType = null;
  let markType = null;
  const schemaType = getSchemaTypeNameByName(
    typeof typeOrName === "string" ? typeOrName : typeOrName.name,
    state.schema
  );
  if (!schemaType) {
    return false;
  }
  if (schemaType === "node") {
    nodeType = getNodeType(typeOrName, state.schema);
  }
  if (schemaType === "mark") {
    markType = getMarkType(typeOrName, state.schema);
  }
  let canReset = false;
  tr4.selection.ranges.forEach((range) => {
    state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node2, pos) => {
      if (nodeType && nodeType === node2.type) {
        canReset = true;
        if (dispatch) {
          tr4.setNodeMarkup(pos, void 0, deleteProps(node2.attrs, attributes));
        }
      }
      if (markType && node2.marks.length) {
        node2.marks.forEach((mark2) => {
          if (markType === mark2.type) {
            canReset = true;
            if (dispatch) {
              tr4.addMark(pos, pos + node2.nodeSize, markType.create(deleteProps(mark2.attrs, attributes)));
            }
          }
        });
      }
    });
  });
  return canReset;
};
var scrollIntoView = () => ({ tr: tr4, dispatch }) => {
  if (dispatch) {
    tr4.scrollIntoView();
  }
  return true;
};
var selectAll2 = () => ({ tr: tr4, dispatch }) => {
  if (dispatch) {
    const selection = new AllSelection(tr4.doc);
    tr4.setSelection(selection);
  }
  return true;
};
var selectNodeBackward2 = () => ({ state, dispatch }) => {
  return selectNodeBackward(state, dispatch);
};
var selectNodeForward2 = () => ({ state, dispatch }) => {
  return selectNodeForward(state, dispatch);
};
var selectParentNode2 = () => ({ state, dispatch }) => {
  return selectParentNode(state, dispatch);
};
var selectTextblockEnd2 = () => ({ state, dispatch }) => {
  return selectTextblockEnd(state, dispatch);
};
var selectTextblockStart2 = () => ({ state, dispatch }) => {
  return selectTextblockStart(state, dispatch);
};
function createDocument(content5, schema, parseOptions = {}, options2 = {}) {
  return createNodeFromContent(content5, schema, {
    slice: false,
    parseOptions,
    errorOnInvalidContent: options2.errorOnInvalidContent
  });
}
var setContent = (content5, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr: tr4, dispatch, commands }) => {
  const { doc: doc4 } = tr4;
  if (parseOptions.preserveWhitespace !== "full") {
    const document22 = createDocument(content5, editor.schema, parseOptions, {
      errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck
    });
    if (dispatch) {
      tr4.replaceWith(0, doc4.content.size, document22).setMeta("preventUpdate", !emitUpdate);
    }
    return true;
  }
  if (dispatch) {
    tr4.setMeta("preventUpdate", !emitUpdate);
  }
  return commands.insertContentAt({ from: 0, to: doc4.content.size }, content5, {
    parseOptions,
    errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck
  });
};
function getMarkAttributes(state, typeOrName) {
  const type = getMarkType(typeOrName, state.schema);
  const { from: from4, to: to2, empty: empty4 } = state.selection;
  const marks = [];
  if (empty4) {
    if (state.storedMarks) {
      marks.push(...state.storedMarks);
    }
    marks.push(...state.selection.$head.marks());
  } else {
    state.doc.nodesBetween(from4, to2, (node2) => {
      marks.push(...node2.marks);
    });
  }
  const mark2 = marks.find((markItem) => markItem.type.name === type.name);
  if (!mark2) {
    return {};
  }
  return { ...mark2.attrs };
}
function combineTransactionSteps(oldDoc, transactions) {
  const transform2 = new Transform(oldDoc);
  transactions.forEach((transaction) => {
    transaction.steps.forEach((step) => {
      transform2.step(step);
    });
  });
  return transform2;
}
function defaultBlockAt2(match2) {
  for (let i3 = 0; i3 < match2.edgeCount; i3 += 1) {
    const { type } = match2.edge(i3);
    if (type.isTextblock && !type.hasRequiredAttrs()) {
      return type;
    }
  }
  return null;
}
function findChildren(node2, predicate) {
  const nodesWithPos = [];
  node2.descendants((child, pos) => {
    if (predicate(child)) {
      nodesWithPos.push({
        node: child,
        pos
      });
    }
  });
  return nodesWithPos;
}
function findChildrenInRange(node2, range, predicate) {
  const nodesWithPos = [];
  node2.nodesBetween(range.from, range.to, (child, pos) => {
    if (predicate(child)) {
      nodesWithPos.push({
        node: child,
        pos
      });
    }
  });
  return nodesWithPos;
}
function findParentNodeClosestToPos($pos, predicate) {
  for (let i3 = $pos.depth; i3 > 0; i3 -= 1) {
    const node2 = $pos.node(i3);
    if (predicate(node2)) {
      return {
        pos: i3 > 0 ? $pos.before(i3) : 0,
        start: $pos.start(i3),
        depth: i3,
        node: node2
      };
    }
  }
}
function findParentNode(predicate) {
  return (selection) => findParentNodeClosestToPos(selection.$from, predicate);
}
function getExtensionField(extension2, field, context) {
  if (extension2.config[field] === void 0 && extension2.parent) {
    return getExtensionField(extension2.parent, field, context);
  }
  if (typeof extension2.config[field] === "function") {
    const value = extension2.config[field].bind({
      ...context,
      parent: extension2.parent ? getExtensionField(extension2.parent, field, context) : null
    });
    return value;
  }
  return extension2.config[field];
}
function flattenExtensions(extensions) {
  return extensions.map((extension2) => {
    const context = {
      name: extension2.name,
      options: extension2.options,
      storage: extension2.storage
    };
    const addExtensions = getExtensionField(extension2, "addExtensions", context);
    if (addExtensions) {
      return [extension2, ...flattenExtensions(addExtensions())];
    }
    return extension2;
  }).flat(10);
}
function getHTMLFromFragment(fragment, schema) {
  const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment);
  const temporaryDocument = document.implementation.createHTMLDocument();
  const container = temporaryDocument.createElement("div");
  container.appendChild(documentFragment);
  return container.innerHTML;
}
function isFunction(value) {
  return typeof value === "function";
}
function callOrReturn(value, context = void 0, ...props) {
  if (isFunction(value)) {
    if (context) {
      return value.bind(context)(...props);
    }
    return value(...props);
  }
  return value;
}
function isEmptyObject(value = {}) {
  return Object.keys(value).length === 0 && value.constructor === Object;
}
function splitExtensions(extensions) {
  const baseExtensions = extensions.filter((extension2) => extension2.type === "extension");
  const nodeExtensions = extensions.filter((extension2) => extension2.type === "node");
  const markExtensions = extensions.filter((extension2) => extension2.type === "mark");
  return {
    baseExtensions,
    nodeExtensions,
    markExtensions
  };
}
function getAttributesFromExtensions(extensions) {
  const extensionAttributes = [];
  const { nodeExtensions, markExtensions } = splitExtensions(extensions);
  const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions];
  const defaultAttribute = {
    default: null,
    validate: void 0,
    rendered: true,
    renderHTML: null,
    parseHTML: null,
    keepOnSplit: true,
    isRequired: false
  };
  extensions.forEach((extension2) => {
    const context = {
      name: extension2.name,
      options: extension2.options,
      storage: extension2.storage,
      extensions: nodeAndMarkExtensions
    };
    const addGlobalAttributes = getExtensionField(
      extension2,
      "addGlobalAttributes",
      context
    );
    if (!addGlobalAttributes) {
      return;
    }
    const globalAttributes = addGlobalAttributes();
    globalAttributes.forEach((globalAttribute) => {
      globalAttribute.types.forEach((type) => {
        Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => {
          extensionAttributes.push({
            type,
            name,
            attribute: {
              ...defaultAttribute,
              ...attribute
            }
          });
        });
      });
    });
  });
  nodeAndMarkExtensions.forEach((extension2) => {
    const context = {
      name: extension2.name,
      options: extension2.options,
      storage: extension2.storage
    };
    const addAttributes = getExtensionField(
      extension2,
      "addAttributes",
      context
    );
    if (!addAttributes) {
      return;
    }
    const attributes = addAttributes();
    Object.entries(attributes).forEach(([name, attribute]) => {
      const mergedAttr = {
        ...defaultAttribute,
        ...attribute
      };
      if (typeof (mergedAttr == null ? void 0 : mergedAttr.default) === "function") {
        mergedAttr.default = mergedAttr.default();
      }
      if ((mergedAttr == null ? void 0 : mergedAttr.isRequired) && (mergedAttr == null ? void 0 : mergedAttr.default) === void 0) {
        delete mergedAttr.default;
      }
      extensionAttributes.push({
        type: extension2.name,
        name,
        attribute: mergedAttr
      });
    });
  });
  return extensionAttributes;
}
function mergeAttributes(...objects) {
  return objects.filter((item) => !!item).reduce((items, item) => {
    const mergedAttributes = { ...items };
    Object.entries(item).forEach(([key2, value]) => {
      const exists = mergedAttributes[key2];
      if (!exists) {
        mergedAttributes[key2] = value;
        return;
      }
      if (key2 === "class") {
        const valueClasses = value ? String(value).split(" ") : [];
        const existingClasses = mergedAttributes[key2] ? mergedAttributes[key2].split(" ") : [];
        const insertClasses = valueClasses.filter((valueClass) => !existingClasses.includes(valueClass));
        mergedAttributes[key2] = [...existingClasses, ...insertClasses].join(" ");
      } else if (key2 === "style") {
        const newStyles = value ? value.split(";").map((style22) => style22.trim()).filter(Boolean) : [];
        const existingStyles = mergedAttributes[key2] ? mergedAttributes[key2].split(";").map((style22) => style22.trim()).filter(Boolean) : [];
        const styleMap = /* @__PURE__ */ new Map();
        existingStyles.forEach((style22) => {
          const [property, val] = style22.split(":").map((part) => part.trim());
          styleMap.set(property, val);
        });
        newStyles.forEach((style22) => {
          const [property, val] = style22.split(":").map((part) => part.trim());
          styleMap.set(property, val);
        });
        mergedAttributes[key2] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; ");
      } else {
        mergedAttributes[key2] = value;
      }
    });
    return mergedAttributes;
  }, {});
}
function getRenderedAttributes(nodeOrMark, extensionAttributes) {
  return extensionAttributes.filter((attribute) => attribute.type === nodeOrMark.type.name).filter((item) => item.attribute.rendered).map((item) => {
    if (!item.attribute.renderHTML) {
      return {
        [item.name]: nodeOrMark.attrs[item.name]
      };
    }
    return item.attribute.renderHTML(nodeOrMark.attrs) || {};
  }).reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {});
}
function fromString(value) {
  if (typeof value !== "string") {
    return value;
  }
  if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) {
    return Number(value);
  }
  if (value === "true") {
    return true;
  }
  if (value === "false") {
    return false;
  }
  return value;
}
function injectExtensionAttributesToParseRule(parseRule, extensionAttributes) {
  if ("style" in parseRule) {
    return parseRule;
  }
  return {
    ...parseRule,
    getAttrs: (node2) => {
      const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node2) : parseRule.attrs;
      if (oldAttributes === false) {
        return false;
      }
      const newAttributes = extensionAttributes.reduce((items, item) => {
        const value = item.attribute.parseHTML ? item.attribute.parseHTML(node2) : fromString(node2.getAttribute(item.name));
        if (value === null || value === void 0) {
          return items;
        }
        return {
          ...items,
          [item.name]: value
        };
      }, {});
      return { ...oldAttributes, ...newAttributes };
    }
  };
}
function cleanUpSchemaItem(data) {
  return Object.fromEntries(
    // @ts-ignore
    Object.entries(data).filter(([key2, value]) => {
      if (key2 === "attrs" && isEmptyObject(value)) {
        return false;
      }
      return value !== null && value !== void 0;
    })
  );
}
function buildAttributeSpec(extensionAttribute) {
  var _a2, _b;
  const spec = {};
  if (!((_a2 = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _a2.isRequired) && "default" in ((extensionAttribute == null ? void 0 : extensionAttribute.attribute) || {})) {
    spec.default = extensionAttribute.attribute.default;
  }
  if (((_b = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _b.validate) !== void 0) {
    spec.validate = extensionAttribute.attribute.validate;
  }
  return [extensionAttribute.name, spec];
}
function getSchemaByResolvedExtensions(extensions, editor) {
  var _a2;
  const allAttributes = getAttributesFromExtensions(extensions);
  const { nodeExtensions, markExtensions } = splitExtensions(extensions);
  const topNode = (_a2 = nodeExtensions.find((extension2) => getExtensionField(extension2, "topNode"))) == null ? void 0 : _a2.name;
  const nodes = Object.fromEntries(
    nodeExtensions.map((extension2) => {
      const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension2.name);
      const context = {
        name: extension2.name,
        options: extension2.options,
        storage: extension2.storage,
        editor
      };
      const extraNodeFields = extensions.reduce((fields, e2) => {
        const extendNodeSchema = getExtensionField(e2, "extendNodeSchema", context);
        return {
          ...fields,
          ...extendNodeSchema ? extendNodeSchema(extension2) : {}
        };
      }, {});
      const schema = cleanUpSchemaItem({
        ...extraNodeFields,
        content: callOrReturn(getExtensionField(extension2, "content", context)),
        marks: callOrReturn(getExtensionField(extension2, "marks", context)),
        group: callOrReturn(getExtensionField(extension2, "group", context)),
        inline: callOrReturn(getExtensionField(extension2, "inline", context)),
        atom: callOrReturn(getExtensionField(extension2, "atom", context)),
        selectable: callOrReturn(getExtensionField(extension2, "selectable", context)),
        draggable: callOrReturn(getExtensionField(extension2, "draggable", context)),
        code: callOrReturn(getExtensionField(extension2, "code", context)),
        whitespace: callOrReturn(getExtensionField(extension2, "whitespace", context)),
        linebreakReplacement: callOrReturn(
          getExtensionField(extension2, "linebreakReplacement", context)
        ),
        defining: callOrReturn(getExtensionField(extension2, "defining", context)),
        isolating: callOrReturn(getExtensionField(extension2, "isolating", context)),
        attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec))
      });
      const parseHTML = callOrReturn(getExtensionField(extension2, "parseHTML", context));
      if (parseHTML) {
        schema.parseDOM = parseHTML.map(
          (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes)
        );
      }
      const renderHTML = getExtensionField(extension2, "renderHTML", context);
      if (renderHTML) {
        schema.toDOM = (node2) => renderHTML({
          node: node2,
          HTMLAttributes: getRenderedAttributes(node2, extensionAttributes)
        });
      }
      const renderText = getExtensionField(extension2, "renderText", context);
      if (renderText) {
        schema.toText = renderText;
      }
      return [extension2.name, schema];
    })
  );
  const marks = Object.fromEntries(
    markExtensions.map((extension2) => {
      const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension2.name);
      const context = {
        name: extension2.name,
        options: extension2.options,
        storage: extension2.storage,
        editor
      };
      const extraMarkFields = extensions.reduce((fields, e2) => {
        const extendMarkSchema = getExtensionField(e2, "extendMarkSchema", context);
        return {
          ...fields,
          ...extendMarkSchema ? extendMarkSchema(extension2) : {}
        };
      }, {});
      const schema = cleanUpSchemaItem({
        ...extraMarkFields,
        inclusive: callOrReturn(getExtensionField(extension2, "inclusive", context)),
        excludes: callOrReturn(getExtensionField(extension2, "excludes", context)),
        group: callOrReturn(getExtensionField(extension2, "group", context)),
        spanning: callOrReturn(getExtensionField(extension2, "spanning", context)),
        code: callOrReturn(getExtensionField(extension2, "code", context)),
        attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec))
      });
      const parseHTML = callOrReturn(getExtensionField(extension2, "parseHTML", context));
      if (parseHTML) {
        schema.parseDOM = parseHTML.map(
          (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes)
        );
      }
      const renderHTML = getExtensionField(extension2, "renderHTML", context);
      if (renderHTML) {
        schema.toDOM = (mark2) => renderHTML({
          mark: mark2,
          HTMLAttributes: getRenderedAttributes(mark2, extensionAttributes)
        });
      }
      return [extension2.name, schema];
    })
  );
  return new Schema({
    topNode,
    nodes,
    marks
  });
}
function findDuplicates(items) {
  const filtered = items.filter((el2, index4) => items.indexOf(el2) !== index4);
  return Array.from(new Set(filtered));
}
function sortExtensions(extensions) {
  const defaultPriority = 100;
  return extensions.sort((a3, b4) => {
    const priorityA = getExtensionField(a3, "priority") || defaultPriority;
    const priorityB = getExtensionField(b4, "priority") || defaultPriority;
    if (priorityA > priorityB) {
      return -1;
    }
    if (priorityA < priorityB) {
      return 1;
    }
    return 0;
  });
}
function resolveExtensions(extensions) {
  const resolvedExtensions = sortExtensions(flattenExtensions(extensions));
  const duplicatedNames = findDuplicates(resolvedExtensions.map((extension2) => extension2.name));
  if (duplicatedNames.length) {
    console.warn(
      `[tiptap warn]: Duplicate extension names found: [${duplicatedNames.map((item) => `'${item}'`).join(", ")}]. This can lead to issues.`
    );
  }
  return resolvedExtensions;
}
function getSchema(extensions, editor) {
  const resolvedExtensions = resolveExtensions(extensions);
  return getSchemaByResolvedExtensions(resolvedExtensions, editor);
}
function getTextBetween(startNode, range, options2) {
  const { from: from4, to: to2 } = range;
  const { blockSeparator = "\n\n", textSerializers = {} } = options2 || {};
  let text10 = "";
  startNode.nodesBetween(from4, to2, (node2, pos, parent, index4) => {
    var _a2;
    if (node2.isBlock && pos > from4) {
      text10 += blockSeparator;
    }
    const textSerializer = textSerializers == null ? void 0 : textSerializers[node2.type.name];
    if (textSerializer) {
      if (parent) {
        text10 += textSerializer({
          node: node2,
          pos,
          parent,
          index: index4,
          range
        });
      }
      return false;
    }
    if (node2.isText) {
      text10 += (_a2 = node2 == null ? void 0 : node2.text) == null ? void 0 : _a2.slice(Math.max(from4, pos) - pos, to2 - pos);
    }
  });
  return text10;
}
function getText2(node2, options2) {
  const range = {
    from: 0,
    to: node2.content.size
  };
  return getTextBetween(node2, range, options2);
}
function getTextSerializersFromSchema(schema) {
  return Object.fromEntries(
    Object.entries(schema.nodes).filter(([, node2]) => node2.spec.toText).map(([name, node2]) => [name, node2.spec.toText])
  );
}
function getNodeAttributes(state, typeOrName) {
  const type = getNodeType(typeOrName, state.schema);
  const { from: from4, to: to2 } = state.selection;
  const nodes = [];
  state.doc.nodesBetween(from4, to2, (node22) => {
    nodes.push(node22);
  });
  const node2 = nodes.reverse().find((nodeItem) => nodeItem.type.name === type.name);
  if (!node2) {
    return {};
  }
  return { ...node2.attrs };
}
function getAttributes(state, typeOrName) {
  const schemaType = getSchemaTypeNameByName(
    typeof typeOrName === "string" ? typeOrName : typeOrName.name,
    state.schema
  );
  if (schemaType === "node") {
    return getNodeAttributes(state, typeOrName);
  }
  if (schemaType === "mark") {
    return getMarkAttributes(state, typeOrName);
  }
  return {};
}
function removeDuplicates(array, by = JSON.stringify) {
  const seen = {};
  return array.filter((item) => {
    const key2 = by(item);
    return Object.prototype.hasOwnProperty.call(seen, key2) ? false : seen[key2] = true;
  });
}
function simplifyChangedRanges(changes) {
  const uniqueChanges = removeDuplicates(changes);
  return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index4) => {
    const rest = uniqueChanges.filter((_2, i3) => i3 !== index4);
    return !rest.some((otherChange) => {
      return change.oldRange.from >= otherChange.oldRange.from && change.oldRange.to <= otherChange.oldRange.to && change.newRange.from >= otherChange.newRange.from && change.newRange.to <= otherChange.newRange.to;
    });
  });
}
function getChangedRanges(transform2) {
  const { mapping, steps } = transform2;
  const changes = [];
  mapping.maps.forEach((stepMap, index4) => {
    const ranges = [];
    if (!stepMap.ranges.length) {
      const { from: from4, to: to2 } = steps[index4];
      if (from4 === void 0 || to2 === void 0) {
        return;
      }
      ranges.push({ from: from4, to: to2 });
    } else {
      stepMap.forEach((from4, to2) => {
        ranges.push({ from: from4, to: to2 });
      });
    }
    ranges.forEach(({ from: from4, to: to2 }) => {
      const newStart = mapping.slice(index4).map(from4, -1);
      const newEnd = mapping.slice(index4).map(to2);
      const oldStart = mapping.invert().map(newStart, -1);
      const oldEnd = mapping.invert().map(newEnd);
      changes.push({
        oldRange: {
          from: oldStart,
          to: oldEnd
        },
        newRange: {
          from: newStart,
          to: newEnd
        }
      });
    });
  });
  return simplifyChangedRanges(changes);
}
function getMarksBetween(from4, to2, doc4) {
  const marks = [];
  if (from4 === to2) {
    doc4.resolve(from4).marks().forEach((mark2) => {
      const $pos = doc4.resolve(from4);
      const range = getMarkRange($pos, mark2.type);
      if (!range) {
        return;
      }
      marks.push({
        mark: mark2,
        ...range
      });
    });
  } else {
    doc4.nodesBetween(from4, to2, (node2, pos) => {
      if (!node2 || (node2 == null ? void 0 : node2.nodeSize) === void 0) {
        return;
      }
      marks.push(
        ...node2.marks.map((mark2) => ({
          from: pos,
          to: pos + node2.nodeSize,
          mark: mark2
        }))
      );
    });
  }
  return marks;
}
function getSchemaTypeByName(name, schema) {
  return schema.nodes[name] || schema.marks[name] || null;
}
function getSplittedAttributes(extensionAttributes, typeName, attributes) {
  return Object.fromEntries(
    Object.entries(attributes).filter(([name]) => {
      const extensionAttribute = extensionAttributes.find((item) => {
        return item.type === typeName && item.name === name;
      });
      if (!extensionAttribute) {
        return false;
      }
      return extensionAttribute.attribute.keepOnSplit;
    })
  );
}
var getTextContentFromNodes = ($from, maxMatch = 500) => {
  let textBefore = "";
  const sliceEndPos = $from.parentOffset;
  $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node2, pos, parent, index4) => {
    var _a2, _b;
    const chunk = ((_b = (_a2 = node2.type.spec).toText) == null ? void 0 : _b.call(_a2, {
      node: node2,
      pos,
      parent,
      index: index4
    })) || node2.textContent || "%leaf%";
    textBefore += node2.isAtom && !node2.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos));
  });
  return textBefore;
};
function isMarkActive(state, typeOrName, attributes = {}) {
  const { empty: empty4, ranges } = state.selection;
  const type = typeOrName ? getMarkType(typeOrName, state.schema) : null;
  if (empty4) {
    return !!(state.storedMarks || state.selection.$from.marks()).filter((mark2) => {
      if (!type) {
        return true;
      }
      return type.name === mark2.type.name;
    }).find((mark2) => objectIncludes(mark2.attrs, attributes, { strict: false }));
  }
  let selectionRange = 0;
  const markRanges = [];
  ranges.forEach(({ $from, $to }) => {
    const from4 = $from.pos;
    const to2 = $to.pos;
    state.doc.nodesBetween(from4, to2, (node2, pos) => {
      if (!node2.isText && !node2.marks.length) {
        return;
      }
      const relativeFrom = Math.max(from4, pos);
      const relativeTo = Math.min(to2, pos + node2.nodeSize);
      const range2 = relativeTo - relativeFrom;
      selectionRange += range2;
      markRanges.push(
        ...node2.marks.map((mark2) => ({
          mark: mark2,
          from: relativeFrom,
          to: relativeTo
        }))
      );
    });
  });
  if (selectionRange === 0) {
    return false;
  }
  const matchedRange = markRanges.filter((markRange) => {
    if (!type) {
      return true;
    }
    return type.name === markRange.mark.type.name;
  }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
  const excludedRange = markRanges.filter((markRange) => {
    if (!type) {
      return true;
    }
    return markRange.mark.type !== type && markRange.mark.type.excludes(type);
  }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
  const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange;
  return range >= selectionRange;
}
function isActive(state, name, attributes = {}) {
  if (!name) {
    return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes);
  }
  const schemaType = getSchemaTypeNameByName(name, state.schema);
  if (schemaType === "node") {
    return isNodeActive(state, name, attributes);
  }
  if (schemaType === "mark") {
    return isMarkActive(state, name, attributes);
  }
  return false;
}
function isExtensionRulesEnabled(extension2, enabled) {
  if (Array.isArray(enabled)) {
    return enabled.some((enabledExtension) => {
      const name = typeof enabledExtension === "string" ? enabledExtension : enabledExtension.name;
      return name === extension2.name;
    });
  }
  return enabled;
}
function isList(name, extensions) {
  const { nodeExtensions } = splitExtensions(extensions);
  const extension2 = nodeExtensions.find((item) => item.name === name);
  if (!extension2) {
    return false;
  }
  const context = {
    name: extension2.name,
    options: extension2.options,
    storage: extension2.storage
  };
  const group = callOrReturn(getExtensionField(extension2, "group", context));
  if (typeof group !== "string") {
    return false;
  }
  return group.split(" ").includes("list");
}
function isNodeEmpty(node2, {
  checkChildren = true,
  ignoreWhitespace = false
} = {}) {
  var _a2;
  if (ignoreWhitespace) {
    if (node2.type.name === "hardBreak") {
      return true;
    }
    if (node2.isText) {
      return /^\s*$/m.test((_a2 = node2.text) != null ? _a2 : "");
    }
  }
  if (node2.isText) {
    return !node2.text;
  }
  if (node2.isAtom || node2.isLeaf) {
    return false;
  }
  if (node2.content.childCount === 0) {
    return true;
  }
  if (checkChildren) {
    let isContentEmpty = true;
    node2.content.forEach((childNode) => {
      if (isContentEmpty === false) {
        return;
      }
      if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {
        isContentEmpty = false;
      }
    });
    return isContentEmpty;
  }
  return false;
}
function isNodeSelection(value) {
  return value instanceof NodeSelection;
}
var MappablePosition = class _MappablePosition {
  constructor(position4) {
    this.position = position4;
  }
  /**
   * Creates a MappablePosition from a JSON object.
   */
  static fromJSON(json) {
    return new _MappablePosition(json.position);
  }
  /**
   * Converts the MappablePosition to a JSON object.
   */
  toJSON() {
    return {
      position: this.position
    };
  }
};
function getUpdatedPosition(position4, transaction) {
  const mapResult = transaction.mapping.mapResult(position4.position);
  return {
    position: new MappablePosition(mapResult.pos),
    mapResult
  };
}
function createMappablePosition(position4) {
  return new MappablePosition(position4);
}
function posToDOMRect(view, from4, to2) {
  const minPos = 0;
  const maxPos = view.state.doc.content.size;
  const resolvedFrom = minMax(from4, minPos, maxPos);
  const resolvedEnd = minMax(to2, minPos, maxPos);
  const start = view.coordsAtPos(resolvedFrom);
  const end = view.coordsAtPos(resolvedEnd, -1);
  const top = Math.min(start.top, end.top);
  const bottom = Math.max(start.bottom, end.bottom);
  const left = Math.min(start.left, end.left);
  const right = Math.max(start.right, end.right);
  const width = right - left;
  const height = bottom - top;
  const x5 = left;
  const y3 = top;
  const data = {
    top,
    bottom,
    left,
    right,
    width,
    height,
    x: x5,
    y: y3
  };
  return {
    ...data,
    toJSON: () => data
  };
}
function canSetMark(state, tr4, newMarkType) {
  var _a2;
  const { selection } = tr4;
  let cursor = null;
  if (isTextSelection(selection)) {
    cursor = selection.$cursor;
  }
  if (cursor) {
    const currentMarks = (_a2 = state.storedMarks) != null ? _a2 : cursor.marks();
    const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType);
    return parentAllowsMarkType && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark2) => mark2.type.excludes(newMarkType)));
  }
  const { ranges } = selection;
  return ranges.some(({ $from, $to }) => {
    let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false;
    state.doc.nodesBetween($from.pos, $to.pos, (node2, _pos, parent) => {
      if (someNodeSupportsMark) {
        return false;
      }
      if (node2.isInline) {
        const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType);
        const currentMarksAllowMarkType = !!newMarkType.isInSet(node2.marks) || !node2.marks.some((otherMark) => otherMark.type.excludes(newMarkType));
        someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType;
      }
      return !someNodeSupportsMark;
    });
    return someNodeSupportsMark;
  });
}
var setMark = (typeOrName, attributes = {}) => ({ tr: tr4, state, dispatch }) => {
  const { selection } = tr4;
  const { empty: empty4, ranges } = selection;
  const type = getMarkType(typeOrName, state.schema);
  if (dispatch) {
    if (empty4) {
      const oldAttributes = getMarkAttributes(state, type);
      tr4.addStoredMark(
        type.create({
          ...oldAttributes,
          ...attributes
        })
      );
    } else {
      ranges.forEach((range) => {
        const from4 = range.$from.pos;
        const to2 = range.$to.pos;
        state.doc.nodesBetween(from4, to2, (node2, pos) => {
          const trimmedFrom = Math.max(pos, from4);
          const trimmedTo = Math.min(pos + node2.nodeSize, to2);
          const someHasMark = node2.marks.find((mark2) => mark2.type === type);
          if (someHasMark) {
            node2.marks.forEach((mark2) => {
              if (type === mark2.type) {
                tr4.addMark(
                  trimmedFrom,
                  trimmedTo,
                  type.create({
                    ...mark2.attrs,
                    ...attributes
                  })
                );
              }
            });
          } else {
            tr4.addMark(trimmedFrom, trimmedTo, type.create(attributes));
          }
        });
      });
    }
  }
  return canSetMark(state, tr4, type);
};
var setMeta2 = (key2, value) => ({ tr: tr4 }) => {
  tr4.setMeta(key2, value);
  return true;
};
var setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {
  const type = getNodeType(typeOrName, state.schema);
  let attributesToCopy;
  if (state.selection.$anchor.sameParent(state.selection.$head)) {
    attributesToCopy = state.selection.$anchor.parent.attrs;
  }
  if (!type.isTextblock) {
    console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.');
    return false;
  }
  return chain().command(({ commands }) => {
    const canSetBlock = setBlockType2(type, { ...attributesToCopy, ...attributes })(state);
    if (canSetBlock) {
      return true;
    }
    return commands.clearNodes();
  }).command(({ state: updatedState }) => {
    return setBlockType2(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch);
  }).run();
};
var setNodeSelection = (position4) => ({ tr: tr4, dispatch }) => {
  if (dispatch) {
    const { doc: doc4 } = tr4;
    const from4 = minMax(position4, 0, doc4.content.size);
    const selection = NodeSelection.create(doc4, from4);
    tr4.setSelection(selection);
  }
  return true;
};
var setTextDirection = (direction, position4) => ({ tr: tr4, state, dispatch }) => {
  const { selection } = state;
  let from4;
  let to2;
  if (typeof position4 === "number") {
    from4 = position4;
    to2 = position4;
  } else if (position4 && "from" in position4 && "to" in position4) {
    from4 = position4.from;
    to2 = position4.to;
  } else {
    from4 = selection.from;
    to2 = selection.to;
  }
  if (dispatch) {
    tr4.doc.nodesBetween(from4, to2, (node2, pos) => {
      if (node2.isText) {
        return;
      }
      tr4.setNodeMarkup(pos, void 0, {
        ...node2.attrs,
        dir: direction
      });
    });
  }
  return true;
};
var setTextSelection = (position4) => ({ tr: tr4, dispatch }) => {
  if (dispatch) {
    const { doc: doc4 } = tr4;
    const { from: from4, to: to2 } = typeof position4 === "number" ? { from: position4, to: position4 } : position4;
    const minPos = TextSelection.atStart(doc4).from;
    const maxPos = TextSelection.atEnd(doc4).to;
    const resolvedFrom = minMax(from4, minPos, maxPos);
    const resolvedEnd = minMax(to2, minPos, maxPos);
    const selection = TextSelection.create(doc4, resolvedFrom, resolvedEnd);
    tr4.setSelection(selection);
  }
  return true;
};
var sinkListItem2 = (typeOrName) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return sinkListItem(type)(state, dispatch);
};
function ensureMarks(state, splittableMarks) {
  const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();
  if (marks) {
    const filteredMarks = marks.filter((mark2) => splittableMarks == null ? void 0 : splittableMarks.includes(mark2.type.name));
    state.tr.ensureMarks(filteredMarks);
  }
}
var splitBlock2 = ({ keepMarks = true } = {}) => ({ tr: tr4, state, dispatch, editor }) => {
  const { selection, doc: doc4 } = tr4;
  const { $from, $to } = selection;
  const extensionAttributes = editor.extensionManager.attributes;
  const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
  if (selection instanceof NodeSelection && selection.node.isBlock) {
    if (!$from.parentOffset || !canSplit(doc4, $from.pos)) {
      return false;
    }
    if (dispatch) {
      if (keepMarks) {
        ensureMarks(state, editor.extensionManager.splittableMarks);
      }
      tr4.split($from.pos).scrollIntoView();
    }
    return true;
  }
  if (!$from.parent.isBlock) {
    return false;
  }
  const atEnd = $to.parentOffset === $to.parent.content.size;
  const deflt = $from.depth === 0 ? void 0 : defaultBlockAt2($from.node(-1).contentMatchAt($from.indexAfter(-1)));
  let types2 = atEnd && deflt ? [
    {
      type: deflt,
      attrs: newAttributes
    }
  ] : void 0;
  let can = canSplit(tr4.doc, tr4.mapping.map($from.pos), 1, types2);
  if (!types2 && !can && canSplit(tr4.doc, tr4.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) {
    can = true;
    types2 = deflt ? [
      {
        type: deflt,
        attrs: newAttributes
      }
    ] : void 0;
  }
  if (dispatch) {
    if (can) {
      if (selection instanceof TextSelection) {
        tr4.deleteSelection();
      }
      tr4.split(tr4.mapping.map($from.pos), 1, types2);
      if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {
        const first2 = tr4.mapping.map($from.before());
        const $first = tr4.doc.resolve(first2);
        if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {
          tr4.setNodeMarkup(tr4.mapping.map($from.before()), deflt);
        }
      }
    }
    if (keepMarks) {
      ensureMarks(state, editor.extensionManager.splittableMarks);
    }
    tr4.scrollIntoView();
  }
  return can;
};
var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr: tr4, state, dispatch, editor }) => {
  var _a2;
  const type = getNodeType(typeOrName, state.schema);
  const { $from, $to } = state.selection;
  const node2 = state.selection.node;
  if (node2 && node2.isBlock || $from.depth < 2 || !$from.sameParent($to)) {
    return false;
  }
  const grandParent = $from.node(-1);
  if (grandParent.type !== type) {
    return false;
  }
  const extensionAttributes = editor.extensionManager.attributes;
  if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {
    if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) {
      return false;
    }
    if (dispatch) {
      let wrap5 = Fragment.empty;
      const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;
      for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {
        wrap5 = Fragment.from($from.node(d).copy(wrap5));
      }
      const depthAfter = (
        // eslint-disable-next-line no-nested-ternary
        $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3
      );
      const newNextTypeAttributes2 = {
        ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
        ...overrideAttrs
      };
      const nextType2 = ((_a2 = type.contentMatch.defaultType) == null ? void 0 : _a2.createAndFill(newNextTypeAttributes2)) || void 0;
      wrap5 = wrap5.append(Fragment.from(type.createAndFill(null, nextType2) || void 0));
      const start = $from.before($from.depth - (depthBefore - 1));
      tr4.replace(start, $from.after(-depthAfter), new Slice(wrap5, 4 - depthBefore, 0));
      let sel = -1;
      tr4.doc.nodesBetween(start, tr4.doc.content.size, (n, pos) => {
        if (sel > -1) {
          return false;
        }
        if (n.isTextblock && n.content.size === 0) {
          sel = pos + 1;
        }
      });
      if (sel > -1) {
        tr4.setSelection(TextSelection.near(tr4.doc.resolve(sel)));
      }
      tr4.scrollIntoView();
    }
    return true;
  }
  const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
  const newTypeAttributes = {
    ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),
    ...overrideAttrs
  };
  const newNextTypeAttributes = {
    ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
    ...overrideAttrs
  };
  tr4.delete($from.pos, $to.pos);
  const types2 = nextType ? [
    { type, attrs: newTypeAttributes },
    { type: nextType, attrs: newNextTypeAttributes }
  ] : [{ type, attrs: newTypeAttributes }];
  if (!canSplit(tr4.doc, $from.pos, 2)) {
    return false;
  }
  if (dispatch) {
    const { selection, storedMarks } = state;
    const { splittableMarks } = editor.extensionManager;
    const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
    tr4.split($from.pos, 2, types2).scrollIntoView();
    if (!marks || !dispatch) {
      return true;
    }
    const filteredMarks = marks.filter((mark2) => splittableMarks.includes(mark2.type.name));
    tr4.ensureMarks(filteredMarks);
  }
  return true;
};
var joinListBackwards = (tr4, listType) => {
  const list7 = findParentNode((node2) => node2.type === listType)(tr4.selection);
  if (!list7) {
    return true;
  }
  const before = tr4.doc.resolve(Math.max(0, list7.pos - 1)).before(list7.depth);
  if (before === void 0) {
    return true;
  }
  const nodeBefore = tr4.doc.nodeAt(before);
  const canJoinBackwards = list7.node.type === (nodeBefore == null ? void 0 : nodeBefore.type) && canJoin(tr4.doc, list7.pos);
  if (!canJoinBackwards) {
    return true;
  }
  tr4.join(list7.pos);
  return true;
};
var joinListForwards = (tr4, listType) => {
  const list7 = findParentNode((node2) => node2.type === listType)(tr4.selection);
  if (!list7) {
    return true;
  }
  const after = tr4.doc.resolve(list7.start).after(list7.depth);
  if (after === void 0) {
    return true;
  }
  const nodeAfter = tr4.doc.nodeAt(after);
  const canJoinForwards = list7.node.type === (nodeAfter == null ? void 0 : nodeAfter.type) && canJoin(tr4.doc, after);
  if (!canJoinForwards) {
    return true;
  }
  tr4.join(after);
  return true;
};
var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr: tr4, state, dispatch, chain, commands, can }) => {
  const { extensions, splittableMarks } = editor.extensionManager;
  const listType = getNodeType(listTypeOrName, state.schema);
  const itemType = getNodeType(itemTypeOrName, state.schema);
  const { selection, storedMarks } = state;
  const { $from, $to } = selection;
  const range = $from.blockRange($to);
  const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
  if (!range) {
    return false;
  }
  const parentList = findParentNode((node2) => isList(node2.type.name, extensions))(selection);
  if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {
    if (parentList.node.type === listType) {
      return commands.liftListItem(itemType);
    }
    if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) {
      return chain().command(() => {
        tr4.setNodeMarkup(parentList.pos, listType);
        return true;
      }).command(() => joinListBackwards(tr4, listType)).command(() => joinListForwards(tr4, listType)).run();
    }
  }
  if (!keepMarks || !marks || !dispatch) {
    return chain().command(() => {
      const canWrapInList = can().wrapInList(listType, attributes);
      if (canWrapInList) {
        return true;
      }
      return commands.clearNodes();
    }).wrapInList(listType, attributes).command(() => joinListBackwards(tr4, listType)).command(() => joinListForwards(tr4, listType)).run();
  }
  return chain().command(() => {
    const canWrapInList = can().wrapInList(listType, attributes);
    const filteredMarks = marks.filter((mark2) => splittableMarks.includes(mark2.type.name));
    tr4.ensureMarks(filteredMarks);
    if (canWrapInList) {
      return true;
    }
    return commands.clearNodes();
  }).wrapInList(listType, attributes).command(() => joinListBackwards(tr4, listType)).command(() => joinListForwards(tr4, listType)).run();
};
var toggleMark = (typeOrName, attributes = {}, options2 = {}) => ({ state, commands }) => {
  const { extendEmptyMarkRange = false } = options2;
  const type = getMarkType(typeOrName, state.schema);
  const isActive2 = isMarkActive(state, type, attributes);
  if (isActive2) {
    return commands.unsetMark(type, { extendEmptyMarkRange });
  }
  return commands.setMark(type, attributes);
};
var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => {
  const type = getNodeType(typeOrName, state.schema);
  const toggleType = getNodeType(toggleTypeOrName, state.schema);
  const isActive2 = isNodeActive(state, type, attributes);
  let attributesToCopy;
  if (state.selection.$anchor.sameParent(state.selection.$head)) {
    attributesToCopy = state.selection.$anchor.parent.attrs;
  }
  if (isActive2) {
    return commands.setNode(toggleType, attributesToCopy);
  }
  return commands.setNode(type, { ...attributesToCopy, ...attributes });
};
var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => {
  const type = getNodeType(typeOrName, state.schema);
  const isActive2 = isNodeActive(state, type, attributes);
  if (isActive2) {
    return commands.lift(type);
  }
  return commands.wrapIn(type, attributes);
};
var undoInputRule = () => ({ state, dispatch }) => {
  const plugins = state.plugins;
  for (let i3 = 0; i3 < plugins.length; i3 += 1) {
    const plugin = plugins[i3];
    let undoable;
    if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
      if (dispatch) {
        const tr4 = state.tr;
        const toUndo = undoable.transform;
        for (let j4 = toUndo.steps.length - 1; j4 >= 0; j4 -= 1) {
          tr4.step(toUndo.steps[j4].invert(toUndo.docs[j4]));
        }
        if (undoable.text) {
          const marks = tr4.doc.resolve(undoable.from).marks();
          tr4.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
        } else {
          tr4.delete(undoable.from, undoable.to);
        }
      }
      return true;
    }
  }
  return false;
};
var unsetAllMarks = () => ({ tr: tr4, dispatch }) => {
  const { selection } = tr4;
  const { empty: empty4, ranges } = selection;
  if (empty4) {
    return true;
  }
  if (dispatch) {
    ranges.forEach((range) => {
      tr4.removeMark(range.$from.pos, range.$to.pos);
    });
  }
  return true;
};
var unsetMark = (typeOrName, options2 = {}) => ({ tr: tr4, state, dispatch }) => {
  var _a2;
  const { extendEmptyMarkRange = false } = options2;
  const { selection } = tr4;
  const type = getMarkType(typeOrName, state.schema);
  const { $from, empty: empty4, ranges } = selection;
  if (!dispatch) {
    return true;
  }
  if (empty4 && extendEmptyMarkRange) {
    let { from: from4, to: to2 } = selection;
    const attrs = (_a2 = $from.marks().find((mark2) => mark2.type === type)) == null ? void 0 : _a2.attrs;
    const range = getMarkRange($from, type, attrs);
    if (range) {
      from4 = range.from;
      to2 = range.to;
    }
    tr4.removeMark(from4, to2, type);
  } else {
    ranges.forEach((range) => {
      tr4.removeMark(range.$from.pos, range.$to.pos, type);
    });
  }
  tr4.removeStoredMark(type);
  return true;
};
var unsetTextDirection = (position4) => ({ tr: tr4, state, dispatch }) => {
  const { selection } = state;
  let from4;
  let to2;
  if (typeof position4 === "number") {
    from4 = position4;
    to2 = position4;
  } else if (position4 && "from" in position4 && "to" in position4) {
    from4 = position4.from;
    to2 = position4.to;
  } else {
    from4 = selection.from;
    to2 = selection.to;
  }
  if (dispatch) {
    tr4.doc.nodesBetween(from4, to2, (node2, pos) => {
      if (node2.isText) {
        return;
      }
      const newAttrs = { ...node2.attrs };
      delete newAttrs.dir;
      tr4.setNodeMarkup(pos, void 0, newAttrs);
    });
  }
  return true;
};
var updateAttributes = (typeOrName, attributes = {}) => ({ tr: tr4, state, dispatch }) => {
  let nodeType = null;
  let markType = null;
  const schemaType = getSchemaTypeNameByName(
    typeof typeOrName === "string" ? typeOrName : typeOrName.name,
    state.schema
  );
  if (!schemaType) {
    return false;
  }
  if (schemaType === "node") {
    nodeType = getNodeType(typeOrName, state.schema);
  }
  if (schemaType === "mark") {
    markType = getMarkType(typeOrName, state.schema);
  }
  let canUpdate = false;
  tr4.selection.ranges.forEach((range) => {
    const from4 = range.$from.pos;
    const to2 = range.$to.pos;
    let lastPos;
    let lastNode;
    let trimmedFrom;
    let trimmedTo;
    if (tr4.selection.empty) {
      state.doc.nodesBetween(from4, to2, (node2, pos) => {
        if (nodeType && nodeType === node2.type) {
          canUpdate = true;
          trimmedFrom = Math.max(pos, from4);
          trimmedTo = Math.min(pos + node2.nodeSize, to2);
          lastPos = pos;
          lastNode = node2;
        }
      });
    } else {
      state.doc.nodesBetween(from4, to2, (node2, pos) => {
        if (pos < from4 && nodeType && nodeType === node2.type) {
          canUpdate = true;
          trimmedFrom = Math.max(pos, from4);
          trimmedTo = Math.min(pos + node2.nodeSize, to2);
          lastPos = pos;
          lastNode = node2;
        }
        if (pos >= from4 && pos <= to2) {
          if (nodeType && nodeType === node2.type) {
            canUpdate = true;
            if (dispatch) {
              tr4.setNodeMarkup(pos, void 0, {
                ...node2.attrs,
                ...attributes
              });
            }
          }
          if (markType && node2.marks.length) {
            node2.marks.forEach((mark2) => {
              if (markType === mark2.type) {
                canUpdate = true;
                if (dispatch) {
                  const trimmedFrom2 = Math.max(pos, from4);
                  const trimmedTo2 = Math.min(pos + node2.nodeSize, to2);
                  tr4.addMark(
                    trimmedFrom2,
                    trimmedTo2,
                    markType.create({
                      ...mark2.attrs,
                      ...attributes
                    })
                  );
                }
              }
            });
          }
        }
      });
    }
    if (lastNode) {
      if (lastPos !== void 0 && dispatch) {
        tr4.setNodeMarkup(lastPos, void 0, {
          ...lastNode.attrs,
          ...attributes
        });
      }
      if (markType && lastNode.marks.length) {
        lastNode.marks.forEach((mark2) => {
          if (markType === mark2.type && dispatch) {
            tr4.addMark(
              trimmedFrom,
              trimmedTo,
              markType.create({
                ...mark2.attrs,
                ...attributes
              })
            );
          }
        });
      }
    }
  });
  return canUpdate;
};
var wrapIn2 = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return wrapIn(type, attributes)(state, dispatch);
};
var wrapInList2 = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return wrapInList(type, attributes)(state, dispatch);
};
var EventEmitter = class {
  constructor() {
    this.callbacks = {};
  }
  on(event, fn4) {
    if (!this.callbacks[event]) {
      this.callbacks[event] = [];
    }
    this.callbacks[event].push(fn4);
    return this;
  }
  emit(event, ...args2) {
    const callbacks = this.callbacks[event];
    if (callbacks) {
      callbacks.forEach((callback) => callback.apply(this, args2));
    }
    return this;
  }
  off(event, fn4) {
    const callbacks = this.callbacks[event];
    if (callbacks) {
      if (fn4) {
        this.callbacks[event] = callbacks.filter((callback) => callback !== fn4);
      } else {
        delete this.callbacks[event];
      }
    }
    return this;
  }
  once(event, fn4) {
    const onceFn = (...args2) => {
      this.off(event, onceFn);
      fn4.apply(this, args2);
    };
    return this.on(event, onceFn);
  }
  removeAllListeners() {
    this.callbacks = {};
  }
};
var InputRule = class {
  constructor(config) {
    var _a2;
    this.find = config.find;
    this.handler = config.handler;
    this.undoable = (_a2 = config.undoable) != null ? _a2 : true;
  }
};
var inputRuleMatcherHandler = (text10, find4) => {
  if (isRegExp(find4)) {
    return find4.exec(text10);
  }
  const inputRuleMatch = find4(text10);
  if (!inputRuleMatch) {
    return null;
  }
  const result = [inputRuleMatch.text];
  result.index = inputRuleMatch.index;
  result.input = text10;
  result.data = inputRuleMatch.data;
  if (inputRuleMatch.replaceWith) {
    if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {
      console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".');
    }
    result.push(inputRuleMatch.replaceWith);
  }
  return result;
};
function run(config) {
  var _a2;
  const { editor, from: from4, to: to2, text: text10, rules, plugin } = config;
  const { view } = editor;
  if (view.composing) {
    return false;
  }
  const $from = view.state.doc.resolve(from4);
  if (
    // check for code node
    $from.parent.type.spec.code || // check for code mark
    !!((_a2 = $from.nodeBefore || $from.nodeAfter) == null ? void 0 : _a2.marks.find((mark2) => mark2.type.spec.code))
  ) {
    return false;
  }
  let matched = false;
  const textBefore = getTextContentFromNodes($from) + text10;
  rules.forEach((rule) => {
    if (matched) {
      return;
    }
    const match2 = inputRuleMatcherHandler(textBefore, rule.find);
    if (!match2) {
      return;
    }
    const tr4 = view.state.tr;
    const state = createChainableState({
      state: view.state,
      transaction: tr4
    });
    const range = {
      from: from4 - (match2[0].length - text10.length),
      to: to2
    };
    const { commands, chain, can } = new CommandManager({
      editor,
      state
    });
    const handler = rule.handler({
      state,
      range,
      match: match2,
      commands,
      chain,
      can
    });
    if (handler === null || !tr4.steps.length) {
      return;
    }
    if (rule.undoable) {
      tr4.setMeta(plugin, {
        transform: tr4,
        from: from4,
        to: to2,
        text: text10
      });
    }
    view.dispatch(tr4);
    matched = true;
  });
  return matched;
}
function inputRulesPlugin(props) {
  const { editor, rules } = props;
  const plugin = new Plugin({
    state: {
      init() {
        return null;
      },
      apply(tr4, prev, state) {
        const stored = tr4.getMeta(plugin);
        if (stored) {
          return stored;
        }
        const simulatedInputMeta = tr4.getMeta("applyInputRules");
        const isSimulatedInput = !!simulatedInputMeta;
        if (isSimulatedInput) {
          setTimeout(() => {
            let { text: text10 } = simulatedInputMeta;
            if (typeof text10 === "string") {
              text10 = text10;
            } else {
              text10 = getHTMLFromFragment(Fragment.from(text10), state.schema);
            }
            const { from: from4 } = simulatedInputMeta;
            const to2 = from4 + text10.length;
            run({
              editor,
              from: from4,
              to: to2,
              text: text10,
              rules,
              plugin
            });
          });
        }
        return tr4.selectionSet || tr4.docChanged ? null : prev;
      }
    },
    props: {
      handleTextInput(view, from4, to2, text10) {
        return run({
          editor,
          from: from4,
          to: to2,
          text: text10,
          rules,
          plugin
        });
      },
      handleDOMEvents: {
        compositionend: (view) => {
          setTimeout(() => {
            const { $cursor } = view.state.selection;
            if ($cursor) {
              run({
                editor,
                from: $cursor.pos,
                to: $cursor.pos,
                text: "",
                rules,
                plugin
              });
            }
          });
          return false;
        }
      },
      // add support for input rules to trigger on enter
      // this is useful for example for code blocks
      handleKeyDown(view, event) {
        if (event.key !== "Enter") {
          return false;
        }
        const { $cursor } = view.state.selection;
        if ($cursor) {
          return run({
            editor,
            from: $cursor.pos,
            to: $cursor.pos,
            text: "\n",
            rules,
            plugin
          });
        }
        return false;
      }
    },
    // @ts-ignore
    isInputRules: true
  });
  return plugin;
}
function getType(value) {
  return Object.prototype.toString.call(value).slice(8, -1);
}
function isPlainObject(value) {
  if (getType(value) !== "Object") {
    return false;
  }
  return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype;
}
function mergeDeep(target, source) {
  const output = { ...target };
  if (isPlainObject(target) && isPlainObject(source)) {
    Object.keys(source).forEach((key2) => {
      if (isPlainObject(source[key2]) && isPlainObject(target[key2])) {
        output[key2] = mergeDeep(target[key2], source[key2]);
      } else {
        output[key2] = source[key2];
      }
    });
  }
  return output;
}
var Extendable = class {
  constructor(config = {}) {
    this.type = "extendable";
    this.parent = null;
    this.child = null;
    this.name = "";
    this.config = {
      name: this.name
    };
    this.config = {
      ...this.config,
      ...config
    };
    this.name = this.config.name;
  }
  get options() {
    return {
      ...callOrReturn(
        getExtensionField(this, "addOptions", {
          name: this.name
        })
      ) || {}
    };
  }
  get storage() {
    return {
      ...callOrReturn(
        getExtensionField(this, "addStorage", {
          name: this.name,
          options: this.options
        })
      ) || {}
    };
  }
  configure(options2 = {}) {
    const extension2 = this.extend({
      ...this.config,
      addOptions: () => {
        return mergeDeep(this.options, options2);
      }
    });
    extension2.name = this.name;
    extension2.parent = this.parent;
    return extension2;
  }
  extend(extendedConfig = {}) {
    const extension2 = new this.constructor({ ...this.config, ...extendedConfig });
    extension2.parent = this;
    this.child = extension2;
    extension2.name = "name" in extendedConfig ? extendedConfig.name : extension2.parent.name;
    return extension2;
  }
};
var Mark2 = class _Mark extends Extendable {
  constructor() {
    super(...arguments);
    this.type = "mark";
  }
  /**
   * Create a new Mark instance
   * @param config - Mark configuration object or a function that returns a configuration object
   */
  static create(config = {}) {
    const resolvedConfig = typeof config === "function" ? config() : config;
    return new _Mark(resolvedConfig);
  }
  static handleExit({ editor, mark: mark2 }) {
    const { tr: tr4 } = editor.state;
    const currentPos = editor.state.selection.$from;
    const isAtEnd = currentPos.pos === currentPos.end();
    if (isAtEnd) {
      const currentMarks = currentPos.marks();
      const isInMark = !!currentMarks.find((m2) => (m2 == null ? void 0 : m2.type.name) === mark2.name);
      if (!isInMark) {
        return false;
      }
      const removeMark2 = currentMarks.find((m2) => (m2 == null ? void 0 : m2.type.name) === mark2.name);
      if (removeMark2) {
        tr4.removeStoredMark(removeMark2);
      }
      tr4.insertText(" ", currentPos.pos);
      editor.view.dispatch(tr4);
      return true;
    }
    return false;
  }
  configure(options2) {
    return super.configure(options2);
  }
  extend(extendedConfig) {
    const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
    return super.extend(resolvedConfig);
  }
};
function isNumber(value) {
  return typeof value === "number";
}
var PasteRule = class {
  constructor(config) {
    this.find = config.find;
    this.handler = config.handler;
  }
};
var pasteRuleMatcherHandler = (text10, find4, event) => {
  if (isRegExp(find4)) {
    return [...text10.matchAll(find4)];
  }
  const matches3 = find4(text10, event);
  if (!matches3) {
    return [];
  }
  return matches3.map((pasteRuleMatch) => {
    const result = [pasteRuleMatch.text];
    result.index = pasteRuleMatch.index;
    result.input = text10;
    result.data = pasteRuleMatch.data;
    if (pasteRuleMatch.replaceWith) {
      if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {
        console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".');
      }
      result.push(pasteRuleMatch.replaceWith);
    }
    return result;
  });
};
function run2(config) {
  const { editor, state, from: from4, to: to2, rule, pasteEvent, dropEvent } = config;
  const { commands, chain, can } = new CommandManager({
    editor,
    state
  });
  const handlers4 = [];
  state.doc.nodesBetween(from4, to2, (node2, pos) => {
    var _a2, _b, _c, _d, _e4;
    if (((_b = (_a2 = node2.type) == null ? void 0 : _a2.spec) == null ? void 0 : _b.code) || !(node2.isText || node2.isTextblock || node2.isInline)) {
      return;
    }
    const contentSize = (_e4 = (_d = (_c = node2.content) == null ? void 0 : _c.size) != null ? _d : node2.nodeSize) != null ? _e4 : 0;
    const resolvedFrom = Math.max(from4, pos);
    const resolvedTo = Math.min(to2, pos + contentSize);
    if (resolvedFrom >= resolvedTo) {
      return;
    }
    const textToMatch = node2.isText ? node2.text || "" : node2.textBetween(resolvedFrom - pos, resolvedTo - pos, void 0, "￼");
    const matches3 = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent);
    matches3.forEach((match2) => {
      if (match2.index === void 0) {
        return;
      }
      const start = resolvedFrom + match2.index + 1;
      const end = start + match2[0].length;
      const range = {
        from: state.tr.mapping.map(start),
        to: state.tr.mapping.map(end)
      };
      const handler = rule.handler({
        state,
        range,
        match: match2,
        commands,
        chain,
        can,
        pasteEvent,
        dropEvent
      });
      handlers4.push(handler);
    });
  });
  const success = handlers4.every((handler) => handler !== null);
  return success;
}
var tiptapDragFromOtherEditor = null;
var createClipboardPasteEvent = (text10) => {
  var _a2;
  const event = new ClipboardEvent("paste", {
    clipboardData: new DataTransfer()
  });
  (_a2 = event.clipboardData) == null ? void 0 : _a2.setData("text/html", text10);
  return event;
};
function pasteRulesPlugin(props) {
  const { editor, rules } = props;
  let dragSourceElement = null;
  let isPastedFromProseMirror = false;
  let isDroppedFromProseMirror = false;
  let pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null;
  let dropEvent;
  try {
    dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null;
  } catch {
    dropEvent = null;
  }
  const processEvent = ({
    state,
    from: from4,
    to: to2,
    rule,
    pasteEvt
  }) => {
    const tr4 = state.tr;
    const chainableState = createChainableState({
      state,
      transaction: tr4
    });
    const handler = run2({
      editor,
      state: chainableState,
      from: Math.max(from4 - 1, 0),
      to: to2.b - 1,
      rule,
      pasteEvent: pasteEvt,
      dropEvent
    });
    if (!handler || !tr4.steps.length) {
      return;
    }
    try {
      dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null;
    } catch {
      dropEvent = null;
    }
    pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null;
    return tr4;
  };
  const plugins = rules.map((rule) => {
    return new Plugin({
      // we register a global drag handler to track the current drag source element
      view(view) {
        const handleDragstart = (event) => {
          var _a2;
          dragSourceElement = ((_a2 = view.dom.parentElement) == null ? void 0 : _a2.contains(event.target)) ? view.dom.parentElement : null;
          if (dragSourceElement) {
            tiptapDragFromOtherEditor = editor;
          }
        };
        const handleDragend = () => {
          if (tiptapDragFromOtherEditor) {
            tiptapDragFromOtherEditor = null;
          }
        };
        window.addEventListener("dragstart", handleDragstart);
        window.addEventListener("dragend", handleDragend);
        return {
          destroy() {
            window.removeEventListener("dragstart", handleDragstart);
            window.removeEventListener("dragend", handleDragend);
          }
        };
      },
      props: {
        handleDOMEvents: {
          drop: (view, event) => {
            isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement;
            dropEvent = event;
            if (!isDroppedFromProseMirror) {
              const dragFromOtherEditor = tiptapDragFromOtherEditor;
              if (dragFromOtherEditor == null ? void 0 : dragFromOtherEditor.isEditable) {
                setTimeout(() => {
                  const selection = dragFromOtherEditor.state.selection;
                  if (selection) {
                    dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to });
                  }
                }, 10);
              }
            }
            return false;
          },
          paste: (_view, event) => {
            var _a2;
            const html7 = (_a2 = event.clipboardData) == null ? void 0 : _a2.getData("text/html");
            pasteEvent = event;
            isPastedFromProseMirror = !!(html7 == null ? void 0 : html7.includes("data-pm-slice"));
            return false;
          }
        }
      },
      appendTransaction: (transactions, oldState, state) => {
        const transaction = transactions[0];
        const isPaste = transaction.getMeta("uiEvent") === "paste" && !isPastedFromProseMirror;
        const isDrop = transaction.getMeta("uiEvent") === "drop" && !isDroppedFromProseMirror;
        const simulatedPasteMeta = transaction.getMeta("applyPasteRules");
        const isSimulatedPaste = !!simulatedPasteMeta;
        if (!isPaste && !isDrop && !isSimulatedPaste) {
          return;
        }
        if (isSimulatedPaste) {
          let { text: text10 } = simulatedPasteMeta;
          if (typeof text10 === "string") {
            text10 = text10;
          } else {
            text10 = getHTMLFromFragment(Fragment.from(text10), state.schema);
          }
          const { from: from22 } = simulatedPasteMeta;
          const to22 = from22 + text10.length;
          const pasteEvt = createClipboardPasteEvent(text10);
          return processEvent({
            rule,
            state,
            from: from22,
            to: { b: to22 },
            pasteEvt
          });
        }
        const from4 = oldState.doc.content.findDiffStart(state.doc.content);
        const to2 = oldState.doc.content.findDiffEnd(state.doc.content);
        if (!isNumber(from4) || !to2 || from4 === to2.b) {
          return;
        }
        return processEvent({
          rule,
          state,
          from: from4,
          to: to2,
          pasteEvt: pasteEvent
        });
      }
    });
  });
  return plugins;
}
var ExtensionManager = class {
  constructor(extensions, editor) {
    this.splittableMarks = [];
    this.editor = editor;
    this.baseExtensions = extensions;
    this.extensions = resolveExtensions(extensions);
    this.schema = getSchemaByResolvedExtensions(this.extensions, editor);
    this.setupExtensions();
  }
  /**
   * Get all commands from the extensions.
   * @returns An object with all commands where the key is the command name and the value is the command function
   */
  get commands() {
    return this.extensions.reduce((commands, extension2) => {
      const context = {
        name: extension2.name,
        options: extension2.options,
        storage: this.editor.extensionStorage[extension2.name],
        editor: this.editor,
        type: getSchemaTypeByName(extension2.name, this.schema)
      };
      const addCommands = getExtensionField(extension2, "addCommands", context);
      if (!addCommands) {
        return commands;
      }
      return {
        ...commands,
        ...addCommands()
      };
    }, {});
  }
  /**
   * Get all registered Prosemirror plugins from the extensions.
   * @returns An array of Prosemirror plugins
   */
  get plugins() {
    const { editor } = this;
    const extensions = sortExtensions([...this.extensions].reverse());
    const allPlugins = extensions.flatMap((extension2) => {
      const context = {
        name: extension2.name,
        options: extension2.options,
        storage: this.editor.extensionStorage[extension2.name],
        editor,
        type: getSchemaTypeByName(extension2.name, this.schema)
      };
      const plugins = [];
      const addKeyboardShortcuts = getExtensionField(
        extension2,
        "addKeyboardShortcuts",
        context
      );
      let defaultBindings = {};
      if (extension2.type === "mark" && getExtensionField(extension2, "exitable", context)) {
        defaultBindings.ArrowRight = () => Mark2.handleExit({ editor, mark: extension2 });
      }
      if (addKeyboardShortcuts) {
        const bindings = Object.fromEntries(
          Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => {
            return [shortcut, () => method({ editor })];
          })
        );
        defaultBindings = { ...defaultBindings, ...bindings };
      }
      const keyMapPlugin = keymap(defaultBindings);
      plugins.push(keyMapPlugin);
      const addInputRules = getExtensionField(extension2, "addInputRules", context);
      if (isExtensionRulesEnabled(extension2, editor.options.enableInputRules) && addInputRules) {
        const rules = addInputRules();
        if (rules && rules.length) {
          const inputResult = inputRulesPlugin({
            editor,
            rules
          });
          const inputPlugins = Array.isArray(inputResult) ? inputResult : [inputResult];
          plugins.push(...inputPlugins);
        }
      }
      const addPasteRules = getExtensionField(extension2, "addPasteRules", context);
      if (isExtensionRulesEnabled(extension2, editor.options.enablePasteRules) && addPasteRules) {
        const rules = addPasteRules();
        if (rules && rules.length) {
          const pasteRules = pasteRulesPlugin({ editor, rules });
          plugins.push(...pasteRules);
        }
      }
      const addProseMirrorPlugins = getExtensionField(
        extension2,
        "addProseMirrorPlugins",
        context
      );
      if (addProseMirrorPlugins) {
        const proseMirrorPlugins = addProseMirrorPlugins();
        plugins.push(...proseMirrorPlugins);
      }
      return plugins;
    });
    return allPlugins;
  }
  /**
   * Get all attributes from the extensions.
   * @returns An array of attributes
   */
  get attributes() {
    return getAttributesFromExtensions(this.extensions);
  }
  /**
   * Get all node views from the extensions.
   * @returns An object with all node views where the key is the node name and the value is the node view function
   */
  get nodeViews() {
    const { editor } = this;
    const { nodeExtensions } = splitExtensions(this.extensions);
    return Object.fromEntries(
      nodeExtensions.filter((extension2) => !!getExtensionField(extension2, "addNodeView")).map((extension2) => {
        const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension2.name);
        const context = {
          name: extension2.name,
          options: extension2.options,
          storage: this.editor.extensionStorage[extension2.name],
          editor,
          type: getNodeType(extension2.name, this.schema)
        };
        const addNodeView = getExtensionField(extension2, "addNodeView", context);
        if (!addNodeView) {
          return [];
        }
        const nodeViewResult = addNodeView();
        if (!nodeViewResult) {
          return [];
        }
        const nodeview = (node2, view, getPos, decorations, innerDecorations) => {
          const HTMLAttributes = getRenderedAttributes(node2, extensionAttributes);
          return nodeViewResult({
            // pass-through
            node: node2,
            view,
            getPos,
            decorations,
            innerDecorations,
            // tiptap-specific
            editor,
            extension: extension2,
            HTMLAttributes
          });
        };
        return [extension2.name, nodeview];
      })
    );
  }
  get markViews() {
    const { editor } = this;
    const { markExtensions } = splitExtensions(this.extensions);
    return Object.fromEntries(
      markExtensions.filter((extension2) => !!getExtensionField(extension2, "addMarkView")).map((extension2) => {
        const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension2.name);
        const context = {
          name: extension2.name,
          options: extension2.options,
          storage: this.editor.extensionStorage[extension2.name],
          editor,
          type: getMarkType(extension2.name, this.schema)
        };
        const addMarkView = getExtensionField(extension2, "addMarkView", context);
        if (!addMarkView) {
          return [];
        }
        const markView = (mark2, view, inline4) => {
          const HTMLAttributes = getRenderedAttributes(mark2, extensionAttributes);
          return addMarkView()({
            // pass-through
            mark: mark2,
            view,
            inline: inline4,
            // tiptap-specific
            editor,
            extension: extension2,
            HTMLAttributes,
            updateAttributes: (attrs) => {
              updateMarkViewAttributes(mark2, editor, attrs);
            }
          });
        };
        return [extension2.name, markView];
      })
    );
  }
  /**
   * Go through all extensions, create extension storages & setup marks
   * & bind editor event listener.
   */
  setupExtensions() {
    const extensions = this.extensions;
    this.editor.extensionStorage = Object.fromEntries(
      extensions.map((extension2) => [extension2.name, extension2.storage])
    );
    extensions.forEach((extension2) => {
      var _a2;
      const context = {
        name: extension2.name,
        options: extension2.options,
        storage: this.editor.extensionStorage[extension2.name],
        editor: this.editor,
        type: getSchemaTypeByName(extension2.name, this.schema)
      };
      if (extension2.type === "mark") {
        const keepOnSplit = (_a2 = callOrReturn(getExtensionField(extension2, "keepOnSplit", context))) != null ? _a2 : true;
        if (keepOnSplit) {
          this.splittableMarks.push(extension2.name);
        }
      }
      const onBeforeCreate = getExtensionField(extension2, "onBeforeCreate", context);
      const onCreate = getExtensionField(extension2, "onCreate", context);
      const onUpdate = getExtensionField(extension2, "onUpdate", context);
      const onSelectionUpdate = getExtensionField(
        extension2,
        "onSelectionUpdate",
        context
      );
      const onTransaction = getExtensionField(extension2, "onTransaction", context);
      const onFocus = getExtensionField(extension2, "onFocus", context);
      const onBlur = getExtensionField(extension2, "onBlur", context);
      const onDestroy = getExtensionField(extension2, "onDestroy", context);
      if (onBeforeCreate) {
        this.editor.on("beforeCreate", onBeforeCreate);
      }
      if (onCreate) {
        this.editor.on("create", onCreate);
      }
      if (onUpdate) {
        this.editor.on("update", onUpdate);
      }
      if (onSelectionUpdate) {
        this.editor.on("selectionUpdate", onSelectionUpdate);
      }
      if (onTransaction) {
        this.editor.on("transaction", onTransaction);
      }
      if (onFocus) {
        this.editor.on("focus", onFocus);
      }
      if (onBlur) {
        this.editor.on("blur", onBlur);
      }
      if (onDestroy) {
        this.editor.on("destroy", onDestroy);
      }
    });
  }
};
ExtensionManager.resolve = resolveExtensions;
ExtensionManager.sort = sortExtensions;
ExtensionManager.flatten = flattenExtensions;
var extensions_exports = {};
__export2(extensions_exports, {
  ClipboardTextSerializer: () => ClipboardTextSerializer,
  Commands: () => Commands,
  Delete: () => Delete,
  Drop: () => Drop,
  Editable: () => Editable,
  FocusEvents: () => FocusEvents,
  Keymap: () => Keymap,
  Paste: () => Paste,
  Tabindex: () => Tabindex,
  TextDirection: () => TextDirection,
  focusEventsPluginKey: () => focusEventsPluginKey
});
var Extension = class _Extension extends Extendable {
  constructor() {
    super(...arguments);
    this.type = "extension";
  }
  /**
   * Create a new Extension instance
   * @param config - Extension configuration object or a function that returns a configuration object
   */
  static create(config = {}) {
    const resolvedConfig = typeof config === "function" ? config() : config;
    return new _Extension(resolvedConfig);
  }
  configure(options2) {
    return super.configure(options2);
  }
  extend(extendedConfig) {
    const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
    return super.extend(resolvedConfig);
  }
};
var ClipboardTextSerializer = Extension.create({
  name: "clipboardTextSerializer",
  addOptions() {
    return {
      blockSeparator: void 0
    };
  },
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("clipboardTextSerializer"),
        props: {
          clipboardTextSerializer: () => {
            const { editor } = this;
            const { state, schema } = editor;
            const { doc: doc4, selection } = state;
            const { ranges } = selection;
            const from4 = Math.min(...ranges.map((range2) => range2.$from.pos));
            const to2 = Math.max(...ranges.map((range2) => range2.$to.pos));
            const textSerializers = getTextSerializersFromSchema(schema);
            const range = { from: from4, to: to2 };
            return getTextBetween(doc4, range, {
              ...this.options.blockSeparator !== void 0 ? { blockSeparator: this.options.blockSeparator } : {},
              textSerializers
            });
          }
        }
      })
    ];
  }
});
var Commands = Extension.create({
  name: "commands",
  addCommands() {
    return {
      ...commands_exports
    };
  }
});
var Delete = Extension.create({
  name: "delete",
  onUpdate({ transaction, appendedTransactions }) {
    var _a2, _b, _c;
    const callback = () => {
      var _a22, _b2, _c2, _d;
      if ((_d = (_c2 = (_b2 = (_a22 = this.editor.options.coreExtensionOptions) == null ? void 0 : _a22.delete) == null ? void 0 : _b2.filterTransaction) == null ? void 0 : _c2.call(_b2, transaction)) != null ? _d : transaction.getMeta("y-sync$")) {
        return;
      }
      const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions]);
      const changes = getChangedRanges(nextTransaction);
      changes.forEach((change) => {
        if (nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter && nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore) {
          nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node2, from4) => {
            const to2 = from4 + node2.nodeSize - 2;
            const isFullyWithinRange = change.oldRange.from <= from4 && to2 <= change.oldRange.to;
            this.editor.emit("delete", {
              type: "node",
              node: node2,
              from: from4,
              to: to2,
              newFrom: nextTransaction.mapping.map(from4),
              newTo: nextTransaction.mapping.map(to2),
              deletedRange: change.oldRange,
              newRange: change.newRange,
              partial: !isFullyWithinRange,
              editor: this.editor,
              transaction,
              combinedTransform: nextTransaction
            });
          });
        }
      });
      const mapping = nextTransaction.mapping;
      nextTransaction.steps.forEach((step, index4) => {
        var _a3, _b3;
        if (step instanceof RemoveMarkStep) {
          const newStart = mapping.slice(index4).map(step.from, -1);
          const newEnd = mapping.slice(index4).map(step.to);
          const oldStart = mapping.invert().map(newStart, -1);
          const oldEnd = mapping.invert().map(newEnd);
          const foundBeforeMark = (_a3 = nextTransaction.doc.nodeAt(newStart - 1)) == null ? void 0 : _a3.marks.some((mark2) => mark2.eq(step.mark));
          const foundAfterMark = (_b3 = nextTransaction.doc.nodeAt(newEnd)) == null ? void 0 : _b3.marks.some((mark2) => mark2.eq(step.mark));
          this.editor.emit("delete", {
            type: "mark",
            mark: step.mark,
            from: step.from,
            to: step.to,
            deletedRange: {
              from: oldStart,
              to: oldEnd
            },
            newRange: {
              from: newStart,
              to: newEnd
            },
            partial: Boolean(foundAfterMark || foundBeforeMark),
            editor: this.editor,
            transaction,
            combinedTransform: nextTransaction
          });
        }
      });
    };
    if ((_c = (_b = (_a2 = this.editor.options.coreExtensionOptions) == null ? void 0 : _a2.delete) == null ? void 0 : _b.async) != null ? _c : true) {
      setTimeout(callback, 0);
    } else {
      callback();
    }
  }
});
var Drop = Extension.create({
  name: "drop",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("tiptapDrop"),
        props: {
          handleDrop: (_2, e2, slice2, moved) => {
            this.editor.emit("drop", {
              editor: this.editor,
              event: e2,
              slice: slice2,
              moved
            });
          }
        }
      })
    ];
  }
});
var Editable = Extension.create({
  name: "editable",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("editable"),
        props: {
          editable: () => this.editor.options.editable
        }
      })
    ];
  }
});
var focusEventsPluginKey = new PluginKey("focusEvents");
var FocusEvents = Extension.create({
  name: "focusEvents",
  addProseMirrorPlugins() {
    const { editor } = this;
    return [
      new Plugin({
        key: focusEventsPluginKey,
        props: {
          handleDOMEvents: {
            focus: (view, event) => {
              editor.isFocused = true;
              const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false);
              view.dispatch(transaction);
              return false;
            },
            blur: (view, event) => {
              editor.isFocused = false;
              const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false);
              view.dispatch(transaction);
              return false;
            }
          }
        }
      })
    ];
  }
});
var Keymap = Extension.create({
  name: "keymap",
  addKeyboardShortcuts() {
    const handleBackspace = () => this.editor.commands.first(({ commands }) => [
      () => commands.undoInputRule(),
      // maybe convert first text block node to default node
      () => commands.command(({ tr: tr4 }) => {
        const { selection, doc: doc4 } = tr4;
        const { empty: empty4, $anchor } = selection;
        const { pos, parent } = $anchor;
        const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr4.doc.resolve(pos - 1) : $anchor;
        const parentIsIsolating = $parentPos.parent.type.spec.isolating;
        const parentPos = $anchor.pos - $anchor.parentOffset;
        const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection.atStart(doc4).from === pos;
        if (!empty4 || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") {
          return false;
        }
        return commands.clearNodes();
      }),
      () => commands.deleteSelection(),
      () => commands.joinBackward(),
      () => commands.selectNodeBackward()
    ]);
    const handleDelete2 = () => this.editor.commands.first(({ commands }) => [
      () => commands.deleteSelection(),
      () => commands.deleteCurrentNode(),
      () => commands.joinForward(),
      () => commands.selectNodeForward()
    ]);
    const handleEnter = () => this.editor.commands.first(({ commands }) => [
      () => commands.newlineInCode(),
      () => commands.createParagraphNear(),
      () => commands.liftEmptyBlock(),
      () => commands.splitBlock()
    ]);
    const baseKeymap = {
      Enter: handleEnter,
      "Mod-Enter": () => this.editor.commands.exitCode(),
      Backspace: handleBackspace,
      "Mod-Backspace": handleBackspace,
      "Shift-Backspace": handleBackspace,
      Delete: handleDelete2,
      "Mod-Delete": handleDelete2,
      "Mod-a": () => this.editor.commands.selectAll()
    };
    const pcKeymap = {
      ...baseKeymap
    };
    const macKeymap = {
      ...baseKeymap,
      "Ctrl-h": handleBackspace,
      "Alt-Backspace": handleBackspace,
      "Ctrl-d": handleDelete2,
      "Ctrl-Alt-Backspace": handleDelete2,
      "Alt-Delete": handleDelete2,
      "Alt-d": handleDelete2,
      "Ctrl-a": () => this.editor.commands.selectTextblockStart(),
      "Ctrl-e": () => this.editor.commands.selectTextblockEnd()
    };
    if (isiOS() || isMacOS()) {
      return macKeymap;
    }
    return pcKeymap;
  },
  addProseMirrorPlugins() {
    return [
      // With this plugin we check if the whole document was selected and deleted.
      // In this case we will additionally call `clearNodes()` to convert e.g. a heading
      // to a paragraph if necessary.
      // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well
      // with many other commands.
      new Plugin({
        key: new PluginKey("clearDocument"),
        appendTransaction: (transactions, oldState, newState) => {
          if (transactions.some((tr22) => tr22.getMeta("composition"))) {
            return;
          }
          const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
          const ignoreTr = transactions.some((transaction) => transaction.getMeta("preventClearDocument"));
          if (!docChanges || ignoreTr) {
            return;
          }
          const { empty: empty4, from: from4, to: to2 } = oldState.selection;
          const allFrom = Selection.atStart(oldState.doc).from;
          const allEnd = Selection.atEnd(oldState.doc).to;
          const allWasSelected = from4 === allFrom && to2 === allEnd;
          if (empty4 || !allWasSelected) {
            return;
          }
          const isEmpty3 = isNodeEmpty(newState.doc);
          if (!isEmpty3) {
            return;
          }
          const tr4 = newState.tr;
          const state = createChainableState({
            state: newState,
            transaction: tr4
          });
          const { commands } = new CommandManager({
            editor: this.editor,
            state
          });
          commands.clearNodes();
          if (!tr4.steps.length) {
            return;
          }
          return tr4;
        }
      })
    ];
  }
});
var Paste = Extension.create({
  name: "paste",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("tiptapPaste"),
        props: {
          handlePaste: (_view, e2, slice2) => {
            this.editor.emit("paste", {
              editor: this.editor,
              event: e2,
              slice: slice2
            });
          }
        }
      })
    ];
  }
});
var Tabindex = Extension.create({
  name: "tabindex",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("tabindex"),
        props: {
          attributes: () => this.editor.isEditable ? { tabindex: "0" } : {}
        }
      })
    ];
  }
});
var TextDirection = Extension.create({
  name: "textDirection",
  addOptions() {
    return {
      direction: void 0
    };
  },
  addGlobalAttributes() {
    if (!this.options.direction) {
      return [];
    }
    const { nodeExtensions } = splitExtensions(this.extensions);
    return [
      {
        types: nodeExtensions.filter((extension2) => extension2.name !== "text").map((extension2) => extension2.name),
        attributes: {
          dir: {
            default: this.options.direction,
            parseHTML: (element7) => {
              const dir = element7.getAttribute("dir");
              if (dir && (dir === "ltr" || dir === "rtl" || dir === "auto")) {
                return dir;
              }
              return this.options.direction;
            },
            renderHTML: (attributes) => {
              if (!attributes.dir) {
                return {};
              }
              return {
                dir: attributes.dir
              };
            }
          }
        }
      }
    ];
  },
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("textDirection"),
        props: {
          attributes: () => {
            const direction = this.options.direction;
            if (!direction) {
              return {};
            }
            return {
              dir: direction
            };
          }
        }
      })
    ];
  }
});
var NodePos = class _NodePos {
  constructor(pos, editor, isBlock = false, node2 = null) {
    this.currentNode = null;
    this.actualDepth = null;
    this.isBlock = isBlock;
    this.resolvedPos = pos;
    this.editor = editor;
    this.currentNode = node2;
  }
  get name() {
    return this.node.type.name;
  }
  get node() {
    return this.currentNode || this.resolvedPos.node();
  }
  get element() {
    return this.editor.view.domAtPos(this.pos).node;
  }
  get depth() {
    var _a2;
    return (_a2 = this.actualDepth) != null ? _a2 : this.resolvedPos.depth;
  }
  get pos() {
    return this.resolvedPos.pos;
  }
  get content() {
    return this.node.content;
  }
  set content(content5) {
    let from4 = this.from;
    let to2 = this.to;
    if (this.isBlock) {
      if (this.content.size === 0) {
        console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);
        return;
      }
      from4 = this.from + 1;
      to2 = this.to - 1;
    }
    this.editor.commands.insertContentAt({ from: from4, to: to2 }, content5);
  }
  get attributes() {
    return this.node.attrs;
  }
  get textContent() {
    return this.node.textContent;
  }
  get size() {
    return this.node.nodeSize;
  }
  get from() {
    if (this.isBlock) {
      return this.pos;
    }
    return this.resolvedPos.start(this.resolvedPos.depth);
  }
  get range() {
    return {
      from: this.from,
      to: this.to
    };
  }
  get to() {
    if (this.isBlock) {
      return this.pos + this.size;
    }
    return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1);
  }
  get parent() {
    if (this.depth === 0) {
      return null;
    }
    const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1);
    const $pos = this.resolvedPos.doc.resolve(parentPos);
    return new _NodePos($pos, this.editor);
  }
  get before() {
    let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2));
    if ($pos.depth !== this.depth) {
      $pos = this.resolvedPos.doc.resolve(this.from - 3);
    }
    return new _NodePos($pos, this.editor);
  }
  get after() {
    let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1));
    if ($pos.depth !== this.depth) {
      $pos = this.resolvedPos.doc.resolve(this.to + 3);
    }
    return new _NodePos($pos, this.editor);
  }
  get children() {
    const children = [];
    this.node.content.forEach((node2, offset4) => {
      const isBlock = node2.isBlock && !node2.isTextblock;
      const isNonTextAtom = node2.isAtom && !node2.isText;
      const targetPos = this.pos + offset4 + (isNonTextAtom ? 0 : 1);
      if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) {
        return;
      }
      const $pos = this.resolvedPos.doc.resolve(targetPos);
      if (!isBlock && $pos.depth <= this.depth) {
        return;
      }
      const childNodePos = new _NodePos($pos, this.editor, isBlock, isBlock ? node2 : null);
      if (isBlock) {
        childNodePos.actualDepth = this.depth + 1;
      }
      children.push(new _NodePos($pos, this.editor, isBlock, isBlock ? node2 : null));
    });
    return children;
  }
  get firstChild() {
    return this.children[0] || null;
  }
  get lastChild() {
    const children = this.children;
    return children[children.length - 1] || null;
  }
  closest(selector, attributes = {}) {
    let node2 = null;
    let currentNode = this.parent;
    while (currentNode && !node2) {
      if (currentNode.node.type.name === selector) {
        if (Object.keys(attributes).length > 0) {
          const nodeAttributes = currentNode.node.attrs;
          const attrKeys = Object.keys(attributes);
          for (let index4 = 0; index4 < attrKeys.length; index4 += 1) {
            const key2 = attrKeys[index4];
            if (nodeAttributes[key2] !== attributes[key2]) {
              break;
            }
          }
        } else {
          node2 = currentNode;
        }
      }
      currentNode = currentNode.parent;
    }
    return node2;
  }
  querySelector(selector, attributes = {}) {
    return this.querySelectorAll(selector, attributes, true)[0] || null;
  }
  querySelectorAll(selector, attributes = {}, firstItemOnly = false) {
    let nodes = [];
    if (!this.children || this.children.length === 0) {
      return nodes;
    }
    const attrKeys = Object.keys(attributes);
    this.children.forEach((childPos) => {
      if (firstItemOnly && nodes.length > 0) {
        return;
      }
      if (childPos.node.type.name === selector) {
        const doesAllAttributesMatch = attrKeys.every((key2) => attributes[key2] === childPos.node.attrs[key2]);
        if (doesAllAttributesMatch) {
          nodes.push(childPos);
        }
      }
      if (firstItemOnly && nodes.length > 0) {
        return;
      }
      nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly));
    });
    return nodes;
  }
  setAttribute(attributes) {
    const { tr: tr4 } = this.editor.state;
    tr4.setNodeMarkup(this.from, void 0, {
      ...this.node.attrs,
      ...attributes
    });
    this.editor.view.dispatch(tr4);
  }
};
var style = `.ProseMirror {
  position: relative;
}

.ProseMirror {
  word-wrap: break-word;
  white-space: pre-wrap;
  white-space: break-spaces;
  -webkit-font-variant-ligatures: none;
  font-variant-ligatures: none;
  font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
}

.ProseMirror [contenteditable="false"] {
  white-space: normal;
}

.ProseMirror [contenteditable="false"] [contenteditable="true"] {
  white-space: pre-wrap;
}

.ProseMirror pre {
  white-space: pre-wrap;
}

img.ProseMirror-separator {
  display: inline !important;
  border: none !important;
  margin: 0 !important;
  width: 0 !important;
  height: 0 !important;
}

.ProseMirror-gapcursor {
  display: none;
  pointer-events: none;
  position: absolute;
  margin: 0;
}

.ProseMirror-gapcursor:after {
  content: "";
  display: block;
  position: absolute;
  top: -2px;
  width: 20px;
  border-top: 1px solid black;
  animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
}

@keyframes ProseMirror-cursor-blink {
  to {
    visibility: hidden;
  }
}

.ProseMirror-hideselection *::selection {
  background: transparent;
}

.ProseMirror-hideselection *::-moz-selection {
  background: transparent;
}

.ProseMirror-hideselection * {
  caret-color: transparent;
}

.ProseMirror-focused .ProseMirror-gapcursor {
  display: block;
}`;
function createStyleTag(style22, nonce, suffix) {
  const tiptapStyleTag = document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ""}]`);
  if (tiptapStyleTag !== null) {
    return tiptapStyleTag;
  }
  const styleNode = document.createElement("style");
  if (nonce) {
    styleNode.setAttribute("nonce", nonce);
  }
  styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ""}`, "");
  styleNode.innerHTML = style22;
  document.getElementsByTagName("head")[0].appendChild(styleNode);
  return styleNode;
}
var Editor = class extends EventEmitter {
  constructor(options2 = {}) {
    super();
    this.css = null;
    this.className = "tiptap";
    this.editorView = null;
    this.isFocused = false;
    this.isInitialized = false;
    this.extensionStorage = {};
    this.instanceId = Math.random().toString(36).slice(2, 9);
    this.options = {
      element: typeof document !== "undefined" ? document.createElement("div") : null,
      content: "",
      injectCSS: true,
      injectNonce: void 0,
      extensions: [],
      autofocus: false,
      editable: true,
      textDirection: void 0,
      editorProps: {},
      parseOptions: {},
      coreExtensionOptions: {},
      enableInputRules: true,
      enablePasteRules: true,
      enableCoreExtensions: true,
      enableContentCheck: false,
      emitContentError: false,
      onBeforeCreate: () => null,
      onCreate: () => null,
      onMount: () => null,
      onUnmount: () => null,
      onUpdate: () => null,
      onSelectionUpdate: () => null,
      onTransaction: () => null,
      onFocus: () => null,
      onBlur: () => null,
      onDestroy: () => null,
      onContentError: ({ error: error2 }) => {
        throw error2;
      },
      onPaste: () => null,
      onDrop: () => null,
      onDelete: () => null
    };
    this.isCapturingTransaction = false;
    this.capturedTransaction = null;
    this.utils = {
      getUpdatedPosition,
      createMappablePosition
    };
    this.setOptions(options2);
    this.createExtensionManager();
    this.createCommandManager();
    this.createSchema();
    this.on("beforeCreate", this.options.onBeforeCreate);
    this.emit("beforeCreate", { editor: this });
    this.on("mount", this.options.onMount);
    this.on("unmount", this.options.onUnmount);
    this.on("contentError", this.options.onContentError);
    this.on("create", this.options.onCreate);
    this.on("update", this.options.onUpdate);
    this.on("selectionUpdate", this.options.onSelectionUpdate);
    this.on("transaction", this.options.onTransaction);
    this.on("focus", this.options.onFocus);
    this.on("blur", this.options.onBlur);
    this.on("destroy", this.options.onDestroy);
    this.on("drop", ({ event, slice: slice2, moved }) => this.options.onDrop(event, slice2, moved));
    this.on("paste", ({ event, slice: slice2 }) => this.options.onPaste(event, slice2));
    this.on("delete", this.options.onDelete);
    const initialDoc = this.createDoc();
    const selection = resolveFocusPosition(initialDoc, this.options.autofocus);
    this.editorState = EditorState.create({
      doc: initialDoc,
      schema: this.schema,
      selection: selection || void 0
    });
    if (this.options.element) {
      this.mount(this.options.element);
    }
  }
  /**
   * Attach the editor to the DOM, creating a new editor view.
   */
  mount(el2) {
    if (typeof document === "undefined") {
      throw new Error(
        `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`
      );
    }
    this.createView(el2);
    this.emit("mount", { editor: this });
    if (this.css && !document.head.contains(this.css)) {
      document.head.appendChild(this.css);
    }
    window.setTimeout(() => {
      if (this.isDestroyed) {
        return;
      }
      if (this.options.autofocus !== false && this.options.autofocus !== null) {
        this.commands.focus(this.options.autofocus);
      }
      this.emit("create", { editor: this });
      this.isInitialized = true;
    }, 0);
  }
  /**
   * Remove the editor from the DOM, but still allow remounting at a different point in time
   */
  unmount() {
    if (this.editorView) {
      const dom = this.editorView.dom;
      if (dom == null ? void 0 : dom.editor) {
        delete dom.editor;
      }
      this.editorView.destroy();
    }
    this.editorView = null;
    this.isInitialized = false;
    if (this.css && !document.querySelectorAll(`.${this.className}`).length) {
      try {
        if (typeof this.css.remove === "function") {
          this.css.remove();
        } else if (this.css.parentNode) {
          this.css.parentNode.removeChild(this.css);
        }
      } catch (error2) {
        console.warn("Failed to remove CSS element:", error2);
      }
    }
    this.css = null;
    this.emit("unmount", { editor: this });
  }
  /**
   * Returns the editor storage.
   */
  get storage() {
    return this.extensionStorage;
  }
  /**
   * An object of all registered commands.
   */
  get commands() {
    return this.commandManager.commands;
  }
  /**
   * Create a command chain to call multiple commands at once.
   */
  chain() {
    return this.commandManager.chain();
  }
  /**
   * Check if a command or a command chain can be executed. Without executing it.
   */
  can() {
    return this.commandManager.can();
  }
  /**
   * Inject CSS styles.
   */
  injectCSS() {
    if (this.options.injectCSS && typeof document !== "undefined") {
      this.css = createStyleTag(style, this.options.injectNonce);
    }
  }
  /**
   * Update editor options.
   *
   * @param options A list of options
   */
  setOptions(options2 = {}) {
    this.options = {
      ...this.options,
      ...options2
    };
    if (!this.editorView || !this.state || this.isDestroyed) {
      return;
    }
    if (this.options.editorProps) {
      this.view.setProps(this.options.editorProps);
    }
    this.view.updateState(this.state);
  }
  /**
   * Update editable state of the editor.
   */
  setEditable(editable, emitUpdate = true) {
    this.setOptions({ editable });
    if (emitUpdate) {
      this.emit("update", { editor: this, transaction: this.state.tr, appendedTransactions: [] });
    }
  }
  /**
   * Returns whether the editor is editable.
   */
  get isEditable() {
    return this.options.editable && this.view && this.view.editable;
  }
  /**
   * Returns the editor state.
   */
  get view() {
    if (this.editorView) {
      return this.editorView;
    }
    return new Proxy(
      {
        state: this.editorState,
        updateState: (state) => {
          this.editorState = state;
        },
        dispatch: (tr4) => {
          this.dispatchTransaction(tr4);
        },
        // Stub some commonly accessed properties to prevent errors
        composing: false,
        dragging: null,
        editable: true,
        isDestroyed: false
      },
      {
        get: (obj, key2) => {
          if (this.editorView) {
            return this.editorView[key2];
          }
          if (key2 === "state") {
            return this.editorState;
          }
          if (key2 in obj) {
            return Reflect.get(obj, key2);
          }
          throw new Error(
            `[tiptap error]: The editor view is not available. Cannot access view['${key2}']. The editor may not be mounted yet.`
          );
        }
      }
    );
  }
  /**
   * Returns the editor state.
   */
  get state() {
    if (this.editorView) {
      this.editorState = this.view.state;
    }
    return this.editorState;
  }
  /**
   * Register a ProseMirror plugin.
   *
   * @param plugin A ProseMirror plugin
   * @param handlePlugins Control how to merge the plugin into the existing plugins.
   * @returns The new editor state
   */
  registerPlugin(plugin, handlePlugins) {
    const plugins = isFunction(handlePlugins) ? handlePlugins(plugin, [...this.state.plugins]) : [...this.state.plugins, plugin];
    const state = this.state.reconfigure({ plugins });
    this.view.updateState(state);
    return state;
  }
  /**
   * Unregister a ProseMirror plugin.
   *
   * @param nameOrPluginKeyToRemove The plugins name
   * @returns The new editor state or undefined if the editor is destroyed
   */
  unregisterPlugin(nameOrPluginKeyToRemove) {
    if (this.isDestroyed) {
      return void 0;
    }
    const prevPlugins = this.state.plugins;
    let plugins = prevPlugins;
    [].concat(nameOrPluginKeyToRemove).forEach((nameOrPluginKey) => {
      const name = typeof nameOrPluginKey === "string" ? `${nameOrPluginKey}$` : nameOrPluginKey.key;
      plugins = plugins.filter((plugin) => !plugin.key.startsWith(name));
    });
    if (prevPlugins.length === plugins.length) {
      return void 0;
    }
    const state = this.state.reconfigure({
      plugins
    });
    this.view.updateState(state);
    return state;
  }
  /**
   * Creates an extension manager.
   */
  createExtensionManager() {
    var _a2, _b;
    const coreExtensions = this.options.enableCoreExtensions ? [
      Editable,
      ClipboardTextSerializer.configure({
        blockSeparator: (_b = (_a2 = this.options.coreExtensionOptions) == null ? void 0 : _a2.clipboardTextSerializer) == null ? void 0 : _b.blockSeparator
      }),
      Commands,
      FocusEvents,
      Keymap,
      Tabindex,
      Drop,
      Paste,
      Delete,
      TextDirection.configure({
        direction: this.options.textDirection
      })
    ].filter((ext) => {
      if (typeof this.options.enableCoreExtensions === "object") {
        return this.options.enableCoreExtensions[ext.name] !== false;
      }
      return true;
    }) : [];
    const allExtensions = [...coreExtensions, ...this.options.extensions].filter((extension2) => {
      return ["extension", "node", "mark"].includes(extension2 == null ? void 0 : extension2.type);
    });
    this.extensionManager = new ExtensionManager(allExtensions, this);
  }
  /**
   * Creates an command manager.
   */
  createCommandManager() {
    this.commandManager = new CommandManager({
      editor: this
    });
  }
  /**
   * Creates a ProseMirror schema.
   */
  createSchema() {
    this.schema = this.extensionManager.schema;
  }
  /**
   * Creates the initial document.
   */
  createDoc() {
    let doc4;
    try {
      doc4 = createDocument(this.options.content, this.schema, this.options.parseOptions, {
        errorOnInvalidContent: this.options.enableContentCheck
      });
    } catch (e2) {
      if (!(e2 instanceof Error) || !["[tiptap error]: Invalid JSON content", "[tiptap error]: Invalid HTML content"].includes(e2.message)) {
        throw e2;
      }
      this.emit("contentError", {
        editor: this,
        error: e2,
        disableCollaboration: () => {
          if ("collaboration" in this.storage && typeof this.storage.collaboration === "object" && this.storage.collaboration) {
            ;
            this.storage.collaboration.isDisabled = true;
          }
          this.options.extensions = this.options.extensions.filter((extension2) => extension2.name !== "collaboration");
          this.createExtensionManager();
        }
      });
      doc4 = createDocument(this.options.content, this.schema, this.options.parseOptions, {
        errorOnInvalidContent: false
      });
    }
    return doc4;
  }
  /**
   * Creates a ProseMirror view.
   */
  createView(element7) {
    var _a2;
    this.editorView = new EditorView(element7, {
      ...this.options.editorProps,
      attributes: {
        // add `role="textbox"` to the editor element
        role: "textbox",
        ...(_a2 = this.options.editorProps) == null ? void 0 : _a2.attributes
      },
      dispatchTransaction: this.dispatchTransaction.bind(this),
      state: this.editorState,
      markViews: this.extensionManager.markViews,
      nodeViews: this.extensionManager.nodeViews
    });
    const newState = this.state.reconfigure({
      plugins: this.extensionManager.plugins
    });
    this.view.updateState(newState);
    this.prependClass();
    this.injectCSS();
    const dom = this.view.dom;
    dom.editor = this;
  }
  /**
   * Creates all node and mark views.
   */
  createNodeViews() {
    if (this.view.isDestroyed) {
      return;
    }
    this.view.setProps({
      markViews: this.extensionManager.markViews,
      nodeViews: this.extensionManager.nodeViews
    });
  }
  /**
   * Prepend class name to element.
   */
  prependClass() {
    this.view.dom.className = `${this.className} ${this.view.dom.className}`;
  }
  captureTransaction(fn4) {
    this.isCapturingTransaction = true;
    fn4();
    this.isCapturingTransaction = false;
    const tr4 = this.capturedTransaction;
    this.capturedTransaction = null;
    return tr4;
  }
  /**
   * The callback over which to send transactions (state updates) produced by the view.
   *
   * @param transaction An editor state transaction
   */
  dispatchTransaction(transaction) {
    if (this.view.isDestroyed) {
      return;
    }
    if (this.isCapturingTransaction) {
      if (!this.capturedTransaction) {
        this.capturedTransaction = transaction;
        return;
      }
      transaction.steps.forEach((step) => {
        var _a2;
        return (_a2 = this.capturedTransaction) == null ? void 0 : _a2.step(step);
      });
      return;
    }
    const { state, transactions } = this.state.applyTransaction(transaction);
    const selectionHasChanged = !this.state.selection.eq(state.selection);
    const rootTrWasApplied = transactions.includes(transaction);
    const prevState = this.state;
    this.emit("beforeTransaction", {
      editor: this,
      transaction,
      nextState: state
    });
    if (!rootTrWasApplied) {
      return;
    }
    this.view.updateState(state);
    this.emit("transaction", {
      editor: this,
      transaction,
      appendedTransactions: transactions.slice(1)
    });
    if (selectionHasChanged) {
      this.emit("selectionUpdate", {
        editor: this,
        transaction
      });
    }
    const mostRecentFocusTr = transactions.findLast((tr4) => tr4.getMeta("focus") || tr4.getMeta("blur"));
    const focus2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("focus");
    const blur2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("blur");
    if (focus2) {
      this.emit("focus", {
        editor: this,
        event: focus2.event,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        transaction: mostRecentFocusTr
      });
    }
    if (blur2) {
      this.emit("blur", {
        editor: this,
        event: blur2.event,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        transaction: mostRecentFocusTr
      });
    }
    if (transaction.getMeta("preventUpdate") || !transactions.some((tr4) => tr4.docChanged) || prevState.doc.eq(state.doc)) {
      return;
    }
    this.emit("update", {
      editor: this,
      transaction,
      appendedTransactions: transactions.slice(1)
    });
  }
  /**
   * Get attributes of the currently selected node or mark.
   */
  getAttributes(nameOrType) {
    return getAttributes(this.state, nameOrType);
  }
  isActive(nameOrAttributes, attributesOrUndefined) {
    const name = typeof nameOrAttributes === "string" ? nameOrAttributes : null;
    const attributes = typeof nameOrAttributes === "string" ? attributesOrUndefined : nameOrAttributes;
    return isActive(this.state, name, attributes);
  }
  /**
   * Get the document as JSON.
   */
  getJSON() {
    return this.state.doc.toJSON();
  }
  /**
   * Get the document as HTML.
   */
  getHTML() {
    return getHTMLFromFragment(this.state.doc.content, this.schema);
  }
  /**
   * Get the document as text.
   */
  getText(options2) {
    const { blockSeparator = "\n\n", textSerializers = {} } = options2 || {};
    return getText2(this.state.doc, {
      blockSeparator,
      textSerializers: {
        ...getTextSerializersFromSchema(this.schema),
        ...textSerializers
      }
    });
  }
  /**
   * Check if there is no content.
   */
  get isEmpty() {
    return isNodeEmpty(this.state.doc);
  }
  /**
   * Destroy the editor.
   */
  destroy() {
    this.emit("destroy");
    this.unmount();
    this.removeAllListeners();
  }
  /**
   * Check if the editor is already destroyed.
   */
  get isDestroyed() {
    var _a2, _b;
    return (_b = (_a2 = this.editorView) == null ? void 0 : _a2.isDestroyed) != null ? _b : true;
  }
  $node(selector, attributes) {
    var _a2;
    return ((_a2 = this.$doc) == null ? void 0 : _a2.querySelector(selector, attributes)) || null;
  }
  $nodes(selector, attributes) {
    var _a2;
    return ((_a2 = this.$doc) == null ? void 0 : _a2.querySelectorAll(selector, attributes)) || null;
  }
  $pos(pos) {
    const $pos = this.state.doc.resolve(pos);
    return new NodePos($pos, this);
  }
  get $doc() {
    return this.$pos(0);
  }
};
function markInputRule(config) {
  return new InputRule({
    find: config.find,
    handler: ({ state, range, match: match2 }) => {
      const attributes = callOrReturn(config.getAttributes, void 0, match2);
      if (attributes === false || attributes === null) {
        return null;
      }
      const { tr: tr4 } = state;
      const captureGroup = match2[match2.length - 1];
      const fullMatch = match2[0];
      if (captureGroup) {
        const startSpaces = fullMatch.search(/\S/);
        const textStart = range.from + fullMatch.indexOf(captureGroup);
        const textEnd = textStart + captureGroup.length;
        const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => {
          const excluded = item.mark.type.excluded;
          return excluded.find((type) => type === config.type && type !== item.mark.type);
        }).filter((item) => item.to > textStart);
        if (excludedMarks.length) {
          return null;
        }
        if (textEnd < range.to) {
          tr4.delete(textEnd, range.to);
        }
        if (textStart > range.from) {
          tr4.delete(range.from + startSpaces, textStart);
        }
        const markEnd = range.from + startSpaces + captureGroup.length;
        tr4.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}));
        tr4.removeStoredMark(config.type);
      }
    },
    undoable: config.undoable
  });
}
var markdown_exports = {};
__export2(markdown_exports, {
  createAtomBlockMarkdownSpec: () => createAtomBlockMarkdownSpec,
  createBlockMarkdownSpec: () => createBlockMarkdownSpec,
  createInlineMarkdownSpec: () => createInlineMarkdownSpec,
  parseAttributes: () => parseAttributes,
  parseIndentedBlocks: () => parseIndentedBlocks,
  renderNestedMarkdownContent: () => renderNestedMarkdownContent,
  serializeAttributes: () => serializeAttributes
});
function parseAttributes(attrString) {
  if (!(attrString == null ? void 0 : attrString.trim())) {
    return {};
  }
  const attributes = {};
  const quotedStrings = [];
  const tempString = attrString.replace(/["']([^"']*)["']/g, (match2) => {
    quotedStrings.push(match2);
    return `__QUOTED_${quotedStrings.length - 1}__`;
  });
  const classMatches = tempString.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);
  if (classMatches) {
    const classes = classMatches.map((match2) => match2.trim().slice(1));
    attributes.class = classes.join(" ");
  }
  const idMatch = tempString.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);
  if (idMatch) {
    attributes.id = idMatch[1];
  }
  const kvRegex = /([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;
  const kvMatches = Array.from(tempString.matchAll(kvRegex));
  kvMatches.forEach(([, key2, quotedRef]) => {
    var _a2;
    const quotedIndex = parseInt(((_a2 = quotedRef.match(/__QUOTED_(\d+)__/)) == null ? void 0 : _a2[1]) || "0", 10);
    const quotedValue = quotedStrings[quotedIndex];
    if (quotedValue) {
      attributes[key2] = quotedValue.slice(1, -1);
    }
  });
  const cleanString = tempString.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g, "").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g, "").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g, "").trim();
  if (cleanString) {
    const booleanAttrs = cleanString.split(/\s+/).filter(Boolean);
    booleanAttrs.forEach((attr2) => {
      if (attr2.match(/^[a-zA-Z][\w-]*$/)) {
        attributes[attr2] = true;
      }
    });
  }
  return attributes;
}
function serializeAttributes(attributes) {
  if (!attributes || Object.keys(attributes).length === 0) {
    return "";
  }
  const parts = [];
  if (attributes.class) {
    const classes = String(attributes.class).split(/\s+/).filter(Boolean);
    classes.forEach((cls) => parts.push(`.${cls}`));
  }
  if (attributes.id) {
    parts.push(`#${attributes.id}`);
  }
  Object.entries(attributes).forEach(([key2, value]) => {
    if (key2 === "class" || key2 === "id") {
      return;
    }
    if (value === true) {
      parts.push(key2);
    } else if (value !== false && value != null) {
      parts.push(`${key2}="${String(value)}"`);
    }
  });
  return parts.join(" ");
}
function createAtomBlockMarkdownSpec(options2) {
  const {
    nodeName,
    name: markdownName,
    parseAttributes: parseAttributes2 = parseAttributes,
    serializeAttributes: serializeAttributes22 = serializeAttributes,
    defaultAttributes = {},
    requiredAttributes = [],
    allowedAttributes
  } = options2;
  const blockName = markdownName || nodeName;
  const filterAttributes = (attrs) => {
    if (!allowedAttributes) {
      return attrs;
    }
    const filtered = {};
    allowedAttributes.forEach((key2) => {
      if (key2 in attrs) {
        filtered[key2] = attrs[key2];
      }
    });
    return filtered;
  };
  return {
    parseMarkdown: (token, h22) => {
      const attrs = { ...defaultAttributes, ...token.attributes };
      return h22.createNode(nodeName, attrs, []);
    },
    markdownTokenizer: {
      name: nodeName,
      level: "block",
      start(src) {
        var _a2;
        const regex = new RegExp(`^:::${blockName}(?:\\s|$)`, "m");
        const index4 = (_a2 = src.match(regex)) == null ? void 0 : _a2.index;
        return index4 !== void 0 ? index4 : -1;
      },
      tokenize(src, _tokens, _lexer) {
        const regex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`);
        const match2 = src.match(regex);
        if (!match2) {
          return void 0;
        }
        const attrString = match2[1] || "";
        const attributes = parseAttributes2(attrString);
        const missingRequired = requiredAttributes.find((required) => !(required in attributes));
        if (missingRequired) {
          return void 0;
        }
        return {
          type: nodeName,
          raw: match2[0],
          attributes
        };
      }
    },
    renderMarkdown: (node2) => {
      const filteredAttrs = filterAttributes(node2.attrs || {});
      const attrs = serializeAttributes22(filteredAttrs);
      const attrString = attrs ? ` {${attrs}}` : "";
      return `:::${blockName}${attrString} :::`;
    }
  };
}
function createBlockMarkdownSpec(options2) {
  const {
    nodeName,
    name: markdownName,
    getContent,
    parseAttributes: parseAttributes2 = parseAttributes,
    serializeAttributes: serializeAttributes22 = serializeAttributes,
    defaultAttributes = {},
    content: content5 = "block",
    allowedAttributes
  } = options2;
  const blockName = markdownName || nodeName;
  const filterAttributes = (attrs) => {
    if (!allowedAttributes) {
      return attrs;
    }
    const filtered = {};
    allowedAttributes.forEach((key2) => {
      if (key2 in attrs) {
        filtered[key2] = attrs[key2];
      }
    });
    return filtered;
  };
  return {
    parseMarkdown: (token, h22) => {
      let nodeContent;
      if (getContent) {
        const contentResult = getContent(token);
        nodeContent = typeof contentResult === "string" ? [{ type: "text", text: contentResult }] : contentResult;
      } else if (content5 === "block") {
        nodeContent = h22.parseChildren(token.tokens || []);
      } else {
        nodeContent = h22.parseInline(token.tokens || []);
      }
      const attrs = { ...defaultAttributes, ...token.attributes };
      return h22.createNode(nodeName, attrs, nodeContent);
    },
    markdownTokenizer: {
      name: nodeName,
      level: "block",
      start(src) {
        var _a2;
        const regex = new RegExp(`^:::${blockName}`, "m");
        const index4 = (_a2 = src.match(regex)) == null ? void 0 : _a2.index;
        return index4 !== void 0 ? index4 : -1;
      },
      tokenize(src, _tokens, lexer) {
        var _a2;
        const openingRegex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*\\n`);
        const openingMatch = src.match(openingRegex);
        if (!openingMatch) {
          return void 0;
        }
        const [openingTag, attrString = ""] = openingMatch;
        const attributes = parseAttributes2(attrString);
        let level = 1;
        const position4 = openingTag.length;
        let matchedContent = "";
        const blockPattern = /^:::([\w-]*)(\s.*)?/gm;
        const remaining = src.slice(position4);
        blockPattern.lastIndex = 0;
        for (; ; ) {
          const match2 = blockPattern.exec(remaining);
          if (match2 === null) {
            break;
          }
          const matchPos = match2.index;
          const blockType = match2[1];
          if ((_a2 = match2[2]) == null ? void 0 : _a2.endsWith(":::")) {
            continue;
          }
          if (blockType) {
            level += 1;
          } else {
            level -= 1;
            if (level === 0) {
              const rawContent = remaining.slice(0, matchPos);
              matchedContent = rawContent.trim();
              const fullMatch = src.slice(0, position4 + matchPos + match2[0].length);
              let contentTokens = [];
              if (matchedContent) {
                if (content5 === "block") {
                  contentTokens = lexer.blockTokens(rawContent);
                  contentTokens.forEach((token) => {
                    if (token.text && (!token.tokens || token.tokens.length === 0)) {
                      token.tokens = lexer.inlineTokens(token.text);
                    }
                  });
                  while (contentTokens.length > 0) {
                    const lastToken = contentTokens[contentTokens.length - 1];
                    if (lastToken.type === "paragraph" && (!lastToken.text || lastToken.text.trim() === "")) {
                      contentTokens.pop();
                    } else {
                      break;
                    }
                  }
                } else {
                  contentTokens = lexer.inlineTokens(matchedContent);
                }
              }
              return {
                type: nodeName,
                raw: fullMatch,
                attributes,
                content: matchedContent,
                tokens: contentTokens
              };
            }
          }
        }
        return void 0;
      }
    },
    renderMarkdown: (node2, h22) => {
      const filteredAttrs = filterAttributes(node2.attrs || {});
      const attrs = serializeAttributes22(filteredAttrs);
      const attrString = attrs ? ` {${attrs}}` : "";
      const renderedContent = h22.renderChildren(node2.content || [], "\n\n");
      return `:::${blockName}${attrString}

${renderedContent}

:::`;
    }
  };
}
function parseShortcodeAttributes(attrString) {
  if (!attrString.trim()) {
    return {};
  }
  const attributes = {};
  const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g;
  let match2 = regex.exec(attrString);
  while (match2 !== null) {
    const [, key2, doubleQuoted, singleQuoted] = match2;
    attributes[key2] = doubleQuoted || singleQuoted;
    match2 = regex.exec(attrString);
  }
  return attributes;
}
function serializeShortcodeAttributes(attrs) {
  return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key2, value]) => `${key2}="${value}"`).join(" ");
}
function createInlineMarkdownSpec(options2) {
  const {
    nodeName,
    name: shortcodeName,
    getContent,
    parseAttributes: parseAttributes2 = parseShortcodeAttributes,
    serializeAttributes: serializeAttributes22 = serializeShortcodeAttributes,
    defaultAttributes = {},
    selfClosing = false,
    allowedAttributes
  } = options2;
  const shortcode = shortcodeName || nodeName;
  const filterAttributes = (attrs) => {
    if (!allowedAttributes) {
      return attrs;
    }
    const filtered = {};
    allowedAttributes.forEach((attr2) => {
      const attrName = typeof attr2 === "string" ? attr2 : attr2.name;
      const skipIfDefault = typeof attr2 === "string" ? void 0 : attr2.skipIfDefault;
      if (attrName in attrs) {
        const value = attrs[attrName];
        if (skipIfDefault !== void 0 && value === skipIfDefault) {
          return;
        }
        filtered[attrName] = value;
      }
    });
    return filtered;
  };
  const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return {
    parseMarkdown: (token, h22) => {
      const attrs = { ...defaultAttributes, ...token.attributes };
      if (selfClosing) {
        return h22.createNode(nodeName, attrs);
      }
      const content5 = getContent ? getContent(token) : token.content || "";
      if (content5) {
        return h22.createNode(nodeName, attrs, [h22.createTextNode(content5)]);
      }
      return h22.createNode(nodeName, attrs, []);
    },
    markdownTokenizer: {
      name: nodeName,
      level: "inline",
      start(src) {
        const startPattern = selfClosing ? new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\]`) : new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${escapedShortcode}\\]`);
        const match2 = src.match(startPattern);
        const index4 = match2 == null ? void 0 : match2.index;
        return index4 !== void 0 ? index4 : -1;
      },
      tokenize(src, _tokens, _lexer) {
        const tokenPattern = selfClosing ? new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]`) : new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${escapedShortcode}\\]`);
        const match2 = src.match(tokenPattern);
        if (!match2) {
          return void 0;
        }
        let content5 = "";
        let attrString = "";
        if (selfClosing) {
          const [, attrs] = match2;
          attrString = attrs;
        } else {
          const [, attrs, contentMatch] = match2;
          attrString = attrs;
          content5 = contentMatch || "";
        }
        const attributes = parseAttributes2(attrString.trim());
        return {
          type: nodeName,
          raw: match2[0],
          content: content5.trim(),
          attributes
        };
      }
    },
    renderMarkdown: (node2) => {
      let content5 = "";
      if (getContent) {
        content5 = getContent(node2);
      } else if (node2.content && node2.content.length > 0) {
        content5 = node2.content.filter((child) => child.type === "text").map((child) => child.text).join("");
      }
      const filteredAttrs = filterAttributes(node2.attrs || {});
      const attrs = serializeAttributes22(filteredAttrs);
      const attrString = attrs ? ` ${attrs}` : "";
      if (selfClosing) {
        return `[${shortcode}${attrString}]`;
      }
      return `[${shortcode}${attrString}]${content5}[/${shortcode}]`;
    }
  };
}
function parseIndentedBlocks(src, config, lexer) {
  var _a2, _b, _c, _d;
  const lines = src.split("\n");
  const items = [];
  let totalRaw = "";
  let i3 = 0;
  const baseIndentSize = config.baseIndentSize || 2;
  while (i3 < lines.length) {
    const currentLine = lines[i3];
    const itemMatch = currentLine.match(config.itemPattern);
    if (!itemMatch) {
      if (items.length > 0) {
        break;
      } else if (currentLine.trim() === "") {
        i3 += 1;
        totalRaw = `${totalRaw}${currentLine}
`;
        continue;
      } else {
        return void 0;
      }
    }
    const itemData = config.extractItemData(itemMatch);
    const { indentLevel, mainContent } = itemData;
    totalRaw = `${totalRaw}${currentLine}
`;
    const itemContent = [mainContent];
    i3 += 1;
    while (i3 < lines.length) {
      const nextLine = lines[i3];
      if (nextLine.trim() === "") {
        const nextNonEmptyIndex = lines.slice(i3 + 1).findIndex((l2) => l2.trim() !== "");
        if (nextNonEmptyIndex === -1) {
          break;
        }
        const nextNonEmpty = lines[i3 + 1 + nextNonEmptyIndex];
        const nextIndent2 = ((_b = (_a2 = nextNonEmpty.match(/^(\s*)/)) == null ? void 0 : _a2[1]) == null ? void 0 : _b.length) || 0;
        if (nextIndent2 > indentLevel) {
          itemContent.push(nextLine);
          totalRaw = `${totalRaw}${nextLine}
`;
          i3 += 1;
          continue;
        } else {
          break;
        }
      }
      const nextIndent = ((_d = (_c = nextLine.match(/^(\s*)/)) == null ? void 0 : _c[1]) == null ? void 0 : _d.length) || 0;
      if (nextIndent > indentLevel) {
        itemContent.push(nextLine);
        totalRaw = `${totalRaw}${nextLine}
`;
        i3 += 1;
      } else {
        break;
      }
    }
    let nestedTokens;
    const nestedContent = itemContent.slice(1);
    if (nestedContent.length > 0) {
      const dedentedNested = nestedContent.map((nestedLine) => nestedLine.slice(indentLevel + baseIndentSize)).join("\n");
      if (dedentedNested.trim()) {
        if (config.customNestedParser) {
          nestedTokens = config.customNestedParser(dedentedNested);
        } else {
          nestedTokens = lexer.blockTokens(dedentedNested);
        }
      }
    }
    const token = config.createToken(itemData, nestedTokens);
    items.push(token);
  }
  if (items.length === 0) {
    return void 0;
  }
  return {
    items,
    raw: totalRaw
  };
}
function renderNestedMarkdownContent(node2, h22, prefixOrGenerator, ctx) {
  if (!node2 || !Array.isArray(node2.content)) {
    return "";
  }
  const prefix3 = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator;
  const [content5, ...children] = node2.content;
  const mainContent = h22.renderChildren([content5]);
  const output = [`${prefix3}${mainContent}`];
  if (children && children.length > 0) {
    children.forEach((child) => {
      const childContent = h22.renderChildren([child]);
      if (childContent) {
        const indentedChild = childContent.split("\n").map((line) => line ? h22.indent(line) : "").join("\n");
        output.push(indentedChild);
      }
    });
  }
  return output.join("\n");
}
function updateMarkViewAttributes(checkMark, editor, attrs = {}) {
  const { state } = editor;
  const { doc: doc4, tr: tr4 } = state;
  const thisMark = checkMark;
  doc4.descendants((node2, pos) => {
    const from4 = tr4.mapping.map(pos);
    const to2 = tr4.mapping.map(pos) + node2.nodeSize;
    let foundMark = null;
    node2.marks.forEach((mark2) => {
      if (mark2 !== thisMark) {
        return false;
      }
      foundMark = mark2;
    });
    if (!foundMark) {
      return;
    }
    let needsUpdate = false;
    Object.keys(attrs).forEach((k3) => {
      if (attrs[k3] !== foundMark.attrs[k3]) {
        needsUpdate = true;
      }
    });
    if (needsUpdate) {
      const updatedMark = checkMark.type.create({
        ...checkMark.attrs,
        ...attrs
      });
      tr4.removeMark(from4, to2, checkMark.type);
      tr4.addMark(from4, to2, updatedMark);
    }
  });
  if (tr4.docChanged) {
    editor.view.dispatch(tr4);
  }
}
var MarkView = class {
  constructor(component, props, options2) {
    this.component = component;
    this.editor = props.editor;
    this.options = { ...options2 };
    this.mark = props.mark;
    this.HTMLAttributes = props.HTMLAttributes;
  }
  get dom() {
    return this.editor.view.dom;
  }
  get contentDOM() {
    return null;
  }
  /**
   * Update the attributes of the mark in the document.
   * @param attrs The attributes to update.
   */
  updateAttributes(attrs, checkMark) {
    updateMarkViewAttributes(checkMark || this.mark, this.editor, attrs);
  }
  ignoreMutation(mutation) {
    if (!this.dom || !this.contentDOM) {
      return true;
    }
    if (typeof this.options.ignoreMutation === "function") {
      return this.options.ignoreMutation({ mutation });
    }
    if (mutation.type === "selection") {
      return false;
    }
    if (this.dom.contains(mutation.target) && mutation.type === "childList" && (isiOS() || isAndroid()) && this.editor.isFocused) {
      const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)];
      if (changedNodes.every((node2) => node2.isContentEditable)) {
        return false;
      }
    }
    if (this.contentDOM === mutation.target && mutation.type === "attributes") {
      return true;
    }
    if (this.contentDOM.contains(mutation.target)) {
      return false;
    }
    return true;
  }
};
var Node3 = class _Node extends Extendable {
  constructor() {
    super(...arguments);
    this.type = "node";
  }
  /**
   * Create a new Node instance
   * @param config - Node configuration object or a function that returns a configuration object
   */
  static create(config = {}) {
    const resolvedConfig = typeof config === "function" ? config() : config;
    return new _Node(resolvedConfig);
  }
  configure(options2) {
    return super.configure(options2);
  }
  extend(extendedConfig) {
    const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
    return super.extend(resolvedConfig);
  }
};
var NodeView = class {
  constructor(component, props, options2) {
    this.isDragging = false;
    this.component = component;
    this.editor = props.editor;
    this.options = {
      stopEvent: null,
      ignoreMutation: null,
      ...options2
    };
    this.extension = props.extension;
    this.node = props.node;
    this.decorations = props.decorations;
    this.innerDecorations = props.innerDecorations;
    this.view = props.view;
    this.HTMLAttributes = props.HTMLAttributes;
    this.getPos = props.getPos;
    this.mount();
  }
  mount() {
    return;
  }
  get dom() {
    return this.editor.view.dom;
  }
  get contentDOM() {
    return null;
  }
  onDragStart(event) {
    var _a2, _b, _c, _d, _e4, _f, _g;
    const { view } = this.editor;
    const target = event.target;
    const dragHandle = target.nodeType === 3 ? (_a2 = target.parentElement) == null ? void 0 : _a2.closest("[data-drag-handle]") : target.closest("[data-drag-handle]");
    if (!this.dom || ((_b = this.contentDOM) == null ? void 0 : _b.contains(target)) || !dragHandle) {
      return;
    }
    let x5 = 0;
    let y3 = 0;
    if (this.dom !== dragHandle) {
      const domBox = this.dom.getBoundingClientRect();
      const handleBox = dragHandle.getBoundingClientRect();
      const offsetX = (_d = event.offsetX) != null ? _d : (_c = event.nativeEvent) == null ? void 0 : _c.offsetX;
      const offsetY = (_f = event.offsetY) != null ? _f : (_e4 = event.nativeEvent) == null ? void 0 : _e4.offsetY;
      x5 = handleBox.x - domBox.x + offsetX;
      y3 = handleBox.y - domBox.y + offsetY;
    }
    const clonedNode = this.dom.cloneNode(true);
    try {
      const domBox = this.dom.getBoundingClientRect();
      clonedNode.style.width = `${Math.round(domBox.width)}px`;
      clonedNode.style.height = `${Math.round(domBox.height)}px`;
      clonedNode.style.boxSizing = "border-box";
      clonedNode.style.pointerEvents = "none";
    } catch {
    }
    let dragImageWrapper = null;
    try {
      dragImageWrapper = document.createElement("div");
      dragImageWrapper.style.position = "absolute";
      dragImageWrapper.style.top = "-9999px";
      dragImageWrapper.style.left = "-9999px";
      dragImageWrapper.style.pointerEvents = "none";
      dragImageWrapper.appendChild(clonedNode);
      document.body.appendChild(dragImageWrapper);
      (_g = event.dataTransfer) == null ? void 0 : _g.setDragImage(clonedNode, x5, y3);
    } finally {
      if (dragImageWrapper) {
        setTimeout(() => {
          try {
            dragImageWrapper == null ? void 0 : dragImageWrapper.remove();
          } catch {
          }
        }, 0);
      }
    }
    const pos = this.getPos();
    if (typeof pos !== "number") {
      return;
    }
    const selection = NodeSelection.create(view.state.doc, pos);
    const transaction = view.state.tr.setSelection(selection);
    view.dispatch(transaction);
  }
  stopEvent(event) {
    var _a2;
    if (!this.dom) {
      return false;
    }
    if (typeof this.options.stopEvent === "function") {
      return this.options.stopEvent({ event });
    }
    const target = event.target;
    const isInElement = this.dom.contains(target) && !((_a2 = this.contentDOM) == null ? void 0 : _a2.contains(target));
    if (!isInElement) {
      return false;
    }
    const isDragEvent = event.type.startsWith("drag");
    const isDropEvent = event.type === "drop";
    const isInput = ["INPUT", "BUTTON", "SELECT", "TEXTAREA"].includes(target.tagName) || target.isContentEditable;
    if (isInput && !isDropEvent && !isDragEvent) {
      return true;
    }
    const { isEditable } = this.editor;
    const { isDragging } = this;
    const isDraggable = !!this.node.type.spec.draggable;
    const isSelectable = NodeSelection.isSelectable(this.node);
    const isCopyEvent = event.type === "copy";
    const isPasteEvent = event.type === "paste";
    const isCutEvent = event.type === "cut";
    const isClickEvent = event.type === "mousedown";
    if (!isDraggable && isSelectable && isDragEvent && event.target === this.dom) {
      event.preventDefault();
    }
    if (isDraggable && isDragEvent && !isDragging && event.target === this.dom) {
      event.preventDefault();
      return false;
    }
    if (isDraggable && isEditable && !isDragging && isClickEvent) {
      const dragHandle = target.closest("[data-drag-handle]");
      const isValidDragHandle = dragHandle && (this.dom === dragHandle || this.dom.contains(dragHandle));
      if (isValidDragHandle) {
        this.isDragging = true;
        document.addEventListener(
          "dragend",
          () => {
            this.isDragging = false;
          },
          { once: true }
        );
        document.addEventListener(
          "drop",
          () => {
            this.isDragging = false;
          },
          { once: true }
        );
        document.addEventListener(
          "mouseup",
          () => {
            this.isDragging = false;
          },
          { once: true }
        );
      }
    }
    if (isDragging || isDropEvent || isCopyEvent || isPasteEvent || isCutEvent || isClickEvent && isSelectable) {
      return false;
    }
    return true;
  }
  /**
   * Called when a DOM [mutation](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) or a selection change happens within the view.
   * @return `false` if the editor should re-read the selection or re-parse the range around the mutation
   * @return `true` if it can safely be ignored.
   */
  ignoreMutation(mutation) {
    if (!this.dom || !this.contentDOM) {
      return true;
    }
    if (typeof this.options.ignoreMutation === "function") {
      return this.options.ignoreMutation({ mutation });
    }
    if (this.node.isLeaf || this.node.isAtom) {
      return true;
    }
    if (mutation.type === "selection") {
      return false;
    }
    if (this.dom.contains(mutation.target) && mutation.type === "childList" && (isiOS() || isAndroid()) && this.editor.isFocused) {
      const changedNodes = [...Array.from(mutation.addedNodes), ...Array.from(mutation.removedNodes)];
      if (changedNodes.every((node2) => node2.isContentEditable)) {
        return false;
      }
    }
    if (this.contentDOM === mutation.target && mutation.type === "attributes") {
      return true;
    }
    if (this.contentDOM.contains(mutation.target)) {
      return false;
    }
    return true;
  }
  /**
   * Update the attributes of the prosemirror node.
   */
  updateAttributes(attributes) {
    this.editor.commands.command(({ tr: tr4 }) => {
      const pos = this.getPos();
      if (typeof pos !== "number") {
        return false;
      }
      tr4.setNodeMarkup(pos, void 0, {
        ...this.node.attrs,
        ...attributes
      });
      return true;
    });
  }
  /**
   * Delete the node.
   */
  deleteNode() {
    const from4 = this.getPos();
    if (typeof from4 !== "number") {
      return;
    }
    const to2 = from4 + this.node.nodeSize;
    this.editor.commands.deleteRange({ from: from4, to: to2 });
  }
};
function markPasteRule(config) {
  return new PasteRule({
    find: config.find,
    handler: ({ state, range, match: match2, pasteEvent }) => {
      const attributes = callOrReturn(config.getAttributes, void 0, match2, pasteEvent);
      if (attributes === false || attributes === null) {
        return null;
      }
      const { tr: tr4 } = state;
      const captureGroup = match2[match2.length - 1];
      const fullMatch = match2[0];
      let markEnd = range.to;
      if (captureGroup) {
        const startSpaces = fullMatch.search(/\S/);
        const textStart = range.from + fullMatch.indexOf(captureGroup);
        const textEnd = textStart + captureGroup.length;
        const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => {
          const excluded = item.mark.type.excluded;
          return excluded.find((type) => type === config.type && type !== item.mark.type);
        }).filter((item) => item.to > textStart);
        if (excludedMarks.length) {
          return null;
        }
        if (textEnd < range.to) {
          tr4.delete(textEnd, range.to);
        }
        if (textStart > range.from) {
          tr4.delete(range.from + startSpaces, textStart);
        }
        markEnd = range.from + startSpaces + captureGroup.length;
        tr4.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}));
        tr4.removeStoredMark(config.type);
      }
    }
  });
}

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/EventEmitter-CjSwpTbz.js
var h = Object.defineProperty;
var b = (a3, s2, l2) => s2 in a3 ? h(a3, s2, { enumerable: true, configurable: true, writable: true, value: l2 }) : a3[s2] = l2;
var t = (a3, s2, l2) => b(a3, typeof s2 != "symbol" ? s2 + "" : s2, l2);
var f3 = class {
  constructor() {
    t(this, "callbacks", {});
  }
  on(s2, l2) {
    return this.callbacks[s2] || (this.callbacks[s2] = []), this.callbacks[s2].push(l2), () => this.off(s2, l2);
  }
  emit(s2, ...l2) {
    const c3 = this.callbacks[s2];
    c3 && c3.forEach((i3) => i3.apply(this, l2));
  }
  off(s2, l2) {
    const c3 = this.callbacks[s2];
    c3 && (l2 ? this.callbacks[s2] = c3.filter((i3) => i3 !== l2) : delete this.callbacks[s2]);
  }
  removeAllListeners() {
    this.callbacks = {};
  }
};

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/rng.js
var getRandomValues2;
var rnds8 = new Uint8Array(16);
function rng() {
  if (!getRandomValues2) {
    getRandomValues2 = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== "undefined" && typeof msCrypto.getRandomValues === "function" && msCrypto.getRandomValues.bind(msCrypto);
    if (!getRandomValues2) {
      throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
    }
  }
  return getRandomValues2(rnds8);
}

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/regex.js
var regex_default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/validate.js
function validate(uuid) {
  return typeof uuid === "string" && regex_default.test(uuid);
}
var validate_default = validate;

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/stringify.js
var byteToHex = [];
for (i3 = 0; i3 < 256; ++i3) {
  byteToHex.push((i3 + 256).toString(16).substr(1));
}
var i3;
function stringify2(arr) {
  var offset4 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0;
  var uuid = (byteToHex[arr[offset4 + 0]] + byteToHex[arr[offset4 + 1]] + byteToHex[arr[offset4 + 2]] + byteToHex[arr[offset4 + 3]] + "-" + byteToHex[arr[offset4 + 4]] + byteToHex[arr[offset4 + 5]] + "-" + byteToHex[arr[offset4 + 6]] + byteToHex[arr[offset4 + 7]] + "-" + byteToHex[arr[offset4 + 8]] + byteToHex[arr[offset4 + 9]] + "-" + byteToHex[arr[offset4 + 10]] + byteToHex[arr[offset4 + 11]] + byteToHex[arr[offset4 + 12]] + byteToHex[arr[offset4 + 13]] + byteToHex[arr[offset4 + 14]] + byteToHex[arr[offset4 + 15]]).toLowerCase();
  if (!validate_default(uuid)) {
    throw TypeError("Stringified UUID is invalid");
  }
  return uuid;
}
var stringify_default = stringify2;

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/parse.js
function parse(uuid) {
  if (!validate_default(uuid)) {
    throw TypeError("Invalid UUID");
  }
  var v8;
  var arr = new Uint8Array(16);
  arr[0] = (v8 = parseInt(uuid.slice(0, 8), 16)) >>> 24;
  arr[1] = v8 >>> 16 & 255;
  arr[2] = v8 >>> 8 & 255;
  arr[3] = v8 & 255;
  arr[4] = (v8 = parseInt(uuid.slice(9, 13), 16)) >>> 8;
  arr[5] = v8 & 255;
  arr[6] = (v8 = parseInt(uuid.slice(14, 18), 16)) >>> 8;
  arr[7] = v8 & 255;
  arr[8] = (v8 = parseInt(uuid.slice(19, 23), 16)) >>> 8;
  arr[9] = v8 & 255;
  arr[10] = (v8 = parseInt(uuid.slice(24, 36), 16)) / 1099511627776 & 255;
  arr[11] = v8 / 4294967296 & 255;
  arr[12] = v8 >>> 24 & 255;
  arr[13] = v8 >>> 16 & 255;
  arr[14] = v8 >>> 8 & 255;
  arr[15] = v8 & 255;
  return arr;
}
var parse_default = parse;

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/v35.js
function stringToBytes(str) {
  str = unescape(encodeURIComponent(str));
  var bytes = [];
  for (var i3 = 0; i3 < str.length; ++i3) {
    bytes.push(str.charCodeAt(i3));
  }
  return bytes;
}
var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
var URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
function v35_default(name, version, hashfunc) {
  function generateUUID(value, namespace, buf, offset4) {
    if (typeof value === "string") {
      value = stringToBytes(value);
    }
    if (typeof namespace === "string") {
      namespace = parse_default(namespace);
    }
    if (namespace.length !== 16) {
      throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");
    }
    var bytes = new Uint8Array(16 + value.length);
    bytes.set(namespace);
    bytes.set(value, namespace.length);
    bytes = hashfunc(bytes);
    bytes[6] = bytes[6] & 15 | version;
    bytes[8] = bytes[8] & 63 | 128;
    if (buf) {
      offset4 = offset4 || 0;
      for (var i3 = 0; i3 < 16; ++i3) {
        buf[offset4 + i3] = bytes[i3];
      }
      return buf;
    }
    return stringify_default(bytes);
  }
  try {
    generateUUID.name = name;
  } catch (err) {
  }
  generateUUID.DNS = DNS;
  generateUUID.URL = URL2;
  return generateUUID;
}

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/md5.js
function md5(bytes) {
  if (typeof bytes === "string") {
    var msg = unescape(encodeURIComponent(bytes));
    bytes = new Uint8Array(msg.length);
    for (var i3 = 0; i3 < msg.length; ++i3) {
      bytes[i3] = msg.charCodeAt(i3);
    }
  }
  return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
}
function md5ToHexEncodedArray(input2) {
  var output = [];
  var length32 = input2.length * 32;
  var hexTab = "0123456789abcdef";
  for (var i3 = 0; i3 < length32; i3 += 8) {
    var x5 = input2[i3 >> 5] >>> i3 % 32 & 255;
    var hex = parseInt(hexTab.charAt(x5 >>> 4 & 15) + hexTab.charAt(x5 & 15), 16);
    output.push(hex);
  }
  return output;
}
function getOutputLength(inputLength8) {
  return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
}
function wordsToMd5(x5, len) {
  x5[len >> 5] |= 128 << len % 32;
  x5[getOutputLength(len) - 1] = len;
  var a3 = 1732584193;
  var b4 = -271733879;
  var c3 = -1732584194;
  var d = 271733878;
  for (var i3 = 0; i3 < x5.length; i3 += 16) {
    var olda = a3;
    var oldb = b4;
    var oldc = c3;
    var oldd = d;
    a3 = md5ff(a3, b4, c3, d, x5[i3], 7, -680876936);
    d = md5ff(d, a3, b4, c3, x5[i3 + 1], 12, -389564586);
    c3 = md5ff(c3, d, a3, b4, x5[i3 + 2], 17, 606105819);
    b4 = md5ff(b4, c3, d, a3, x5[i3 + 3], 22, -1044525330);
    a3 = md5ff(a3, b4, c3, d, x5[i3 + 4], 7, -176418897);
    d = md5ff(d, a3, b4, c3, x5[i3 + 5], 12, 1200080426);
    c3 = md5ff(c3, d, a3, b4, x5[i3 + 6], 17, -1473231341);
    b4 = md5ff(b4, c3, d, a3, x5[i3 + 7], 22, -45705983);
    a3 = md5ff(a3, b4, c3, d, x5[i3 + 8], 7, 1770035416);
    d = md5ff(d, a3, b4, c3, x5[i3 + 9], 12, -1958414417);
    c3 = md5ff(c3, d, a3, b4, x5[i3 + 10], 17, -42063);
    b4 = md5ff(b4, c3, d, a3, x5[i3 + 11], 22, -1990404162);
    a3 = md5ff(a3, b4, c3, d, x5[i3 + 12], 7, 1804603682);
    d = md5ff(d, a3, b4, c3, x5[i3 + 13], 12, -40341101);
    c3 = md5ff(c3, d, a3, b4, x5[i3 + 14], 17, -1502002290);
    b4 = md5ff(b4, c3, d, a3, x5[i3 + 15], 22, 1236535329);
    a3 = md5gg(a3, b4, c3, d, x5[i3 + 1], 5, -165796510);
    d = md5gg(d, a3, b4, c3, x5[i3 + 6], 9, -1069501632);
    c3 = md5gg(c3, d, a3, b4, x5[i3 + 11], 14, 643717713);
    b4 = md5gg(b4, c3, d, a3, x5[i3], 20, -373897302);
    a3 = md5gg(a3, b4, c3, d, x5[i3 + 5], 5, -701558691);
    d = md5gg(d, a3, b4, c3, x5[i3 + 10], 9, 38016083);
    c3 = md5gg(c3, d, a3, b4, x5[i3 + 15], 14, -660478335);
    b4 = md5gg(b4, c3, d, a3, x5[i3 + 4], 20, -405537848);
    a3 = md5gg(a3, b4, c3, d, x5[i3 + 9], 5, 568446438);
    d = md5gg(d, a3, b4, c3, x5[i3 + 14], 9, -1019803690);
    c3 = md5gg(c3, d, a3, b4, x5[i3 + 3], 14, -187363961);
    b4 = md5gg(b4, c3, d, a3, x5[i3 + 8], 20, 1163531501);
    a3 = md5gg(a3, b4, c3, d, x5[i3 + 13], 5, -1444681467);
    d = md5gg(d, a3, b4, c3, x5[i3 + 2], 9, -51403784);
    c3 = md5gg(c3, d, a3, b4, x5[i3 + 7], 14, 1735328473);
    b4 = md5gg(b4, c3, d, a3, x5[i3 + 12], 20, -1926607734);
    a3 = md5hh(a3, b4, c3, d, x5[i3 + 5], 4, -378558);
    d = md5hh(d, a3, b4, c3, x5[i3 + 8], 11, -2022574463);
    c3 = md5hh(c3, d, a3, b4, x5[i3 + 11], 16, 1839030562);
    b4 = md5hh(b4, c3, d, a3, x5[i3 + 14], 23, -35309556);
    a3 = md5hh(a3, b4, c3, d, x5[i3 + 1], 4, -1530992060);
    d = md5hh(d, a3, b4, c3, x5[i3 + 4], 11, 1272893353);
    c3 = md5hh(c3, d, a3, b4, x5[i3 + 7], 16, -155497632);
    b4 = md5hh(b4, c3, d, a3, x5[i3 + 10], 23, -1094730640);
    a3 = md5hh(a3, b4, c3, d, x5[i3 + 13], 4, 681279174);
    d = md5hh(d, a3, b4, c3, x5[i3], 11, -358537222);
    c3 = md5hh(c3, d, a3, b4, x5[i3 + 3], 16, -722521979);
    b4 = md5hh(b4, c3, d, a3, x5[i3 + 6], 23, 76029189);
    a3 = md5hh(a3, b4, c3, d, x5[i3 + 9], 4, -640364487);
    d = md5hh(d, a3, b4, c3, x5[i3 + 12], 11, -421815835);
    c3 = md5hh(c3, d, a3, b4, x5[i3 + 15], 16, 530742520);
    b4 = md5hh(b4, c3, d, a3, x5[i3 + 2], 23, -995338651);
    a3 = md5ii(a3, b4, c3, d, x5[i3], 6, -198630844);
    d = md5ii(d, a3, b4, c3, x5[i3 + 7], 10, 1126891415);
    c3 = md5ii(c3, d, a3, b4, x5[i3 + 14], 15, -1416354905);
    b4 = md5ii(b4, c3, d, a3, x5[i3 + 5], 21, -57434055);
    a3 = md5ii(a3, b4, c3, d, x5[i3 + 12], 6, 1700485571);
    d = md5ii(d, a3, b4, c3, x5[i3 + 3], 10, -1894986606);
    c3 = md5ii(c3, d, a3, b4, x5[i3 + 10], 15, -1051523);
    b4 = md5ii(b4, c3, d, a3, x5[i3 + 1], 21, -2054922799);
    a3 = md5ii(a3, b4, c3, d, x5[i3 + 8], 6, 1873313359);
    d = md5ii(d, a3, b4, c3, x5[i3 + 15], 10, -30611744);
    c3 = md5ii(c3, d, a3, b4, x5[i3 + 6], 15, -1560198380);
    b4 = md5ii(b4, c3, d, a3, x5[i3 + 13], 21, 1309151649);
    a3 = md5ii(a3, b4, c3, d, x5[i3 + 4], 6, -145523070);
    d = md5ii(d, a3, b4, c3, x5[i3 + 11], 10, -1120210379);
    c3 = md5ii(c3, d, a3, b4, x5[i3 + 2], 15, 718787259);
    b4 = md5ii(b4, c3, d, a3, x5[i3 + 9], 21, -343485551);
    a3 = safeAdd(a3, olda);
    b4 = safeAdd(b4, oldb);
    c3 = safeAdd(c3, oldc);
    d = safeAdd(d, oldd);
  }
  return [a3, b4, c3, d];
}
function bytesToWords(input2) {
  if (input2.length === 0) {
    return [];
  }
  var length8 = input2.length * 8;
  var output = new Uint32Array(getOutputLength(length8));
  for (var i3 = 0; i3 < length8; i3 += 8) {
    output[i3 >> 5] |= (input2[i3 / 8] & 255) << i3 % 32;
  }
  return output;
}
function safeAdd(x5, y3) {
  var lsw = (x5 & 65535) + (y3 & 65535);
  var msw = (x5 >> 16) + (y3 >> 16) + (lsw >> 16);
  return msw << 16 | lsw & 65535;
}
function bitRotateLeft(num, cnt) {
  return num << cnt | num >>> 32 - cnt;
}
function md5cmn(q4, a3, b4, x5, s2, t2) {
  return safeAdd(bitRotateLeft(safeAdd(safeAdd(a3, q4), safeAdd(x5, t2)), s2), b4);
}
function md5ff(a3, b4, c3, d, x5, s2, t2) {
  return md5cmn(b4 & c3 | ~b4 & d, a3, b4, x5, s2, t2);
}
function md5gg(a3, b4, c3, d, x5, s2, t2) {
  return md5cmn(b4 & d | c3 & ~d, a3, b4, x5, s2, t2);
}
function md5hh(a3, b4, c3, d, x5, s2, t2) {
  return md5cmn(b4 ^ c3 ^ d, a3, b4, x5, s2, t2);
}
function md5ii(a3, b4, c3, d, x5, s2, t2) {
  return md5cmn(c3 ^ (b4 | ~d), a3, b4, x5, s2, t2);
}
var md5_default = md5;

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/v3.js
var v3 = v35_default("v3", 48, md5_default);

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/v4.js
function v4(options2, buf, offset4) {
  options2 = options2 || {};
  var rnds = options2.random || (options2.rng || rng)();
  rnds[6] = rnds[6] & 15 | 64;
  rnds[8] = rnds[8] & 63 | 128;
  if (buf) {
    offset4 = offset4 || 0;
    for (var i3 = 0; i3 < 16; ++i3) {
      buf[offset4 + i3] = rnds[i3];
    }
    return buf;
  }
  return stringify_default(rnds);
}
var v4_default = v4;

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/sha1.js
function f4(s2, x5, y3, z2) {
  switch (s2) {
    case 0:
      return x5 & y3 ^ ~x5 & z2;
    case 1:
      return x5 ^ y3 ^ z2;
    case 2:
      return x5 & y3 ^ x5 & z2 ^ y3 & z2;
    case 3:
      return x5 ^ y3 ^ z2;
  }
}
function ROTL(x5, n) {
  return x5 << n | x5 >>> 32 - n;
}
function sha1(bytes) {
  var K6 = [1518500249, 1859775393, 2400959708, 3395469782];
  var H4 = [1732584193, 4023233417, 2562383102, 271733878, 3285377520];
  if (typeof bytes === "string") {
    var msg = unescape(encodeURIComponent(bytes));
    bytes = [];
    for (var i3 = 0; i3 < msg.length; ++i3) {
      bytes.push(msg.charCodeAt(i3));
    }
  } else if (!Array.isArray(bytes)) {
    bytes = Array.prototype.slice.call(bytes);
  }
  bytes.push(128);
  var l2 = bytes.length / 4 + 2;
  var N3 = Math.ceil(l2 / 16);
  var M7 = new Array(N3);
  for (var _i2 = 0; _i2 < N3; ++_i2) {
    var arr = new Uint32Array(16);
    for (var j4 = 0; j4 < 16; ++j4) {
      arr[j4] = bytes[_i2 * 64 + j4 * 4] << 24 | bytes[_i2 * 64 + j4 * 4 + 1] << 16 | bytes[_i2 * 64 + j4 * 4 + 2] << 8 | bytes[_i2 * 64 + j4 * 4 + 3];
    }
    M7[_i2] = arr;
  }
  M7[N3 - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
  M7[N3 - 1][14] = Math.floor(M7[N3 - 1][14]);
  M7[N3 - 1][15] = (bytes.length - 1) * 8 & 4294967295;
  for (var _i22 = 0; _i22 < N3; ++_i22) {
    var W3 = new Uint32Array(80);
    for (var t2 = 0; t2 < 16; ++t2) {
      W3[t2] = M7[_i22][t2];
    }
    for (var _t6 = 16; _t6 < 80; ++_t6) {
      W3[_t6] = ROTL(W3[_t6 - 3] ^ W3[_t6 - 8] ^ W3[_t6 - 14] ^ W3[_t6 - 16], 1);
    }
    var a3 = H4[0];
    var b4 = H4[1];
    var c3 = H4[2];
    var d = H4[3];
    var e2 = H4[4];
    for (var _t22 = 0; _t22 < 80; ++_t22) {
      var s2 = Math.floor(_t22 / 20);
      var T4 = ROTL(a3, 5) + f4(s2, b4, c3, d) + e2 + K6[s2] + W3[_t22] >>> 0;
      e2 = d;
      d = c3;
      c3 = ROTL(b4, 30) >>> 0;
      b4 = a3;
      a3 = T4;
    }
    H4[0] = H4[0] + a3 >>> 0;
    H4[1] = H4[1] + b4 >>> 0;
    H4[2] = H4[2] + c3 >>> 0;
    H4[3] = H4[3] + d >>> 0;
    H4[4] = H4[4] + e2 >>> 0;
  }
  return [H4[0] >> 24 & 255, H4[0] >> 16 & 255, H4[0] >> 8 & 255, H4[0] & 255, H4[1] >> 24 & 255, H4[1] >> 16 & 255, H4[1] >> 8 & 255, H4[1] & 255, H4[2] >> 24 & 255, H4[2] >> 16 & 255, H4[2] >> 8 & 255, H4[2] & 255, H4[3] >> 24 & 255, H4[3] >> 16 & 255, H4[3] >> 8 & 255, H4[3] & 255, H4[4] >> 24 & 255, H4[4] >> 16 & 255, H4[4] >> 8 & 255, H4[4] & 255];
}
var sha1_default = sha1;

// ../../node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/esm-browser/v5.js
var v5 = v35_default("v5", 80, sha1_default);

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/comments.js
var x = Object.defineProperty;
var Y = (r4, d, e2) => d in r4 ? x(r4, d, { enumerable: true, configurable: true, writable: true, value: e2 }) : r4[d] = e2;
var c = (r4, d, e2) => Y(r4, typeof d != "symbol" ? d + "" : d, e2);
var M = Mark2.create({
  name: "comment",
  excludes: "",
  inclusive: false,
  keepOnSplit: true,
  addAttributes() {
    return {
      // orphans are marks that currently don't have an active thread. It could be
      // that users have resolved the thread. Resolved threads by default are not shown in the document,
      // but we need to keep the mark (positioning) data so we can still "revive" it when the thread is unresolved
      // or we enter a "comments" view that includes resolved threads.
      orphan: {
        parseHTML: (r4) => !!r4.getAttribute("data-orphan"),
        renderHTML: (r4) => r4.orphan ? {
          "data-orphan": "true"
        } : {},
        default: false
      },
      threadId: {
        parseHTML: (r4) => r4.getAttribute("data-bn-thread-id"),
        renderHTML: (r4) => ({
          "data-bn-thread-id": r4.threadId
        }),
        default: ""
      }
    };
  },
  renderHTML({ HTMLAttributes: r4 }) {
    return [
      "span",
      mergeAttributes(r4, {
        class: "bn-thread-mark"
      })
    ];
  },
  parseHTML() {
    return [{ tag: "span.bn-thread-mark" }];
  },
  extendMarkSchema(r4) {
    return r4.name === "comment" ? {
      blocknoteIgnore: true
    } : {};
  }
});
var F = class extends f3 {
  constructor(e2) {
    super();
    c(this, "userCache", /* @__PURE__ */ new Map());
    c(this, "loadingUsers", /* @__PURE__ */ new Set());
    this.resolveUsers = e2;
  }
  /**
   * Load information about users based on an array of user ids.
   */
  async loadUsers(e2) {
    const t2 = e2.filter(
      (a3) => !this.userCache.has(a3) && !this.loadingUsers.has(a3)
    );
    if (t2.length !== 0) {
      for (const a3 of t2)
        this.loadingUsers.add(a3);
      try {
        const a3 = await this.resolveUsers(t2);
        for (const s2 of a3)
          this.userCache.set(s2.id, s2);
        this.emit("update", this.userCache);
      } finally {
        for (const a3 of t2)
          this.loadingUsers.delete(a3);
      }
    }
  }
  /**
   * Retrieve information about a user based on their id, if cached.
   *
   * The user will have to be loaded via `loadUsers` first
   */
  getUser(e2) {
    return this.userCache.get(e2);
  }
  /**
   * Subscribe to changes in the user store.
   *
   * @param cb - The callback to call when the user store changes.
   * @returns A function to unsubscribe from the user store.
   */
  subscribe(e2) {
    return this.on("update", e2);
  }
};
var w = new PluginKey("blocknote-comments");
function K2(r4, d) {
  const e2 = /* @__PURE__ */ new Map();
  return r4.descendants((t2, a3) => {
    t2.marks.forEach((s2) => {
      if (s2.type.name === d) {
        const o2 = s2.attrs.threadId;
        if (!o2)
          return;
        const m2 = a3, n = m2 + t2.nodeSize, i3 = e2.get(o2) ?? {
          from: 1 / 0,
          to: 0
        };
        e2.set(o2, {
          from: Math.min(m2, i3.from),
          to: Math.max(n, i3.to)
        });
      }
    });
  }), e2;
}
var ne = a(
  ({
    editor: r4,
    options: { schema: d, threadStore: e2, resolveUsers: t2 }
  }) => {
    if (!t2)
      throw new Error(
        "resolveUsers is required to be defined when using comments"
      );
    if (!e2)
      throw new Error(
        "threadStore is required to be defined when using comments"
      );
    const a3 = M.name, s2 = new F(t2), o2 = f(
      {
        pendingComment: false,
        selectedThreadId: void 0,
        threadPositions: /* @__PURE__ */ new Map()
      },
      {
        onUpdate() {
          o2.state.selectedThreadId !== o2.prevState.selectedThreadId && r4.transact((n) => n.setMeta(w, true));
        }
      }
    ), m2 = (n) => {
      r4.transact((i3) => {
        i3.doc.descendants((u2, l2) => {
          u2.marks.forEach((h7) => {
            if (h7.type.name === a3) {
              const T4 = h7.type, f6 = h7.attrs.threadId, A4 = n.get(f6), v8 = !!(!A4 || A4.resolved || A4.deletedAt);
              if (v8 !== h7.attrs.orphan) {
                const E4 = Math.max(l2, 0), b4 = Math.min(
                  l2 + u2.nodeSize,
                  i3.doc.content.size - 1,
                  i3.doc.content.size - 1
                );
                i3.removeMark(E4, b4, h7), i3.addMark(
                  E4,
                  b4,
                  T4.create({
                    ...h7.attrs,
                    orphan: v8
                  })
                ), v8 && o2.state.selectedThreadId === f6 && o2.setState((P4) => ({
                  ...P4,
                  selectedThreadId: void 0
                }));
              }
            }
          });
        });
      });
    };
    return {
      key: "comments",
      store: o2,
      prosemirrorPlugins: [
        new Plugin({
          key: w,
          state: {
            init() {
              return {
                decorations: DecorationSet.empty
              };
            },
            apply(n, i3) {
              const u2 = n.getMeta(w);
              if (!n.docChanged && !u2)
                return i3;
              const l2 = n.docChanged ? K2(n.doc, a3) : o2.state.threadPositions;
              (l2.size > 0 || o2.state.threadPositions.size > 0) && o2.setState((T4) => ({
                ...T4,
                threadPositions: l2
              }));
              const h7 = [];
              if (o2.state.selectedThreadId) {
                const T4 = l2.get(
                  o2.state.selectedThreadId
                );
                T4 && h7.push(
                  Decoration.inline(
                    T4.from,
                    T4.to,
                    {
                      class: "bn-thread-mark-selected"
                    }
                  )
                );
              }
              return {
                decorations: DecorationSet.create(n.doc, h7)
              };
            }
          },
          props: {
            decorations(n) {
              var i3;
              return ((i3 = w.getState(n)) == null ? void 0 : i3.decorations) ?? DecorationSet.empty;
            },
            handleClick: (n, i3, u2) => {
              if (u2.button !== 0)
                return;
              const l2 = n.state.doc.nodeAt(i3);
              if (!l2) {
                o2.setState((f6) => ({
                  ...f6,
                  selectedThreadId: void 0
                }));
                return;
              }
              const h7 = l2.marks.find(
                (f6) => f6.type.name === a3 && f6.attrs.orphan !== true
              ), T4 = h7 == null ? void 0 : h7.attrs.threadId;
              T4 !== o2.state.selectedThreadId && o2.setState((f6) => ({
                ...f6,
                selectedThreadId: T4
              }));
            }
          }
        })
      ],
      threadStore: e2,
      mount() {
        const n = e2.subscribe(m2);
        m2(e2.getThreads());
        const i3 = r4.onSelectionChange(() => {
          o2.state.pendingComment && o2.setState((u2) => ({
            ...u2,
            pendingComment: false
          }));
        });
        return () => {
          n(), i3();
        };
      },
      selectThread(n, i3 = true) {
        var u2, l2;
        if (o2.state.selectedThreadId !== n && (o2.setState((h7) => ({
          ...h7,
          pendingComment: false,
          selectedThreadId: n
        })), n && i3)) {
          const h7 = o2.state.threadPositions.get(n);
          if (!h7)
            return;
          (l2 = (u2 = r4.prosemirrorView) == null ? void 0 : u2.domAtPos(h7.from).node) == null || l2.scrollIntoView({
            behavior: "smooth",
            block: "center"
          });
        }
      },
      startPendingComment() {
        var n;
        o2.setState((i3) => ({
          ...i3,
          selectedThreadId: void 0,
          pendingComment: true
        })), (n = r4.getExtension(f2)) == null || n.showSelection(true);
      },
      stopPendingComment() {
        var n;
        o2.setState((i3) => ({
          ...i3,
          selectedThreadId: void 0,
          pendingComment: false
        })), (n = r4.getExtension(f2)) == null || n.showSelection(false);
      },
      async createThread(n) {
        const i3 = await e2.createThread(n);
        if (e2.addThreadToDocument) {
          const u2 = r4.prosemirrorView, l2 = u2.state.selection, h7 = ySyncPluginKey.getState(u2.state), T4 = {
            prosemirror: {
              head: l2.head,
              anchor: l2.anchor
            },
            yjs: h7 ? getRelativeSelection(h7.binding, u2.state) : void 0
          };
          await e2.addThreadToDocument({
            threadId: i3.id,
            selection: T4
          });
        } else
          r4._tiptapEditor.commands.setMark(a3, {
            orphan: false,
            threadId: i3.id
          });
      },
      userStore: s2,
      commentEditorSchema: d,
      tiptapExtensions: [M]
    };
  }
);

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/TrailingNode-8cXFaQUm.js
var import_fast_deep_equal = __toESM(require_fast_deep_equal(), 1);

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/blockToNode-BNoNIXU7.js
function pt(t2, o2 = JSON.stringify) {
  const r4 = {};
  return t2.filter((n) => {
    const e2 = o2(n);
    return Object.prototype.hasOwnProperty.call(r4, e2) ? false : r4[e2] = true;
  });
}
function dt(t2) {
  const o2 = t2.filter(
    (n, e2) => t2.indexOf(n) !== e2
  );
  return pt(o2);
}
var Q = Extension.create({
  name: "uniqueID",
  // we’ll set a very high priority to make sure this runs first
  // and is compatible with `appendTransaction` hooks of other extensions
  priority: 1e4,
  addOptions() {
    return {
      attributeName: "id",
      types: [],
      setIdAttribute: false,
      generateID: () => {
        if (typeof window < "u" && window.__TEST_OPTIONS) {
          const t2 = window.__TEST_OPTIONS;
          return t2.mockID === void 0 ? t2.mockID = 0 : t2.mockID++, t2.mockID.toString();
        }
        return v4_default();
      },
      filterTransaction: null
    };
  },
  addGlobalAttributes() {
    return [
      {
        types: this.options.types,
        attributes: {
          [this.options.attributeName]: {
            default: null,
            parseHTML: (t2) => t2.getAttribute(`data-${this.options.attributeName}`),
            renderHTML: (t2) => {
              const o2 = {
                [`data-${this.options.attributeName}`]: t2[this.options.attributeName]
              };
              return this.options.setIdAttribute ? {
                ...o2,
                id: t2[this.options.attributeName]
              } : o2;
            }
          }
        }
      }
    ];
  },
  // check initial content for missing ids
  // onCreate() {
  //   // Don’t do this when the collaboration extension is active
  //   // because this may update the content, so Y.js tries to merge these changes.
  //   // This leads to empty block nodes.
  //   // See: https://github.com/ueberdosis/tiptap/issues/2400
  //   if (
  //     this.editor.extensionManager.extensions.find(
  //       (extension) => extension.name === "collaboration"
  //     )
  //   ) {
  //     return;
  //   }
  //   const { view, state } = this.editor;
  //   const { tr, doc } = state;
  //   const { types, attributeName, generateID } = this.options;
  //   const nodesWithoutId = findChildren(doc, (node) => {
  //     return (
  //       types.includes(node.type.name) && node.attrs[attributeName] === null
  //     );
  //   });
  //   nodesWithoutId.forEach(({ node, pos }) => {
  //     tr.setNodeMarkup(pos, undefined, {
  //       ...node.attrs,
  //       [attributeName]: generateID(),
  //     });
  //   });
  //   tr.setMeta("addToHistory", false);
  //   view.dispatch(tr);
  // },
  addProseMirrorPlugins() {
    let t2 = null, o2 = false;
    return [
      new Plugin({
        key: new PluginKey("uniqueID"),
        appendTransaction: (r4, n, e2) => {
          const s2 = r4.some((g) => g.docChanged) && !n.doc.eq(e2.doc), i3 = this.options.filterTransaction && r4.some((g) => {
            var C3, d;
            return !((d = (C3 = this.options).filterTransaction) != null && d.call(C3, g));
          });
          if (!s2 || i3)
            return;
          const { tr: l2 } = e2, { types: a3, attributeName: c3, generateID: h7 } = this.options, f6 = combineTransactionSteps(
            n.doc,
            r4
          ), { mapping: p4 } = f6;
          if (getChangedRanges(f6).forEach(({ newRange: g }) => {
            const C3 = findChildrenInRange(
              e2.doc,
              g,
              (y3) => a3.includes(y3.type.name)
            ), d = C3.map(({ node: y3 }) => y3.attrs[c3]).filter((y3) => y3 !== null), w3 = dt(d);
            C3.forEach(({ node: y3, pos: m2 }) => {
              var z2;
              const b4 = (z2 = l2.doc.nodeAt(m2)) == null ? void 0 : z2.attrs[c3];
              if (b4 === null) {
                const U5 = n.doc.type.createAndFill().content;
                if (n.doc.content.findDiffStart(U5) === null) {
                  const q4 = JSON.parse(
                    JSON.stringify(e2.doc.toJSON())
                  );
                  if (q4.content[0].content[0].attrs.id = "initialBlockId", JSON.stringify(q4.content) === JSON.stringify(U5.toJSON())) {
                    l2.setNodeMarkup(m2, void 0, {
                      ...y3.attrs,
                      [c3]: "initialBlockId"
                    });
                    return;
                  }
                }
                l2.setNodeMarkup(m2, void 0, {
                  ...y3.attrs,
                  [c3]: h7()
                });
                return;
              }
              const { deleted: k3 } = p4.invert().mapResult(m2);
              k3 && w3.includes(b4) && l2.setNodeMarkup(m2, void 0, {
                ...y3.attrs,
                [c3]: h7()
              });
            });
          }), !!l2.steps.length)
            return l2.setMeta("uniqueID", true), l2;
        },
        // we register a global drag handler to track the current drag source element
        view(r4) {
          const n = (e2) => {
            let s2;
            t2 = !((s2 = r4.dom.parentElement) === null || s2 === void 0) && s2.contains(e2.target) ? r4.dom.parentElement : null;
          };
          return window.addEventListener("dragstart", n), {
            destroy() {
              window.removeEventListener("dragstart", n);
            }
          };
        },
        props: {
          // `handleDOMEvents` is called before `transformPasted` so we can do
          // some checks before. However, `transformPasted` only runs when
          // editor content is pasted - not external content.
          handleDOMEvents: {
            // only create new ids for dropped content while holding `alt`
            // or content is dragged from another editor
            drop: (r4, n) => {
              let e2;
              return t2 !== r4.dom.parentElement || ((e2 = n.dataTransfer) === null || e2 === void 0 ? void 0 : e2.effectAllowed) === "copy" ? o2 = true : o2 = false, t2 = null, false;
            },
            // always create new ids on pasted content
            paste: () => (o2 = true, false)
          },
          // we’ll remove ids for every pasted node
          // so we can create a new one within `appendTransaction`
          transformPasted: (r4) => {
            if (!o2)
              return r4;
            const { types: n, attributeName: e2 } = this.options, s2 = (i3) => {
              const l2 = [];
              return i3.forEach((a3) => {
                if (a3.isText) {
                  l2.push(a3);
                  return;
                }
                if (!n.includes(a3.type.name)) {
                  l2.push(a3.copy(s2(a3.content)));
                  return;
                }
                const c3 = a3.type.create(
                  {
                    ...a3.attrs,
                    [e2]: null
                  },
                  s2(a3.content),
                  a3.marks
                );
                l2.push(c3);
              }), Fragment.from(l2);
            };
            return o2 = false, new Slice(
              s2(r4.content),
              r4.openStart,
              r4.openEnd
            );
          }
        }
      })
    ];
  }
});
function K3(t2) {
  return t2.type === "link";
}
function X(t2) {
  return typeof t2 != "string" && t2.type === "link";
}
function B(t2) {
  return typeof t2 != "string" && t2.type === "text";
}
function S(t2) {
  var o2, r4, n, e2, s2;
  return R(t2) ? { ...t2 } : v(t2) ? {
    type: "tableCell",
    content: [].concat(t2.content),
    props: {
      backgroundColor: ((o2 = t2.props) == null ? void 0 : o2.backgroundColor) ?? "default",
      textColor: ((r4 = t2.props) == null ? void 0 : r4.textColor) ?? "default",
      textAlignment: ((n = t2.props) == null ? void 0 : n.textAlignment) ?? "left",
      colspan: ((e2 = t2.props) == null ? void 0 : e2.colspan) ?? 1,
      rowspan: ((s2 = t2.props) == null ? void 0 : s2.rowspan) ?? 1
    }
  } : {
    type: "tableCell",
    content: [].concat(t2),
    props: {
      backgroundColor: "default",
      textColor: "default",
      textAlignment: "left",
      colspan: 1,
      rowspan: 1
    }
  };
}
function v(t2) {
  return t2 != null && typeof t2 != "string" && !Array.isArray(t2) && t2.type === "tableCell";
}
function R(t2) {
  return v(t2) && t2.props !== void 0 && t2.content !== void 0;
}
function A(t2) {
  return R(t2) ? t2.props.colspan ?? 1 : 1;
}
function D(t2) {
  return R(t2) ? t2.props.rowspan ?? 1 : 1;
}
var O = class extends Error {
  constructor(o2) {
    super(`Unreachable case: ${o2}`);
  }
};
function At(t2, o2 = true) {
  const { "data-test": r4, ...n } = t2;
  if (Object.keys(n).length > 0 && o2)
    throw new Error("Object must be empty " + JSON.stringify(t2));
}
function Y2(t2, o2) {
  const r4 = t2.resolve(o2);
  if (r4.nodeAfter && r4.nodeAfter.type.isInGroup("bnBlock"))
    return {
      posBeforeNode: r4.pos,
      node: r4.nodeAfter
    };
  let n = r4.depth, e2 = r4.node(n);
  for (; n > 0; ) {
    if (e2.type.isInGroup("bnBlock"))
      return {
        posBeforeNode: r4.before(n),
        node: e2
      };
    n--, e2 = r4.node(n);
  }
  const s2 = [];
  t2.descendants((l2, a3) => {
    l2.type.isInGroup("bnBlock") && s2.push(a3);
  }), console.warn(`Position ${o2} is not within a blockContainer node.`);
  const i3 = t2.resolve(
    s2.find((l2) => l2 >= o2) || s2[s2.length - 1]
  );
  return {
    posBeforeNode: i3.pos,
    node: i3.nodeAfter
  };
}
function $2(t2, o2) {
  if (!t2.type.isInGroup("bnBlock"))
    throw new Error(
      `Attempted to get bnBlock node at position but found node of different type ${t2.type.name}`
    );
  const r4 = t2, n = o2, e2 = n + r4.nodeSize, s2 = {
    node: r4,
    beforePos: n,
    afterPos: e2
  };
  if (r4.type.name === "blockContainer") {
    let i3, l2;
    if (r4.forEach((a3, c3) => {
      if (a3.type.spec.group === "blockContent") {
        const h7 = a3, f6 = n + c3 + 1, p4 = f6 + a3.nodeSize;
        i3 = {
          node: h7,
          beforePos: f6,
          afterPos: p4
        };
      } else if (a3.type.name === "blockGroup") {
        const h7 = a3, f6 = n + c3 + 1, p4 = f6 + a3.nodeSize;
        l2 = {
          node: h7,
          beforePos: f6,
          afterPos: p4
        };
      }
    }), !i3)
      throw new Error(
        `blockContainer node does not contain a blockContent node in its children: ${r4}`
      );
    return {
      isBlockContainer: true,
      bnBlock: s2,
      blockContent: i3,
      childContainer: l2,
      blockNoteType: i3.node.type.name
    };
  } else {
    if (!s2.node.type.isInGroup("childContainer"))
      throw new Error(
        `bnBlock node is not in the childContainer group: ${s2.node}`
      );
    return {
      isBlockContainer: false,
      bnBlock: s2,
      childContainer: s2,
      blockNoteType: s2.node.type.name
    };
  }
}
function Z(t2) {
  return $2(t2.node, t2.posBeforeNode);
}
function It(t2) {
  if (!t2.nodeAfter)
    throw new Error(
      `Attempted to get blockContainer node at position ${t2.pos} but a node at this position does not exist`
    );
  return $2(t2.nodeAfter, t2.pos);
}
function Tt(t2) {
  const o2 = Y2(t2.doc, t2.selection.anchor);
  return Z(o2);
}
function Ot(t2) {
  const o2 = Y2(t2.doc, t2.selection.anchor);
  return Z(o2);
}
function ht(t2) {
  return "doc" in t2 ? t2.doc.type.schema : t2.type.schema;
}
function G(t2) {
  return t2.cached.blockNoteEditor;
}
function J(t2) {
  return G(t2).schema;
}
function _(t2) {
  return J(t2).blockSchema;
}
function H(t2) {
  return J(t2).inlineContentSchema;
}
function N(t2) {
  return J(t2).styleSchema;
}
function j(t2) {
  return G(t2).blockCache;
}
function gt(t2, o2, r4) {
  var s2, i3;
  const n = {
    type: "tableContent",
    columnWidths: [],
    headerRows: void 0,
    headerCols: void 0,
    rows: []
  }, e2 = [];
  t2.content.forEach((l2, a3, c3) => {
    const h7 = {
      cells: []
    };
    c3 === 0 && l2.content.forEach((f6) => {
      let p4 = f6.attrs.colwidth;
      p4 == null && (p4 = new Array(f6.attrs.colspan ?? 1).fill(void 0)), n.columnWidths.push(...p4);
    }), h7.cells = l2.content.content.map((f6, p4) => (e2[c3] || (e2[c3] = []), e2[c3][p4] = f6.type.name === "tableHeader", {
      type: "tableCell",
      content: f6.content.content.map(
        (g) => F2(g, o2, r4)
      ).reduce(
        (g, C3) => {
          if (!g.length)
            return C3;
          const d = g[g.length - 1], w3 = C3[0];
          return w3 && B(d) && B(w3) && JSON.stringify(d.styles) === JSON.stringify(w3.styles) ? (d.text += `
` + w3.text, g.push(...C3.slice(1)), g) : (g.push(...C3), g);
        },
        []
      ),
      props: {
        colspan: f6.attrs.colspan,
        rowspan: f6.attrs.rowspan,
        backgroundColor: f6.attrs.backgroundColor,
        textColor: f6.attrs.textColor,
        textAlignment: f6.attrs.textAlignment
      }
    })), n.rows.push(h7);
  });
  for (let l2 = 0; l2 < e2.length; l2++)
    (s2 = e2[l2]) != null && s2.every((a3) => a3) && (n.headerRows = (n.headerRows ?? 0) + 1);
  for (let l2 = 0; l2 < ((i3 = e2[0]) == null ? void 0 : i3.length); l2++)
    e2 != null && e2.every((a3) => a3[l2]) && (n.headerCols = (n.headerCols ?? 0) + 1);
  return n;
}
function F2(t2, o2, r4) {
  const n = [];
  let e2;
  return t2.content.forEach((s2) => {
    if (s2.type.name === "hardBreak") {
      if (e2)
        if (B(e2))
          e2.text += `
`;
        else if (K3(e2))
          e2.content[e2.content.length - 1].text += `
`;
        else
          throw new Error("unexpected");
      else
        e2 = {
          type: "text",
          text: `
`,
          styles: {}
        };
      return;
    }
    if (s2.type.name !== "link" && s2.type.name !== "text") {
      if (!o2[s2.type.name]) {
        console.warn("unrecognized inline content type", s2.type.name);
        return;
      }
      e2 && (n.push(e2), e2 = void 0), n.push(
        wt(s2, o2, r4)
      );
      return;
    }
    const i3 = {};
    let l2;
    for (const a3 of s2.marks)
      if (a3.type.name === "link")
        l2 = a3;
      else {
        const c3 = r4[a3.type.name];
        if (!c3) {
          if (a3.type.spec.blocknoteIgnore)
            continue;
          throw new Error(`style ${a3.type.name} not found in styleSchema`);
        }
        if (c3.propSchema === "boolean")
          i3[c3.type] = true;
        else if (c3.propSchema === "string")
          i3[c3.type] = a3.attrs.stringValue;
        else
          throw new O(c3.propSchema);
      }
    e2 ? B(e2) ? l2 ? (n.push(e2), e2 = {
      type: "link",
      href: l2.attrs.href,
      content: [
        {
          type: "text",
          text: s2.textContent,
          styles: i3
        }
      ]
    }) : JSON.stringify(e2.styles) === JSON.stringify(i3) ? e2.text += s2.textContent : (n.push(e2), e2 = {
      type: "text",
      text: s2.textContent,
      styles: i3
    }) : K3(e2) && (l2 ? e2.href === l2.attrs.href ? JSON.stringify(
      e2.content[e2.content.length - 1].styles
    ) === JSON.stringify(i3) ? e2.content[e2.content.length - 1].text += s2.textContent : e2.content.push({
      type: "text",
      text: s2.textContent,
      styles: i3
    }) : (n.push(e2), e2 = {
      type: "link",
      href: l2.attrs.href,
      content: [
        {
          type: "text",
          text: s2.textContent,
          styles: i3
        }
      ]
    }) : (n.push(e2), e2 = {
      type: "text",
      text: s2.textContent,
      styles: i3
    })) : l2 ? e2 = {
      type: "link",
      href: l2.attrs.href,
      content: [
        {
          type: "text",
          text: s2.textContent,
          styles: i3
        }
      ]
    } : e2 = {
      type: "text",
      text: s2.textContent,
      styles: i3
    };
  }), e2 && n.push(e2), n;
}
function wt(t2, o2, r4) {
  if (t2.type.name === "text" || t2.type.name === "link")
    throw new Error("unexpected");
  const n = {}, e2 = o2[t2.type.name];
  for (const [l2, a3] of Object.entries(t2.attrs)) {
    if (!e2)
      throw Error("ic node is of an unrecognized type: " + t2.type.name);
    const c3 = e2.propSchema;
    l2 in c3 && (n[l2] = a3);
  }
  let s2;
  return e2.content === "styled" ? s2 = F2(
    t2,
    o2,
    r4
  ) : s2 = void 0, {
    type: t2.type.name,
    props: n,
    content: s2
  };
}
function L(t2, o2, r4 = _(o2), n = H(o2), e2 = N(o2), s2 = j(o2)) {
  var C3;
  if (!t2.type.isInGroup("bnBlock"))
    throw Error("Node should be a bnBlock, but is instead: " + t2.type.name);
  const i3 = s2 == null ? void 0 : s2.get(t2);
  if (i3)
    return i3;
  const l2 = $2(t2, 0);
  let a3 = l2.bnBlock.node.attrs.id;
  a3 === null && (a3 = Q.options.generateID());
  const c3 = r4[l2.blockNoteType];
  if (!c3)
    throw Error("Block is of an unrecognized type: " + l2.blockNoteType);
  const h7 = {};
  for (const [d, w3] of Object.entries({
    ...t2.attrs,
    ...l2.isBlockContainer ? l2.blockContent.node.attrs : {}
  })) {
    const y3 = c3.propSchema;
    d in y3 && !(y3[d].default === void 0 && w3 === void 0) && (h7[d] = w3);
  }
  const f6 = r4[l2.blockNoteType], p4 = [];
  (C3 = l2.childContainer) == null || C3.node.forEach((d) => {
    p4.push(
      L(
        d,
        o2,
        r4,
        n,
        e2,
        s2
      )
    );
  });
  let u2;
  if (f6.content === "inline") {
    if (!l2.isBlockContainer)
      throw new Error("impossible");
    u2 = F2(
      l2.blockContent.node,
      n,
      e2
    );
  } else if (f6.content === "table") {
    if (!l2.isBlockContainer)
      throw new Error("impossible");
    u2 = gt(
      l2.blockContent.node,
      n,
      e2
    );
  } else if (f6.content === "none")
    u2 = void 0;
  else
    throw new O(f6.content);
  const g = {
    id: a3,
    type: f6.type,
    props: h7,
    content: u2,
    children: p4
  };
  return s2 == null || s2.set(t2, g), g;
}
function St(t2, o2 = ht(t2), r4 = _(o2), n = H(o2), e2 = N(o2), s2 = j(o2)) {
  const i3 = [];
  return t2.firstChild && t2.firstChild.descendants((l2) => (i3.push(
    L(
      l2,
      o2,
      r4,
      n,
      e2,
      s2
    )
  ), false)), i3;
}
function Dt(t2, o2, r4 = _(o2), n = H(o2), e2 = N(o2), s2 = j(o2)) {
  function i3(l2, a3, c3) {
    if (l2.type.name !== "blockGroup")
      throw new Error("unexpected");
    const h7 = [];
    let f6, p4;
    return l2.forEach((u2, g, C3) => {
      if (u2.type.name !== "blockContainer")
        throw new Error("unexpected");
      if (u2.childCount === 0)
        return;
      if (u2.childCount === 0 || u2.childCount > 2)
        throw new Error(
          "unexpected, blockContainer.childCount: " + u2.childCount
        );
      const d = C3 === 0, w3 = C3 === l2.childCount - 1;
      if (u2.firstChild.type.name === "blockGroup") {
        if (!d)
          throw new Error("unexpected");
        const k3 = i3(
          u2.firstChild,
          Math.max(0, a3 - 1),
          w3 ? Math.max(0, c3 - 1) : 0
        );
        f6 = k3.blockCutAtStart, w3 && (p4 = k3.blockCutAtEnd), h7.push(...k3.blocks);
        return;
      }
      const y3 = L(
        u2,
        o2,
        r4,
        n,
        e2,
        s2
      ), m2 = u2.childCount > 1 ? u2.child(1) : void 0;
      let b4 = [];
      if (m2) {
        const k3 = i3(
          m2,
          0,
          // TODO: can this be anything other than 0?
          w3 ? Math.max(0, c3 - 1) : 0
        );
        b4 = k3.blocks, w3 && (p4 = k3.blockCutAtEnd);
      }
      w3 && !m2 && c3 > 1 && (p4 = y3.id), d && a3 > 1 && (f6 = y3.id), h7.push({
        ...y3,
        children: b4
      });
    }), { blocks: h7, blockCutAtStart: f6, blockCutAtEnd: p4 };
  }
  if (t2.content.childCount === 0)
    return {
      blocks: [],
      blockCutAtStart: void 0,
      blockCutAtEnd: void 0
    };
  if (t2.content.childCount !== 1)
    throw new Error(
      "slice must be a single block, did you forget includeParents=true?"
    );
  return i3(
    t2.content.firstChild,
    Math.max(t2.openStart - 1, 0),
    Math.max(t2.openEnd - 1, 0)
  );
}
function x2(t2) {
  const { height: o2, width: r4 } = tt(t2), n = new Array(o2).fill(false).map(() => new Array(r4).fill(null)), e2 = (s2, i3) => {
    for (let l2 = s2; l2 < o2; l2++)
      for (let a3 = i3; a3 < r4; a3++)
        if (!n[l2][a3])
          return { row: l2, col: a3 };
    throw new Error(
      "Unable to create occupancy grid for table, no more available cells"
    );
  };
  for (let s2 = 0; s2 < t2.content.rows.length; s2++)
    for (let i3 = 0; i3 < t2.content.rows[s2].cells.length; i3++) {
      const l2 = S(t2.content.rows[s2].cells[i3]), a3 = D(l2), c3 = A(l2), { row: h7, col: f6 } = e2(s2, i3);
      for (let p4 = h7; p4 < h7 + a3; p4++)
        for (let u2 = f6; u2 < f6 + c3; u2++) {
          if (n[p4][u2])
            throw new Error(
              `Unable to create occupancy grid for table, cell at ${p4},${u2} is already occupied`
            );
          n[p4][u2] = {
            row: s2,
            col: i3,
            rowspan: a3,
            colspan: c3,
            cell: l2
          };
        }
    }
  return n;
}
function I(t2) {
  const o2 = /* @__PURE__ */ new Set();
  return t2.map((r4) => ({
    cells: r4.map((n) => o2.has(n.row + ":" + n.col) ? false : (o2.add(n.row + ":" + n.col), n.cell)).filter((n) => n !== false)
  }));
}
function E(t2, o2, r4 = x2(o2)) {
  for (let n = 0; n < r4.length; n++)
    for (let e2 = 0; e2 < r4[n].length; e2++) {
      const s2 = r4[n][e2];
      if (s2 && s2.row === t2.row && s2.col === t2.col)
        return { row: n, col: e2, cell: s2.cell };
    }
  throw new Error(
    `Unable to resolve relative table cell indices for table, cell at ${t2.row},${t2.col} is not occupied`
  );
}
function tt(t2) {
  const o2 = t2.content.rows.length;
  let r4 = 0;
  return t2.content.rows.forEach((n) => {
    let e2 = 0;
    n.cells.forEach((s2) => {
      e2 += A(s2);
    }), r4 = Math.max(r4, e2);
  }), { height: o2, width: r4 };
}
function et(t2, o2, r4 = x2(o2)) {
  var e2;
  const n = (e2 = r4[t2.row]) == null ? void 0 : e2[t2.col];
  if (n)
    return {
      row: n.row,
      col: n.col,
      cell: n.cell
    };
}
function yt(t2, o2) {
  var s2;
  const r4 = x2(t2);
  if (o2 < 0 || o2 >= r4.length)
    return [];
  let n = 0;
  for (let i3 = 0; i3 < o2; i3++) {
    const l2 = (s2 = r4[n]) == null ? void 0 : s2[0];
    if (!l2)
      return [];
    n += l2.rowspan;
  }
  const e2 = new Array(r4[0].length).fill(false).map((i3, l2) => et(
    { row: n, col: l2 },
    t2,
    r4
  )).filter(
    (i3) => i3 !== void 0
  );
  return e2.filter((i3, l2) => e2.findIndex((a3) => a3.row === i3.row && a3.col === i3.col) === l2);
}
function Ct(t2, o2) {
  var s2;
  const r4 = x2(t2);
  if (o2 < 0 || o2 >= r4[0].length)
    return [];
  let n = 0;
  for (let i3 = 0; i3 < o2; i3++) {
    const l2 = (s2 = r4[0]) == null ? void 0 : s2[n];
    if (!l2)
      return [];
    n += l2.colspan;
  }
  const e2 = new Array(r4.length).fill(false).map((i3, l2) => et(
    { row: l2, col: n },
    t2,
    r4
  )).filter(
    (i3) => i3 !== void 0
  );
  return e2.filter((i3, l2) => e2.findIndex((a3) => a3.row === i3.row && a3.col === i3.col) === l2);
}
function Mt(t2, o2, r4, n = x2(t2)) {
  const { col: e2 } = E(
    {
      row: 0,
      col: o2
    },
    t2,
    n
  ), { col: s2 } = E(
    {
      row: 0,
      col: r4
    },
    t2,
    n
  );
  return n.forEach((i3) => {
    const [l2] = i3.splice(e2, 1);
    i3.splice(s2, 0, l2);
  }), I(n);
}
function Pt(t2, o2, r4, n = x2(t2)) {
  const { row: e2 } = E(
    {
      row: o2,
      col: 0
    },
    t2,
    n
  ), { row: s2 } = E(
    {
      row: r4,
      col: 0
    },
    t2,
    n
  ), [i3] = n.splice(e2, 1);
  return n.splice(s2, 0, i3), I(n);
}
function M2(t2) {
  return t2 ? v(t2) ? M2(t2.content) : typeof t2 == "string" ? t2.length === 0 : Array.isArray(t2) ? t2.every(
    (o2) => typeof o2 == "string" ? o2.length === 0 : B(o2) ? o2.text.length === 0 : X(o2) ? typeof o2.content == "string" ? o2.content.length === 0 : o2.content.every((r4) => r4.text.length === 0) : false
  ) : false : true;
}
function Rt(t2, o2, r4 = x2(t2)) {
  if (o2 === "columns") {
    let s2 = 0;
    for (let i3 = r4[0].length - 1; i3 >= 0 && r4.every(
      (a3) => M2(a3[i3].cell) && a3[i3].colspan === 1
    ); i3--)
      s2++;
    for (let i3 = r4.length - 1; i3 >= 0; i3--) {
      const l2 = Math.max(
        r4[i3].length - s2,
        1
      );
      r4[i3] = r4[i3].slice(0, l2);
    }
    return I(r4);
  }
  let n = 0;
  for (let s2 = r4.length - 1; s2 >= 0 && r4[s2].every(
    (l2) => M2(l2.cell) && l2.rowspan === 1
  ); s2--)
    n++;
  const e2 = Math.min(n, r4.length - 1);
  return r4.splice(r4.length - e2, e2), I(r4);
}
function $t(t2, o2, r4, n = x2(t2)) {
  const { width: e2, height: s2 } = tt(t2);
  if (o2 === "columns")
    n.forEach((i3, l2) => {
      if (r4 >= 0)
        for (let a3 = 0; a3 < r4; a3++)
          i3.push({
            row: l2,
            col: Math.max(...i3.map((c3) => c3.col)) + 1,
            rowspan: 1,
            colspan: 1,
            cell: S("")
          });
      else
        i3.splice(e2 + r4, -1 * r4);
    });
  else if (r4 > 0)
    for (let i3 = 0; i3 < r4; i3++) {
      const l2 = new Array(e2).fill(null).map((a3, c3) => ({
        row: s2 + i3,
        col: c3,
        rowspan: 1,
        colspan: 1,
        cell: S("")
      }));
      n.push(l2);
    }
  else r4 < 0 && n.splice(s2 + r4, -1 * r4);
  return I(n);
}
function Jt(t2, o2, r4) {
  const n = yt(t2, r4);
  if (!n.some((a3) => D(a3.cell) > 1))
    return true;
  let s2 = r4, i3 = r4;
  return n.forEach((a3) => {
    const c3 = D(a3.cell);
    s2 = Math.max(s2, a3.row + c3 - 1), i3 = Math.min(i3, a3.row);
  }), o2 < r4 ? r4 === s2 : r4 === i3;
}
function _t2(t2, o2, r4) {
  const n = Ct(t2, r4);
  if (!n.some((a3) => A(a3.cell) > 1))
    return true;
  let s2 = r4, i3 = r4;
  return n.forEach((a3) => {
    const c3 = A(a3.cell);
    s2 = Math.max(s2, a3.col + c3 - 1), i3 = Math.min(i3, a3.col);
  }), o2 < r4 ? r4 === s2 : r4 === i3;
}
function Ht(t2, o2, r4) {
  const n = E(t2, r4), e2 = E(o2, r4);
  return n.col === e2.col;
}
function V(t2, o2, r4, n) {
  const e2 = [];
  for (const [i3, l2] of Object.entries(t2.styles || {})) {
    const a3 = r4[i3];
    if (!a3)
      throw new Error(`style ${i3} not found in styleSchema`);
    if (a3.propSchema === "boolean")
      l2 && e2.push(o2.mark(i3));
    else if (a3.propSchema === "string")
      l2 && e2.push(o2.mark(i3, { stringValue: l2 }));
    else
      throw new O(a3.propSchema);
  }
  return !n || !o2.nodes[n].spec.code ? t2.text.split(/(\n)/g).filter((i3) => i3.length > 0).map((i3) => i3 === `
` ? o2.nodes.hardBreak.createChecked() : o2.text(i3, e2)) : t2.text.length > 0 ? [o2.text(t2.text, e2)] : [];
}
function mt(t2, o2, r4) {
  const n = o2.marks.link.create({
    href: t2.href
  });
  return P(t2.content, o2, r4).map(
    (e2) => {
      if (e2.type.name === "text")
        return e2.mark([...e2.marks, n]);
      if (e2.type.name === "hardBreak")
        return e2;
      throw new Error("unexpected node type");
    }
  );
}
function P(t2, o2, r4, n) {
  const e2 = [];
  if (typeof t2 == "string")
    return e2.push(
      ...V(
        { text: t2, styles: {} },
        o2,
        r4,
        n
      )
    ), e2;
  for (const s2 of t2)
    e2.push(
      ...V(s2, o2, r4, n)
    );
  return e2;
}
function T(t2, o2, r4, n = N(o2)) {
  const e2 = [];
  for (const s2 of t2)
    typeof s2 == "string" ? e2.push(
      ...P(s2, o2, n, r4)
    ) : X(s2) ? e2.push(...mt(s2, o2, n)) : B(s2) ? e2.push(
      ...P([s2], o2, n, r4)
    ) : e2.push(
      nt(s2, o2, n)
    );
  return e2;
}
function kt(t2, o2, r4 = N(o2)) {
  const n = [], e2 = new Array(t2.headerRows ?? 0).fill(true), s2 = new Array(t2.headerCols ?? 0).fill(true), i3 = t2.columnWidths ?? [];
  for (let l2 = 0; l2 < t2.rows.length; l2++) {
    const a3 = t2.rows[l2], c3 = [], h7 = e2[l2];
    for (let p4 = 0; p4 < a3.cells.length; p4++) {
      const u2 = a3.cells[p4], g = s2[p4], C3 = void 0;
      let d = null;
      const w3 = E(
        {
          row: l2,
          col: p4
        },
        { content: t2 }
      );
      let y3 = i3[w3.col] ? [i3[w3.col]] : null;
      if (u2) if (typeof u2 == "string")
        d = o2.text(u2);
      else if (v(u2)) {
        u2.content && (d = T(
          u2.content,
          o2,
          "tableParagraph",
          r4
        ));
        const b4 = A(u2);
        b4 > 1 && (y3 = new Array(b4).fill(false).map((k3, W3) => i3[w3.col + W3] ?? void 0));
      } else
        d = T(
          u2,
          o2,
          "tableParagraph",
          r4
        );
      const m2 = o2.nodes[g || h7 ? "tableHeader" : "tableCell"].createChecked(
        {
          ...v(u2) ? u2.props : {},
          colwidth: y3
        },
        o2.nodes.tableParagraph.createChecked(C3, d)
      );
      c3.push(m2);
    }
    const f6 = o2.nodes.tableRow.createChecked({}, c3);
    n.push(f6);
  }
  return n;
}
function nt(t2, o2, r4) {
  let n, e2 = t2.type;
  if (e2 === void 0 && (e2 = "paragraph"), !o2.nodes[e2])
    throw new Error(`node type ${e2} not found in schema`);
  if (!t2.content)
    n = o2.nodes[e2].createChecked(t2.props);
  else if (typeof t2.content == "string") {
    const s2 = T(
      [t2.content],
      o2,
      e2,
      r4
    );
    n = o2.nodes[e2].createChecked(t2.props, s2);
  } else if (Array.isArray(t2.content)) {
    const s2 = T(
      t2.content,
      o2,
      e2,
      r4
    );
    n = o2.nodes[e2].createChecked(t2.props, s2);
  } else if (t2.content.type === "tableContent") {
    const s2 = kt(t2.content, o2, r4);
    n = o2.nodes[e2].createChecked(t2.props, s2);
  } else
    throw new O(t2.content.type);
  return n;
}
function bt(t2, o2, r4 = N(o2)) {
  let n = t2.id;
  n === void 0 && (n = Q.options.generateID());
  const e2 = [];
  if (t2.children)
    for (const i3 of t2.children)
      e2.push(bt(i3, o2, r4));
  if (!t2.type || // can happen if block.type is not defined (this should create the default node)
  o2.nodes[t2.type].isInGroup("blockContent")) {
    const i3 = nt(
      t2,
      o2,
      r4
    ), l2 = e2.length > 0 ? o2.nodes.blockGroup.createChecked({}, e2) : void 0;
    return o2.nodes.blockContainer.createChecked(
      {
        id: n,
        ...t2.props
      },
      l2 ? [i3, l2] : i3
    );
  } else {
    if (o2.nodes[t2.type].isInGroup("bnBlock"))
      return o2.nodes[t2.type].createChecked(
        {
          id: n,
          ...t2.props
        },
        e2
      );
    throw new Error(
      `block type ${t2.type} doesn't match blockContent or bnBlock group`
    );
  }
}

// ../../node_modules/.pnpm/prosemirror-tables@1.8.5/node_modules/prosemirror-tables/dist/index.js
var readFromCache;
var addToCache;
if (typeof WeakMap != "undefined") {
  let cache = /* @__PURE__ */ new WeakMap();
  readFromCache = (key2) => cache.get(key2);
  addToCache = (key2, value) => {
    cache.set(key2, value);
    return value;
  };
} else {
  const cache = [];
  const cacheSize = 10;
  let cachePos = 0;
  readFromCache = (key2) => {
    for (let i3 = 0; i3 < cache.length; i3 += 2) if (cache[i3] == key2) return cache[i3 + 1];
  };
  addToCache = (key2, value) => {
    if (cachePos == cacheSize) cachePos = 0;
    cache[cachePos++] = key2;
    return cache[cachePos++] = value;
  };
}
var TableMap = class {
  constructor(width, height, map7, problems) {
    this.width = width;
    this.height = height;
    this.map = map7;
    this.problems = problems;
  }
  findCell(pos) {
    for (let i3 = 0; i3 < this.map.length; i3++) {
      const curPos = this.map[i3];
      if (curPos != pos) continue;
      const left = i3 % this.width;
      const top = i3 / this.width | 0;
      let right = left + 1;
      let bottom = top + 1;
      for (let j4 = 1; right < this.width && this.map[i3 + j4] == curPos; j4++) right++;
      for (let j4 = 1; bottom < this.height && this.map[i3 + this.width * j4] == curPos; j4++) bottom++;
      return {
        left,
        top,
        right,
        bottom
      };
    }
    throw new RangeError(`No cell with offset ${pos} found`);
  }
  colCount(pos) {
    for (let i3 = 0; i3 < this.map.length; i3++) if (this.map[i3] == pos) return i3 % this.width;
    throw new RangeError(`No cell with offset ${pos} found`);
  }
  nextCell(pos, axis, dir) {
    const { left, right, top, bottom } = this.findCell(pos);
    if (axis == "horiz") {
      if (dir < 0 ? left == 0 : right == this.width) return null;
      return this.map[top * this.width + (dir < 0 ? left - 1 : right)];
    } else {
      if (dir < 0 ? top == 0 : bottom == this.height) return null;
      return this.map[left + this.width * (dir < 0 ? top - 1 : bottom)];
    }
  }
  rectBetween(a3, b4) {
    const { left: leftA, right: rightA, top: topA, bottom: bottomA } = this.findCell(a3);
    const { left: leftB, right: rightB, top: topB, bottom: bottomB } = this.findCell(b4);
    return {
      left: Math.min(leftA, leftB),
      top: Math.min(topA, topB),
      right: Math.max(rightA, rightB),
      bottom: Math.max(bottomA, bottomB)
    };
  }
  cellsInRect(rect) {
    const result = [];
    const seen = {};
    for (let row2 = rect.top; row2 < rect.bottom; row2++) for (let col = rect.left; col < rect.right; col++) {
      const index4 = row2 * this.width + col;
      const pos = this.map[index4];
      if (seen[pos]) continue;
      seen[pos] = true;
      if (col == rect.left && col && this.map[index4 - 1] == pos || row2 == rect.top && row2 && this.map[index4 - this.width] == pos) continue;
      result.push(pos);
    }
    return result;
  }
  positionAt(row2, col, table3) {
    for (let i3 = 0, rowStart = 0; ; i3++) {
      const rowEnd = rowStart + table3.child(i3).nodeSize;
      if (i3 == row2) {
        let index4 = col + row2 * this.width;
        const rowEndIndex = (row2 + 1) * this.width;
        while (index4 < rowEndIndex && this.map[index4] < rowStart) index4++;
        return index4 == rowEndIndex ? rowEnd - 1 : this.map[index4];
      }
      rowStart = rowEnd;
    }
  }
  static get(table3) {
    return readFromCache(table3) || addToCache(table3, computeMap(table3));
  }
};
function computeMap(table3) {
  if (table3.type.spec.tableRole != "table") throw new RangeError("Not a table node: " + table3.type.name);
  const width = findWidth(table3), height = table3.childCount;
  const map7 = [];
  let mapPos = 0;
  let problems = null;
  const colWidths = [];
  for (let i3 = 0, e2 = width * height; i3 < e2; i3++) map7[i3] = 0;
  for (let row2 = 0, pos = 0; row2 < height; row2++) {
    const rowNode = table3.child(row2);
    pos++;
    for (let i3 = 0; ; i3++) {
      while (mapPos < map7.length && map7[mapPos] != 0) mapPos++;
      if (i3 == rowNode.childCount) break;
      const cellNode = rowNode.child(i3);
      const { colspan, rowspan, colwidth } = cellNode.attrs;
      for (let h7 = 0; h7 < rowspan; h7++) {
        if (h7 + row2 >= height) {
          (problems || (problems = [])).push({
            type: "overlong_rowspan",
            pos,
            n: rowspan - h7
          });
          break;
        }
        const start = mapPos + h7 * width;
        for (let w3 = 0; w3 < colspan; w3++) {
          if (map7[start + w3] == 0) map7[start + w3] = pos;
          else (problems || (problems = [])).push({
            type: "collision",
            row: row2,
            pos,
            n: colspan - w3
          });
          const colW = colwidth && colwidth[w3];
          if (colW) {
            const widthIndex = (start + w3) % width * 2, prev = colWidths[widthIndex];
            if (prev == null || prev != colW && colWidths[widthIndex + 1] == 1) {
              colWidths[widthIndex] = colW;
              colWidths[widthIndex + 1] = 1;
            } else if (prev == colW) colWidths[widthIndex + 1]++;
          }
        }
      }
      mapPos += colspan;
      pos += cellNode.nodeSize;
    }
    const expectedPos = (row2 + 1) * width;
    let missing = 0;
    while (mapPos < expectedPos) if (map7[mapPos++] == 0) missing++;
    if (missing) (problems || (problems = [])).push({
      type: "missing",
      row: row2,
      n: missing
    });
    pos++;
  }
  if (width === 0 || height === 0) (problems || (problems = [])).push({ type: "zero_sized" });
  const tableMap = new TableMap(width, height, map7, problems);
  let badWidths = false;
  for (let i3 = 0; !badWidths && i3 < colWidths.length; i3 += 2) if (colWidths[i3] != null && colWidths[i3 + 1] < height) badWidths = true;
  if (badWidths) findBadColWidths(tableMap, colWidths, table3);
  return tableMap;
}
function findWidth(table3) {
  let width = -1;
  let hasRowSpan = false;
  for (let row2 = 0; row2 < table3.childCount; row2++) {
    const rowNode = table3.child(row2);
    let rowWidth = 0;
    if (hasRowSpan) for (let j4 = 0; j4 < row2; j4++) {
      const prevRow = table3.child(j4);
      for (let i3 = 0; i3 < prevRow.childCount; i3++) {
        const cell2 = prevRow.child(i3);
        if (j4 + cell2.attrs.rowspan > row2) rowWidth += cell2.attrs.colspan;
      }
    }
    for (let i3 = 0; i3 < rowNode.childCount; i3++) {
      const cell2 = rowNode.child(i3);
      rowWidth += cell2.attrs.colspan;
      if (cell2.attrs.rowspan > 1) hasRowSpan = true;
    }
    if (width == -1) width = rowWidth;
    else if (width != rowWidth) width = Math.max(width, rowWidth);
  }
  return width;
}
function findBadColWidths(map7, colWidths, table3) {
  if (!map7.problems) map7.problems = [];
  const seen = {};
  for (let i3 = 0; i3 < map7.map.length; i3++) {
    const pos = map7.map[i3];
    if (seen[pos]) continue;
    seen[pos] = true;
    const node2 = table3.nodeAt(pos);
    if (!node2) throw new RangeError(`No cell with offset ${pos} found`);
    let updated = null;
    const attrs = node2.attrs;
    for (let j4 = 0; j4 < attrs.colspan; j4++) {
      const colWidth = colWidths[(i3 + j4) % map7.width * 2];
      if (colWidth != null && (!attrs.colwidth || attrs.colwidth[j4] != colWidth)) (updated || (updated = freshColWidth(attrs)))[j4] = colWidth;
    }
    if (updated) map7.problems.unshift({
      type: "colwidth mismatch",
      pos,
      colwidth: updated
    });
  }
}
function freshColWidth(attrs) {
  if (attrs.colwidth) return attrs.colwidth.slice();
  const result = [];
  for (let i3 = 0; i3 < attrs.colspan; i3++) result.push(0);
  return result;
}
function tableNodeTypes(schema) {
  let result = schema.cached.tableNodeTypes;
  if (!result) {
    result = schema.cached.tableNodeTypes = {};
    for (const name in schema.nodes) {
      const type = schema.nodes[name], role = type.spec.tableRole;
      if (role) result[role] = type;
    }
  }
  return result;
}
var tableEditingKey = new PluginKey("selectingCells");
function cellAround($pos) {
  for (let d = $pos.depth - 1; d > 0; d--) if ($pos.node(d).type.spec.tableRole == "row") return $pos.node(0).resolve($pos.before(d + 1));
  return null;
}
function cellWrapping($pos) {
  for (let d = $pos.depth; d > 0; d--) {
    const role = $pos.node(d).type.spec.tableRole;
    if (role === "cell" || role === "header_cell") return $pos.node(d);
  }
  return null;
}
function isInTable(state) {
  const $head = state.selection.$head;
  for (let d = $head.depth; d > 0; d--) if ($head.node(d).type.spec.tableRole == "row") return true;
  return false;
}
function selectionCell(state) {
  const sel = state.selection;
  if ("$anchorCell" in sel && sel.$anchorCell) return sel.$anchorCell.pos > sel.$headCell.pos ? sel.$anchorCell : sel.$headCell;
  else if ("node" in sel && sel.node && sel.node.type.spec.tableRole == "cell") return sel.$anchor;
  const $cell = cellAround(sel.$head) || cellNear(sel.$head);
  if ($cell) return $cell;
  throw new RangeError(`No cell found around position ${sel.head}`);
}
function cellNear($pos) {
  for (let after = $pos.nodeAfter, pos = $pos.pos; after; after = after.firstChild, pos++) {
    const role = after.type.spec.tableRole;
    if (role == "cell" || role == "header_cell") return $pos.doc.resolve(pos);
  }
  for (let before = $pos.nodeBefore, pos = $pos.pos; before; before = before.lastChild, pos--) {
    const role = before.type.spec.tableRole;
    if (role == "cell" || role == "header_cell") return $pos.doc.resolve(pos - before.nodeSize);
  }
}
function pointsAtCell($pos) {
  return $pos.parent.type.spec.tableRole == "row" && !!$pos.nodeAfter;
}
function moveCellForward($pos) {
  return $pos.node(0).resolve($pos.pos + $pos.nodeAfter.nodeSize);
}
function inSameTable($cellA, $cellB) {
  return $cellA.depth == $cellB.depth && $cellA.pos >= $cellB.start(-1) && $cellA.pos <= $cellB.end(-1);
}
function nextCell($pos, axis, dir) {
  const table3 = $pos.node(-1);
  const map7 = TableMap.get(table3);
  const tableStart = $pos.start(-1);
  const moved = map7.nextCell($pos.pos - tableStart, axis, dir);
  return moved == null ? null : $pos.node(0).resolve(tableStart + moved);
}
function removeColSpan(attrs, pos, n = 1) {
  const result = {
    ...attrs,
    colspan: attrs.colspan - n
  };
  if (result.colwidth) {
    result.colwidth = result.colwidth.slice();
    result.colwidth.splice(pos, n);
    if (!result.colwidth.some((w3) => w3 > 0)) result.colwidth = null;
  }
  return result;
}
function addColSpan(attrs, pos, n = 1) {
  const result = {
    ...attrs,
    colspan: attrs.colspan + n
  };
  if (result.colwidth) {
    result.colwidth = result.colwidth.slice();
    for (let i3 = 0; i3 < n; i3++) result.colwidth.splice(pos, 0, 0);
  }
  return result;
}
function columnIsHeader(map7, table3, col) {
  const headerCell = tableNodeTypes(table3.type.schema).header_cell;
  for (let row2 = 0; row2 < map7.height; row2++) if (table3.nodeAt(map7.map[col + row2 * map7.width]).type != headerCell) return false;
  return true;
}
var CellSelection = class CellSelection2 extends Selection {
  constructor($anchorCell, $headCell = $anchorCell) {
    const table3 = $anchorCell.node(-1);
    const map7 = TableMap.get(table3);
    const tableStart = $anchorCell.start(-1);
    const rect = map7.rectBetween($anchorCell.pos - tableStart, $headCell.pos - tableStart);
    const doc4 = $anchorCell.node(0);
    const cells2 = map7.cellsInRect(rect).filter((p4) => p4 != $headCell.pos - tableStart);
    cells2.unshift($headCell.pos - tableStart);
    const ranges = cells2.map((pos) => {
      const cell2 = table3.nodeAt(pos);
      if (!cell2) throw new RangeError(`No cell with offset ${pos} found`);
      const from4 = tableStart + pos + 1;
      return new SelectionRange(doc4.resolve(from4), doc4.resolve(from4 + cell2.content.size));
    });
    super(ranges[0].$from, ranges[0].$to, ranges);
    this.$anchorCell = $anchorCell;
    this.$headCell = $headCell;
  }
  map(doc4, mapping) {
    const $anchorCell = doc4.resolve(mapping.map(this.$anchorCell.pos));
    const $headCell = doc4.resolve(mapping.map(this.$headCell.pos));
    if (pointsAtCell($anchorCell) && pointsAtCell($headCell) && inSameTable($anchorCell, $headCell)) {
      const tableChanged = this.$anchorCell.node(-1) != $anchorCell.node(-1);
      if (tableChanged && this.isRowSelection()) return CellSelection2.rowSelection($anchorCell, $headCell);
      else if (tableChanged && this.isColSelection()) return CellSelection2.colSelection($anchorCell, $headCell);
      else return new CellSelection2($anchorCell, $headCell);
    }
    return TextSelection.between($anchorCell, $headCell);
  }
  content() {
    const table3 = this.$anchorCell.node(-1);
    const map7 = TableMap.get(table3);
    const tableStart = this.$anchorCell.start(-1);
    const rect = map7.rectBetween(this.$anchorCell.pos - tableStart, this.$headCell.pos - tableStart);
    const seen = {};
    const rows = [];
    for (let row2 = rect.top; row2 < rect.bottom; row2++) {
      const rowContent = [];
      for (let index4 = row2 * map7.width + rect.left, col = rect.left; col < rect.right; col++, index4++) {
        const pos = map7.map[index4];
        if (seen[pos]) continue;
        seen[pos] = true;
        const cellRect = map7.findCell(pos);
        let cell2 = table3.nodeAt(pos);
        if (!cell2) throw new RangeError(`No cell with offset ${pos} found`);
        const extraLeft = rect.left - cellRect.left;
        const extraRight = cellRect.right - rect.right;
        if (extraLeft > 0 || extraRight > 0) {
          let attrs = cell2.attrs;
          if (extraLeft > 0) attrs = removeColSpan(attrs, 0, extraLeft);
          if (extraRight > 0) attrs = removeColSpan(attrs, attrs.colspan - extraRight, extraRight);
          if (cellRect.left < rect.left) {
            cell2 = cell2.type.createAndFill(attrs);
            if (!cell2) throw new RangeError(`Could not create cell with attrs ${JSON.stringify(attrs)}`);
          } else cell2 = cell2.type.create(attrs, cell2.content);
        }
        if (cellRect.top < rect.top || cellRect.bottom > rect.bottom) {
          const attrs = {
            ...cell2.attrs,
            rowspan: Math.min(cellRect.bottom, rect.bottom) - Math.max(cellRect.top, rect.top)
          };
          if (cellRect.top < rect.top) cell2 = cell2.type.createAndFill(attrs);
          else cell2 = cell2.type.create(attrs, cell2.content);
        }
        rowContent.push(cell2);
      }
      rows.push(table3.child(row2).copy(Fragment.from(rowContent)));
    }
    const fragment = this.isColSelection() && this.isRowSelection() ? table3 : rows;
    return new Slice(Fragment.from(fragment), 1, 1);
  }
  replace(tr4, content5 = Slice.empty) {
    const mapFrom = tr4.steps.length, ranges = this.ranges;
    for (let i3 = 0; i3 < ranges.length; i3++) {
      const { $from, $to } = ranges[i3], mapping = tr4.mapping.slice(mapFrom);
      tr4.replace(mapping.map($from.pos), mapping.map($to.pos), i3 ? Slice.empty : content5);
    }
    const sel = Selection.findFrom(tr4.doc.resolve(tr4.mapping.slice(mapFrom).map(this.to)), -1);
    if (sel) tr4.setSelection(sel);
  }
  replaceWith(tr4, node2) {
    this.replace(tr4, new Slice(Fragment.from(node2), 0, 0));
  }
  forEachCell(f6) {
    const table3 = this.$anchorCell.node(-1);
    const map7 = TableMap.get(table3);
    const tableStart = this.$anchorCell.start(-1);
    const cells2 = map7.cellsInRect(map7.rectBetween(this.$anchorCell.pos - tableStart, this.$headCell.pos - tableStart));
    for (let i3 = 0; i3 < cells2.length; i3++) f6(table3.nodeAt(cells2[i3]), tableStart + cells2[i3]);
  }
  isColSelection() {
    const anchorTop = this.$anchorCell.index(-1);
    const headTop = this.$headCell.index(-1);
    if (Math.min(anchorTop, headTop) > 0) return false;
    const anchorBottom = anchorTop + this.$anchorCell.nodeAfter.attrs.rowspan;
    const headBottom = headTop + this.$headCell.nodeAfter.attrs.rowspan;
    return Math.max(anchorBottom, headBottom) == this.$headCell.node(-1).childCount;
  }
  static colSelection($anchorCell, $headCell = $anchorCell) {
    const table3 = $anchorCell.node(-1);
    const map7 = TableMap.get(table3);
    const tableStart = $anchorCell.start(-1);
    const anchorRect = map7.findCell($anchorCell.pos - tableStart);
    const headRect = map7.findCell($headCell.pos - tableStart);
    const doc4 = $anchorCell.node(0);
    if (anchorRect.top <= headRect.top) {
      if (anchorRect.top > 0) $anchorCell = doc4.resolve(tableStart + map7.map[anchorRect.left]);
      if (headRect.bottom < map7.height) $headCell = doc4.resolve(tableStart + map7.map[map7.width * (map7.height - 1) + headRect.right - 1]);
    } else {
      if (headRect.top > 0) $headCell = doc4.resolve(tableStart + map7.map[headRect.left]);
      if (anchorRect.bottom < map7.height) $anchorCell = doc4.resolve(tableStart + map7.map[map7.width * (map7.height - 1) + anchorRect.right - 1]);
    }
    return new CellSelection2($anchorCell, $headCell);
  }
  isRowSelection() {
    const table3 = this.$anchorCell.node(-1);
    const map7 = TableMap.get(table3);
    const tableStart = this.$anchorCell.start(-1);
    const anchorLeft = map7.colCount(this.$anchorCell.pos - tableStart);
    const headLeft = map7.colCount(this.$headCell.pos - tableStart);
    if (Math.min(anchorLeft, headLeft) > 0) return false;
    const anchorRight = anchorLeft + this.$anchorCell.nodeAfter.attrs.colspan;
    const headRight = headLeft + this.$headCell.nodeAfter.attrs.colspan;
    return Math.max(anchorRight, headRight) == map7.width;
  }
  eq(other) {
    return other instanceof CellSelection2 && other.$anchorCell.pos == this.$anchorCell.pos && other.$headCell.pos == this.$headCell.pos;
  }
  static rowSelection($anchorCell, $headCell = $anchorCell) {
    const table3 = $anchorCell.node(-1);
    const map7 = TableMap.get(table3);
    const tableStart = $anchorCell.start(-1);
    const anchorRect = map7.findCell($anchorCell.pos - tableStart);
    const headRect = map7.findCell($headCell.pos - tableStart);
    const doc4 = $anchorCell.node(0);
    if (anchorRect.left <= headRect.left) {
      if (anchorRect.left > 0) $anchorCell = doc4.resolve(tableStart + map7.map[anchorRect.top * map7.width]);
      if (headRect.right < map7.width) $headCell = doc4.resolve(tableStart + map7.map[map7.width * (headRect.top + 1) - 1]);
    } else {
      if (headRect.left > 0) $headCell = doc4.resolve(tableStart + map7.map[headRect.top * map7.width]);
      if (anchorRect.right < map7.width) $anchorCell = doc4.resolve(tableStart + map7.map[map7.width * (anchorRect.top + 1) - 1]);
    }
    return new CellSelection2($anchorCell, $headCell);
  }
  toJSON() {
    return {
      type: "cell",
      anchor: this.$anchorCell.pos,
      head: this.$headCell.pos
    };
  }
  static fromJSON(doc4, json) {
    return new CellSelection2(doc4.resolve(json.anchor), doc4.resolve(json.head));
  }
  static create(doc4, anchorCell, headCell = anchorCell) {
    return new CellSelection2(doc4.resolve(anchorCell), doc4.resolve(headCell));
  }
  getBookmark() {
    return new CellBookmark(this.$anchorCell.pos, this.$headCell.pos);
  }
};
CellSelection.prototype.visible = false;
Selection.jsonID("cell", CellSelection);
var CellBookmark = class CellBookmark2 {
  constructor(anchor, head2) {
    this.anchor = anchor;
    this.head = head2;
  }
  map(mapping) {
    return new CellBookmark2(mapping.map(this.anchor), mapping.map(this.head));
  }
  resolve(doc4) {
    const $anchorCell = doc4.resolve(this.anchor), $headCell = doc4.resolve(this.head);
    if ($anchorCell.parent.type.spec.tableRole == "row" && $headCell.parent.type.spec.tableRole == "row" && $anchorCell.index() < $anchorCell.parent.childCount && $headCell.index() < $headCell.parent.childCount && inSameTable($anchorCell, $headCell)) return new CellSelection($anchorCell, $headCell);
    else return Selection.near($headCell, 1);
  }
};
function drawCellSelection(state) {
  if (!(state.selection instanceof CellSelection)) return null;
  const cells2 = [];
  state.selection.forEachCell((node2, pos) => {
    cells2.push(Decoration.node(pos, pos + node2.nodeSize, { class: "selectedCell" }));
  });
  return DecorationSet.create(state.doc, cells2);
}
function isCellBoundarySelection({ $from, $to }) {
  if ($from.pos == $to.pos || $from.pos < $to.pos - 6) return false;
  let afterFrom = $from.pos;
  let beforeTo = $to.pos;
  let depth = $from.depth;
  for (; depth >= 0; depth--, afterFrom++) if ($from.after(depth + 1) < $from.end(depth)) break;
  for (let d = $to.depth; d >= 0; d--, beforeTo--) if ($to.before(d + 1) > $to.start(d)) break;
  return afterFrom == beforeTo && /row|table/.test($from.node(depth).type.spec.tableRole);
}
function isTextSelectionAcrossCells({ $from, $to }) {
  let fromCellBoundaryNode;
  let toCellBoundaryNode;
  for (let i3 = $from.depth; i3 > 0; i3--) {
    const node2 = $from.node(i3);
    if (node2.type.spec.tableRole === "cell" || node2.type.spec.tableRole === "header_cell") {
      fromCellBoundaryNode = node2;
      break;
    }
  }
  for (let i3 = $to.depth; i3 > 0; i3--) {
    const node2 = $to.node(i3);
    if (node2.type.spec.tableRole === "cell" || node2.type.spec.tableRole === "header_cell") {
      toCellBoundaryNode = node2;
      break;
    }
  }
  return fromCellBoundaryNode !== toCellBoundaryNode && $to.parentOffset === 0;
}
function normalizeSelection(state, tr4, allowTableNodeSelection) {
  const sel = (tr4 || state).selection;
  const doc4 = (tr4 || state).doc;
  let normalize4;
  let role;
  if (sel instanceof NodeSelection && (role = sel.node.type.spec.tableRole)) {
    if (role == "cell" || role == "header_cell") normalize4 = CellSelection.create(doc4, sel.from);
    else if (role == "row") {
      const $cell = doc4.resolve(sel.from + 1);
      normalize4 = CellSelection.rowSelection($cell, $cell);
    } else if (!allowTableNodeSelection) {
      const map7 = TableMap.get(sel.node);
      const start = sel.from + 1;
      const lastCell = start + map7.map[map7.width * map7.height - 1];
      normalize4 = CellSelection.create(doc4, start + 1, lastCell);
    }
  } else if (sel instanceof TextSelection && isCellBoundarySelection(sel)) normalize4 = TextSelection.create(doc4, sel.from);
  else if (sel instanceof TextSelection && isTextSelectionAcrossCells(sel)) normalize4 = TextSelection.create(doc4, sel.$from.start(), sel.$from.end());
  if (normalize4) (tr4 || (tr4 = state.tr)).setSelection(normalize4);
  return tr4;
}
var fixTablesKey = new PluginKey("fix-tables");
function changedDescendants(old, cur, offset4, f6) {
  const oldSize = old.childCount, curSize = cur.childCount;
  outer: for (let i3 = 0, j4 = 0; i3 < curSize; i3++) {
    const child = cur.child(i3);
    for (let scan = j4, e2 = Math.min(oldSize, i3 + 3); scan < e2; scan++) if (old.child(scan) == child) {
      j4 = scan + 1;
      offset4 += child.nodeSize;
      continue outer;
    }
    f6(child, offset4);
    if (j4 < oldSize && old.child(j4).sameMarkup(child)) changedDescendants(old.child(j4), child, offset4 + 1, f6);
    else child.nodesBetween(0, child.content.size, f6, offset4 + 1);
    offset4 += child.nodeSize;
  }
}
function fixTables(state, oldState) {
  let tr4;
  const check = (node2, pos) => {
    if (node2.type.spec.tableRole == "table") tr4 = fixTable(state, node2, pos, tr4);
  };
  if (!oldState) state.doc.descendants(check);
  else if (oldState.doc != state.doc) changedDescendants(oldState.doc, state.doc, 0, check);
  return tr4;
}
function fixTable(state, table3, tablePos, tr4) {
  const map7 = TableMap.get(table3);
  if (!map7.problems) return tr4;
  if (!tr4) tr4 = state.tr;
  const mustAdd = [];
  for (let i3 = 0; i3 < map7.height; i3++) mustAdd.push(0);
  for (let i3 = 0; i3 < map7.problems.length; i3++) {
    const prob = map7.problems[i3];
    if (prob.type == "collision") {
      const cell2 = table3.nodeAt(prob.pos);
      if (!cell2) continue;
      const attrs = cell2.attrs;
      for (let j4 = 0; j4 < attrs.rowspan; j4++) mustAdd[prob.row + j4] += prob.n;
      tr4.setNodeMarkup(tr4.mapping.map(tablePos + 1 + prob.pos), null, removeColSpan(attrs, attrs.colspan - prob.n, prob.n));
    } else if (prob.type == "missing") mustAdd[prob.row] += prob.n;
    else if (prob.type == "overlong_rowspan") {
      const cell2 = table3.nodeAt(prob.pos);
      if (!cell2) continue;
      tr4.setNodeMarkup(tr4.mapping.map(tablePos + 1 + prob.pos), null, {
        ...cell2.attrs,
        rowspan: cell2.attrs.rowspan - prob.n
      });
    } else if (prob.type == "colwidth mismatch") {
      const cell2 = table3.nodeAt(prob.pos);
      if (!cell2) continue;
      tr4.setNodeMarkup(tr4.mapping.map(tablePos + 1 + prob.pos), null, {
        ...cell2.attrs,
        colwidth: prob.colwidth
      });
    } else if (prob.type == "zero_sized") {
      const pos = tr4.mapping.map(tablePos);
      tr4.delete(pos, pos + table3.nodeSize);
    }
  }
  let first2, last2;
  for (let i3 = 0; i3 < mustAdd.length; i3++) if (mustAdd[i3]) {
    if (first2 == null) first2 = i3;
    last2 = i3;
  }
  for (let i3 = 0, pos = tablePos + 1; i3 < map7.height; i3++) {
    const row2 = table3.child(i3);
    const end = pos + row2.nodeSize;
    const add = mustAdd[i3];
    if (add > 0) {
      let role = "cell";
      if (row2.firstChild) role = row2.firstChild.type.spec.tableRole;
      const nodes = [];
      for (let j4 = 0; j4 < add; j4++) {
        const node2 = tableNodeTypes(state.schema)[role].createAndFill();
        if (node2) nodes.push(node2);
      }
      const side = (i3 == 0 || first2 == i3 - 1) && last2 == i3 ? pos + 1 : end - 1;
      tr4.insert(tr4.mapping.map(side), nodes);
    }
    pos = end;
  }
  return tr4.setMeta(fixTablesKey, { fixTables: true });
}
function selectedRect(state) {
  const sel = state.selection;
  const $pos = selectionCell(state);
  const table3 = $pos.node(-1);
  const tableStart = $pos.start(-1);
  const map7 = TableMap.get(table3);
  return {
    ...sel instanceof CellSelection ? map7.rectBetween(sel.$anchorCell.pos - tableStart, sel.$headCell.pos - tableStart) : map7.findCell($pos.pos - tableStart),
    tableStart,
    map: map7,
    table: table3
  };
}
function addColumn(tr4, { map: map7, tableStart, table: table3 }, col) {
  let refColumn = col > 0 ? -1 : 0;
  if (columnIsHeader(map7, table3, col + refColumn)) refColumn = col == 0 || col == map7.width ? null : 0;
  for (let row2 = 0; row2 < map7.height; row2++) {
    const index4 = row2 * map7.width + col;
    if (col > 0 && col < map7.width && map7.map[index4 - 1] == map7.map[index4]) {
      const pos = map7.map[index4];
      const cell2 = table3.nodeAt(pos);
      tr4.setNodeMarkup(tr4.mapping.map(tableStart + pos), null, addColSpan(cell2.attrs, col - map7.colCount(pos)));
      row2 += cell2.attrs.rowspan - 1;
    } else {
      const type = refColumn == null ? tableNodeTypes(table3.type.schema).cell : table3.nodeAt(map7.map[index4 + refColumn]).type;
      const pos = map7.positionAt(row2, col, table3);
      tr4.insert(tr4.mapping.map(tableStart + pos), type.createAndFill());
    }
  }
  return tr4;
}
function addColumnBefore(state, dispatch) {
  if (!isInTable(state)) return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addColumn(state.tr, rect, rect.left));
  }
  return true;
}
function addColumnAfter(state, dispatch) {
  if (!isInTable(state)) return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addColumn(state.tr, rect, rect.right));
  }
  return true;
}
function removeColumn(tr4, { map: map7, table: table3, tableStart }, col) {
  const mapStart = tr4.mapping.maps.length;
  for (let row2 = 0; row2 < map7.height; ) {
    const index4 = row2 * map7.width + col;
    const pos = map7.map[index4];
    const cell2 = table3.nodeAt(pos);
    const attrs = cell2.attrs;
    if (col > 0 && map7.map[index4 - 1] == pos || col < map7.width - 1 && map7.map[index4 + 1] == pos) tr4.setNodeMarkup(tr4.mapping.slice(mapStart).map(tableStart + pos), null, removeColSpan(attrs, col - map7.colCount(pos)));
    else {
      const start = tr4.mapping.slice(mapStart).map(tableStart + pos);
      tr4.delete(start, start + cell2.nodeSize);
    }
    row2 += attrs.rowspan;
  }
}
function deleteColumn(state, dispatch) {
  if (!isInTable(state)) return false;
  if (dispatch) {
    const rect = selectedRect(state);
    const tr4 = state.tr;
    if (rect.left == 0 && rect.right == rect.map.width) return false;
    for (let i3 = rect.right - 1; ; i3--) {
      removeColumn(tr4, rect, i3);
      if (i3 == rect.left) break;
      const table3 = rect.tableStart ? tr4.doc.nodeAt(rect.tableStart - 1) : tr4.doc;
      if (!table3) throw new RangeError("No table found");
      rect.table = table3;
      rect.map = TableMap.get(table3);
    }
    dispatch(tr4);
  }
  return true;
}
function rowIsHeader(map7, table3, row2) {
  var _table$nodeAt;
  const headerCell = tableNodeTypes(table3.type.schema).header_cell;
  for (let col = 0; col < map7.width; col++) if (((_table$nodeAt = table3.nodeAt(map7.map[col + row2 * map7.width])) === null || _table$nodeAt === void 0 ? void 0 : _table$nodeAt.type) != headerCell) return false;
  return true;
}
function addRow(tr4, { map: map7, tableStart, table: table3 }, row2) {
  let rowPos = tableStart;
  for (let i3 = 0; i3 < row2; i3++) rowPos += table3.child(i3).nodeSize;
  const cells2 = [];
  let refRow = row2 > 0 ? -1 : 0;
  if (rowIsHeader(map7, table3, row2 + refRow)) refRow = row2 == 0 || row2 == map7.height ? null : 0;
  for (let col = 0, index4 = map7.width * row2; col < map7.width; col++, index4++) if (row2 > 0 && row2 < map7.height && map7.map[index4] == map7.map[index4 - map7.width]) {
    const pos = map7.map[index4];
    const attrs = table3.nodeAt(pos).attrs;
    tr4.setNodeMarkup(tableStart + pos, null, {
      ...attrs,
      rowspan: attrs.rowspan + 1
    });
    col += attrs.colspan - 1;
  } else {
    var _table$nodeAt2;
    const type = refRow == null ? tableNodeTypes(table3.type.schema).cell : (_table$nodeAt2 = table3.nodeAt(map7.map[index4 + refRow * map7.width])) === null || _table$nodeAt2 === void 0 ? void 0 : _table$nodeAt2.type;
    const node2 = type === null || type === void 0 ? void 0 : type.createAndFill();
    if (node2) cells2.push(node2);
  }
  tr4.insert(rowPos, tableNodeTypes(table3.type.schema).row.create(null, cells2));
  return tr4;
}
function addRowBefore(state, dispatch) {
  if (!isInTable(state)) return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addRow(state.tr, rect, rect.top));
  }
  return true;
}
function addRowAfter(state, dispatch) {
  if (!isInTable(state)) return false;
  if (dispatch) {
    const rect = selectedRect(state);
    dispatch(addRow(state.tr, rect, rect.bottom));
  }
  return true;
}
function removeRow(tr4, { map: map7, table: table3, tableStart }, row2) {
  let rowPos = 0;
  for (let i3 = 0; i3 < row2; i3++) rowPos += table3.child(i3).nodeSize;
  const nextRow = rowPos + table3.child(row2).nodeSize;
  const mapFrom = tr4.mapping.maps.length;
  tr4.delete(rowPos + tableStart, nextRow + tableStart);
  const seen = /* @__PURE__ */ new Set();
  for (let col = 0, index4 = row2 * map7.width; col < map7.width; col++, index4++) {
    const pos = map7.map[index4];
    if (seen.has(pos)) continue;
    seen.add(pos);
    if (row2 > 0 && pos == map7.map[index4 - map7.width]) {
      const attrs = table3.nodeAt(pos).attrs;
      tr4.setNodeMarkup(tr4.mapping.slice(mapFrom).map(pos + tableStart), null, {
        ...attrs,
        rowspan: attrs.rowspan - 1
      });
      col += attrs.colspan - 1;
    } else if (row2 < map7.height && pos == map7.map[index4 + map7.width]) {
      const cell2 = table3.nodeAt(pos);
      const attrs = cell2.attrs;
      const copy3 = cell2.type.create({
        ...attrs,
        rowspan: cell2.attrs.rowspan - 1
      }, cell2.content);
      const newPos = map7.positionAt(row2 + 1, col, table3);
      tr4.insert(tr4.mapping.slice(mapFrom).map(tableStart + newPos), copy3);
      col += attrs.colspan - 1;
    }
  }
}
function deleteRow(state, dispatch) {
  if (!isInTable(state)) return false;
  if (dispatch) {
    const rect = selectedRect(state), tr4 = state.tr;
    if (rect.top == 0 && rect.bottom == rect.map.height) return false;
    for (let i3 = rect.bottom - 1; ; i3--) {
      removeRow(tr4, rect, i3);
      if (i3 == rect.top) break;
      const table3 = rect.tableStart ? tr4.doc.nodeAt(rect.tableStart - 1) : tr4.doc;
      if (!table3) throw new RangeError("No table found");
      rect.table = table3;
      rect.map = TableMap.get(rect.table);
    }
    dispatch(tr4);
  }
  return true;
}
function isEmpty2(cell2) {
  const c3 = cell2.content;
  return c3.childCount == 1 && c3.child(0).isTextblock && c3.child(0).childCount == 0;
}
function cellsOverlapRectangle({ width, height, map: map7 }, rect) {
  let indexTop = rect.top * width + rect.left, indexLeft = indexTop;
  let indexBottom = (rect.bottom - 1) * width + rect.left, indexRight = indexTop + (rect.right - rect.left - 1);
  for (let i3 = rect.top; i3 < rect.bottom; i3++) {
    if (rect.left > 0 && map7[indexLeft] == map7[indexLeft - 1] || rect.right < width && map7[indexRight] == map7[indexRight + 1]) return true;
    indexLeft += width;
    indexRight += width;
  }
  for (let i3 = rect.left; i3 < rect.right; i3++) {
    if (rect.top > 0 && map7[indexTop] == map7[indexTop - width] || rect.bottom < height && map7[indexBottom] == map7[indexBottom + width]) return true;
    indexTop++;
    indexBottom++;
  }
  return false;
}
function mergeCells(state, dispatch) {
  const sel = state.selection;
  if (!(sel instanceof CellSelection) || sel.$anchorCell.pos == sel.$headCell.pos) return false;
  const rect = selectedRect(state), { map: map7 } = rect;
  if (cellsOverlapRectangle(map7, rect)) return false;
  if (dispatch) {
    const tr4 = state.tr;
    const seen = {};
    let content5 = Fragment.empty;
    let mergedPos;
    let mergedCell;
    for (let row2 = rect.top; row2 < rect.bottom; row2++) for (let col = rect.left; col < rect.right; col++) {
      const cellPos = map7.map[row2 * map7.width + col];
      const cell2 = rect.table.nodeAt(cellPos);
      if (seen[cellPos] || !cell2) continue;
      seen[cellPos] = true;
      if (mergedPos == null) {
        mergedPos = cellPos;
        mergedCell = cell2;
      } else {
        if (!isEmpty2(cell2)) content5 = content5.append(cell2.content);
        const mapped = tr4.mapping.map(cellPos + rect.tableStart);
        tr4.delete(mapped, mapped + cell2.nodeSize);
      }
    }
    if (mergedPos == null || mergedCell == null) return true;
    tr4.setNodeMarkup(mergedPos + rect.tableStart, null, {
      ...addColSpan(mergedCell.attrs, mergedCell.attrs.colspan, rect.right - rect.left - mergedCell.attrs.colspan),
      rowspan: rect.bottom - rect.top
    });
    if (content5.size > 0) {
      const end = mergedPos + 1 + mergedCell.content.size;
      const start = isEmpty2(mergedCell) ? mergedPos + 1 : end;
      tr4.replaceWith(start + rect.tableStart, end + rect.tableStart, content5);
    }
    tr4.setSelection(new CellSelection(tr4.doc.resolve(mergedPos + rect.tableStart)));
    dispatch(tr4);
  }
  return true;
}
function splitCell(state, dispatch) {
  const nodeTypes = tableNodeTypes(state.schema);
  return splitCellWithType(({ node: node2 }) => {
    return nodeTypes[node2.type.spec.tableRole];
  })(state, dispatch);
}
function splitCellWithType(getCellType) {
  return (state, dispatch) => {
    const sel = state.selection;
    let cellNode;
    let cellPos;
    if (!(sel instanceof CellSelection)) {
      var _cellAround;
      cellNode = cellWrapping(sel.$from);
      if (!cellNode) return false;
      cellPos = (_cellAround = cellAround(sel.$from)) === null || _cellAround === void 0 ? void 0 : _cellAround.pos;
    } else {
      if (sel.$anchorCell.pos != sel.$headCell.pos) return false;
      cellNode = sel.$anchorCell.nodeAfter;
      cellPos = sel.$anchorCell.pos;
    }
    if (cellNode == null || cellPos == null) return false;
    if (cellNode.attrs.colspan == 1 && cellNode.attrs.rowspan == 1) return false;
    if (dispatch) {
      let baseAttrs = cellNode.attrs;
      const attrs = [];
      const colwidth = baseAttrs.colwidth;
      if (baseAttrs.rowspan > 1) baseAttrs = {
        ...baseAttrs,
        rowspan: 1
      };
      if (baseAttrs.colspan > 1) baseAttrs = {
        ...baseAttrs,
        colspan: 1
      };
      const rect = selectedRect(state), tr4 = state.tr;
      for (let i3 = 0; i3 < rect.right - rect.left; i3++) attrs.push(colwidth ? {
        ...baseAttrs,
        colwidth: colwidth && colwidth[i3] ? [colwidth[i3]] : null
      } : baseAttrs);
      let lastCell;
      for (let row2 = rect.top; row2 < rect.bottom; row2++) {
        let pos = rect.map.positionAt(row2, rect.left, rect.table);
        if (row2 == rect.top) pos += cellNode.nodeSize;
        for (let col = rect.left, i3 = 0; col < rect.right; col++, i3++) {
          if (col == rect.left && row2 == rect.top) continue;
          tr4.insert(lastCell = tr4.mapping.map(pos + rect.tableStart, 1), getCellType({
            node: cellNode,
            row: row2,
            col
          }).createAndFill(attrs[i3]));
        }
      }
      tr4.setNodeMarkup(cellPos, getCellType({
        node: cellNode,
        row: rect.top,
        col: rect.left
      }), attrs[0]);
      if (sel instanceof CellSelection) tr4.setSelection(new CellSelection(tr4.doc.resolve(sel.$anchorCell.pos), lastCell ? tr4.doc.resolve(lastCell) : void 0));
      dispatch(tr4);
    }
    return true;
  };
}
function deprecated_toggleHeader(type) {
  return function(state, dispatch) {
    if (!isInTable(state)) return false;
    if (dispatch) {
      const types2 = tableNodeTypes(state.schema);
      const rect = selectedRect(state), tr4 = state.tr;
      const cells2 = rect.map.cellsInRect(type == "column" ? {
        left: rect.left,
        top: 0,
        right: rect.right,
        bottom: rect.map.height
      } : type == "row" ? {
        left: 0,
        top: rect.top,
        right: rect.map.width,
        bottom: rect.bottom
      } : rect);
      const nodes = cells2.map((pos) => rect.table.nodeAt(pos));
      for (let i3 = 0; i3 < cells2.length; i3++) if (nodes[i3].type == types2.header_cell) tr4.setNodeMarkup(rect.tableStart + cells2[i3], types2.cell, nodes[i3].attrs);
      if (tr4.steps.length === 0) for (let i3 = 0; i3 < cells2.length; i3++) tr4.setNodeMarkup(rect.tableStart + cells2[i3], types2.header_cell, nodes[i3].attrs);
      dispatch(tr4);
    }
    return true;
  };
}
function isHeaderEnabledByType(type, rect, types2) {
  const cellPositions = rect.map.cellsInRect({
    left: 0,
    top: 0,
    right: type == "row" ? rect.map.width : 1,
    bottom: type == "column" ? rect.map.height : 1
  });
  for (let i3 = 0; i3 < cellPositions.length; i3++) {
    const cell2 = rect.table.nodeAt(cellPositions[i3]);
    if (cell2 && cell2.type !== types2.header_cell) return false;
  }
  return true;
}
function toggleHeader(type, options2) {
  options2 = options2 || { useDeprecatedLogic: false };
  if (options2.useDeprecatedLogic) return deprecated_toggleHeader(type);
  return function(state, dispatch) {
    if (!isInTable(state)) return false;
    if (dispatch) {
      const types2 = tableNodeTypes(state.schema);
      const rect = selectedRect(state), tr4 = state.tr;
      const isHeaderRowEnabled = isHeaderEnabledByType("row", rect, types2);
      const isHeaderColumnEnabled = isHeaderEnabledByType("column", rect, types2);
      const selectionStartsAt = (type === "column" ? isHeaderRowEnabled : type === "row" ? isHeaderColumnEnabled : false) ? 1 : 0;
      const cellsRect = type == "column" ? {
        left: 0,
        top: selectionStartsAt,
        right: 1,
        bottom: rect.map.height
      } : type == "row" ? {
        left: selectionStartsAt,
        top: 0,
        right: rect.map.width,
        bottom: 1
      } : rect;
      const newType = type == "column" ? isHeaderColumnEnabled ? types2.cell : types2.header_cell : type == "row" ? isHeaderRowEnabled ? types2.cell : types2.header_cell : types2.cell;
      rect.map.cellsInRect(cellsRect).forEach((relativeCellPos) => {
        const cellPos = relativeCellPos + rect.tableStart;
        const cell2 = tr4.doc.nodeAt(cellPos);
        if (cell2) tr4.setNodeMarkup(cellPos, newType, cell2.attrs);
      });
      dispatch(tr4);
    }
    return true;
  };
}
var toggleHeaderRow = toggleHeader("row", { useDeprecatedLogic: true });
var toggleHeaderColumn = toggleHeader("column", { useDeprecatedLogic: true });
var toggleHeaderCell = toggleHeader("cell", { useDeprecatedLogic: true });
function findNextCell($cell, dir) {
  if (dir < 0) {
    const before = $cell.nodeBefore;
    if (before) return $cell.pos - before.nodeSize;
    for (let row2 = $cell.index(-1) - 1, rowEnd = $cell.before(); row2 >= 0; row2--) {
      const rowNode = $cell.node(-1).child(row2);
      const lastChild = rowNode.lastChild;
      if (lastChild) return rowEnd - 1 - lastChild.nodeSize;
      rowEnd -= rowNode.nodeSize;
    }
  } else {
    if ($cell.index() < $cell.parent.childCount - 1) return $cell.pos + $cell.nodeAfter.nodeSize;
    const table3 = $cell.node(-1);
    for (let row2 = $cell.indexAfter(-1), rowStart = $cell.after(); row2 < table3.childCount; row2++) {
      const rowNode = table3.child(row2);
      if (rowNode.childCount) return rowStart + 1;
      rowStart += rowNode.nodeSize;
    }
  }
  return null;
}
function goToNextCell(direction) {
  return function(state, dispatch) {
    if (!isInTable(state)) return false;
    const cell2 = findNextCell(selectionCell(state), direction);
    if (cell2 == null) return false;
    if (dispatch) {
      const $cell = state.doc.resolve(cell2);
      dispatch(state.tr.setSelection(TextSelection.between($cell, moveCellForward($cell))).scrollIntoView());
    }
    return true;
  };
}
function deleteCellSelection(state, dispatch) {
  const sel = state.selection;
  if (!(sel instanceof CellSelection)) return false;
  if (dispatch) {
    const tr4 = state.tr;
    const baseContent = tableNodeTypes(state.schema).cell.createAndFill().content;
    sel.forEachCell((cell2, pos) => {
      if (!cell2.content.eq(baseContent)) tr4.replace(tr4.mapping.map(pos + 1), tr4.mapping.map(pos + cell2.nodeSize - 1), new Slice(baseContent, 0, 0));
    });
    if (tr4.docChanged) dispatch(tr4);
  }
  return true;
}
function pastedCells(slice2) {
  if (slice2.size === 0) return null;
  let { content: content5, openStart, openEnd } = slice2;
  while (content5.childCount == 1 && (openStart > 0 && openEnd > 0 || content5.child(0).type.spec.tableRole == "table")) {
    openStart--;
    openEnd--;
    content5 = content5.child(0).content;
  }
  const first2 = content5.child(0);
  const role = first2.type.spec.tableRole;
  const schema = first2.type.schema, rows = [];
  if (role == "row") for (let i3 = 0; i3 < content5.childCount; i3++) {
    let cells2 = content5.child(i3).content;
    const left = i3 ? 0 : Math.max(0, openStart - 1);
    const right = i3 < content5.childCount - 1 ? 0 : Math.max(0, openEnd - 1);
    if (left || right) cells2 = fitSlice(tableNodeTypes(schema).row, new Slice(cells2, left, right)).content;
    rows.push(cells2);
  }
  else if (role == "cell" || role == "header_cell") rows.push(openStart || openEnd ? fitSlice(tableNodeTypes(schema).row, new Slice(content5, openStart, openEnd)).content : content5);
  else return null;
  return ensureRectangular(schema, rows);
}
function ensureRectangular(schema, rows) {
  const widths = [];
  for (let i3 = 0; i3 < rows.length; i3++) {
    const row2 = rows[i3];
    for (let j4 = row2.childCount - 1; j4 >= 0; j4--) {
      const { rowspan, colspan } = row2.child(j4).attrs;
      for (let r4 = i3; r4 < i3 + rowspan; r4++) widths[r4] = (widths[r4] || 0) + colspan;
    }
  }
  let width = 0;
  for (let r4 = 0; r4 < widths.length; r4++) width = Math.max(width, widths[r4]);
  for (let r4 = 0; r4 < widths.length; r4++) {
    if (r4 >= rows.length) rows.push(Fragment.empty);
    if (widths[r4] < width) {
      const empty4 = tableNodeTypes(schema).cell.createAndFill();
      const cells2 = [];
      for (let i3 = widths[r4]; i3 < width; i3++) cells2.push(empty4);
      rows[r4] = rows[r4].append(Fragment.from(cells2));
    }
  }
  return {
    height: rows.length,
    width,
    rows
  };
}
function fitSlice(nodeType, slice2) {
  const node2 = nodeType.createAndFill();
  return new Transform(node2).replace(0, node2.content.size, slice2).doc;
}
function clipCells({ width, height, rows }, newWidth, newHeight) {
  if (width != newWidth) {
    const added = [];
    const newRows = [];
    for (let row2 = 0; row2 < rows.length; row2++) {
      const frag = rows[row2], cells2 = [];
      for (let col = added[row2] || 0, i3 = 0; col < newWidth; i3++) {
        let cell2 = frag.child(i3 % frag.childCount);
        if (col + cell2.attrs.colspan > newWidth) cell2 = cell2.type.createChecked(removeColSpan(cell2.attrs, cell2.attrs.colspan, col + cell2.attrs.colspan - newWidth), cell2.content);
        cells2.push(cell2);
        col += cell2.attrs.colspan;
        for (let j4 = 1; j4 < cell2.attrs.rowspan; j4++) added[row2 + j4] = (added[row2 + j4] || 0) + cell2.attrs.colspan;
      }
      newRows.push(Fragment.from(cells2));
    }
    rows = newRows;
    width = newWidth;
  }
  if (height != newHeight) {
    const newRows = [];
    for (let row2 = 0, i3 = 0; row2 < newHeight; row2++, i3++) {
      const cells2 = [], source = rows[i3 % height];
      for (let j4 = 0; j4 < source.childCount; j4++) {
        let cell2 = source.child(j4);
        if (row2 + cell2.attrs.rowspan > newHeight) cell2 = cell2.type.create({
          ...cell2.attrs,
          rowspan: Math.max(1, newHeight - cell2.attrs.rowspan)
        }, cell2.content);
        cells2.push(cell2);
      }
      newRows.push(Fragment.from(cells2));
    }
    rows = newRows;
    height = newHeight;
  }
  return {
    width,
    height,
    rows
  };
}
function growTable(tr4, map7, table3, start, width, height, mapFrom) {
  const schema = tr4.doc.type.schema;
  const types2 = tableNodeTypes(schema);
  let empty4;
  let emptyHead;
  if (width > map7.width) for (let row2 = 0, rowEnd = 0; row2 < map7.height; row2++) {
    const rowNode = table3.child(row2);
    rowEnd += rowNode.nodeSize;
    const cells2 = [];
    let add;
    if (rowNode.lastChild == null || rowNode.lastChild.type == types2.cell) add = empty4 || (empty4 = types2.cell.createAndFill());
    else add = emptyHead || (emptyHead = types2.header_cell.createAndFill());
    for (let i3 = map7.width; i3 < width; i3++) cells2.push(add);
    tr4.insert(tr4.mapping.slice(mapFrom).map(rowEnd - 1 + start), cells2);
  }
  if (height > map7.height) {
    const cells2 = [];
    for (let i3 = 0, start$1 = (map7.height - 1) * map7.width; i3 < Math.max(map7.width, width); i3++) {
      const header = i3 >= map7.width ? false : table3.nodeAt(map7.map[start$1 + i3]).type == types2.header_cell;
      cells2.push(header ? emptyHead || (emptyHead = types2.header_cell.createAndFill()) : empty4 || (empty4 = types2.cell.createAndFill()));
    }
    const emptyRow = types2.row.create(null, Fragment.from(cells2)), rows = [];
    for (let i3 = map7.height; i3 < height; i3++) rows.push(emptyRow);
    tr4.insert(tr4.mapping.slice(mapFrom).map(start + table3.nodeSize - 2), rows);
  }
  return !!(empty4 || emptyHead);
}
function isolateHorizontal(tr4, map7, table3, start, left, right, top, mapFrom) {
  if (top == 0 || top == map7.height) return false;
  let found2 = false;
  for (let col = left; col < right; col++) {
    const index4 = top * map7.width + col, pos = map7.map[index4];
    if (map7.map[index4 - map7.width] == pos) {
      found2 = true;
      const cell2 = table3.nodeAt(pos);
      const { top: cellTop, left: cellLeft } = map7.findCell(pos);
      tr4.setNodeMarkup(tr4.mapping.slice(mapFrom).map(pos + start), null, {
        ...cell2.attrs,
        rowspan: top - cellTop
      });
      tr4.insert(tr4.mapping.slice(mapFrom).map(map7.positionAt(top, cellLeft, table3)), cell2.type.createAndFill({
        ...cell2.attrs,
        rowspan: cellTop + cell2.attrs.rowspan - top
      }));
      col += cell2.attrs.colspan - 1;
    }
  }
  return found2;
}
function isolateVertical(tr4, map7, table3, start, top, bottom, left, mapFrom) {
  if (left == 0 || left == map7.width) return false;
  let found2 = false;
  for (let row2 = top; row2 < bottom; row2++) {
    const index4 = row2 * map7.width + left, pos = map7.map[index4];
    if (map7.map[index4 - 1] == pos) {
      found2 = true;
      const cell2 = table3.nodeAt(pos);
      const cellLeft = map7.colCount(pos);
      const updatePos = tr4.mapping.slice(mapFrom).map(pos + start);
      tr4.setNodeMarkup(updatePos, null, removeColSpan(cell2.attrs, left - cellLeft, cell2.attrs.colspan - (left - cellLeft)));
      tr4.insert(updatePos + cell2.nodeSize, cell2.type.createAndFill(removeColSpan(cell2.attrs, 0, left - cellLeft)));
      row2 += cell2.attrs.rowspan - 1;
    }
  }
  return found2;
}
function insertCells(state, dispatch, tableStart, rect, cells2) {
  let table3 = tableStart ? state.doc.nodeAt(tableStart - 1) : state.doc;
  if (!table3) throw new Error("No table found");
  let map7 = TableMap.get(table3);
  const { top, left } = rect;
  const right = left + cells2.width, bottom = top + cells2.height;
  const tr4 = state.tr;
  let mapFrom = 0;
  function recomp() {
    table3 = tableStart ? tr4.doc.nodeAt(tableStart - 1) : tr4.doc;
    if (!table3) throw new Error("No table found");
    map7 = TableMap.get(table3);
    mapFrom = tr4.mapping.maps.length;
  }
  if (growTable(tr4, map7, table3, tableStart, right, bottom, mapFrom)) recomp();
  if (isolateHorizontal(tr4, map7, table3, tableStart, left, right, top, mapFrom)) recomp();
  if (isolateHorizontal(tr4, map7, table3, tableStart, left, right, bottom, mapFrom)) recomp();
  if (isolateVertical(tr4, map7, table3, tableStart, top, bottom, left, mapFrom)) recomp();
  if (isolateVertical(tr4, map7, table3, tableStart, top, bottom, right, mapFrom)) recomp();
  for (let row2 = top; row2 < bottom; row2++) {
    const from4 = map7.positionAt(row2, left, table3), to2 = map7.positionAt(row2, right, table3);
    tr4.replace(tr4.mapping.slice(mapFrom).map(from4 + tableStart), tr4.mapping.slice(mapFrom).map(to2 + tableStart), new Slice(cells2.rows[row2 - top], 0, 0));
  }
  recomp();
  tr4.setSelection(new CellSelection(tr4.doc.resolve(tableStart + map7.positionAt(top, left, table3)), tr4.doc.resolve(tableStart + map7.positionAt(bottom - 1, right - 1, table3))));
  dispatch(tr4);
}
var handleKeyDown = keydownHandler({
  ArrowLeft: arrow("horiz", -1),
  ArrowRight: arrow("horiz", 1),
  ArrowUp: arrow("vert", -1),
  ArrowDown: arrow("vert", 1),
  "Shift-ArrowLeft": shiftArrow("horiz", -1),
  "Shift-ArrowRight": shiftArrow("horiz", 1),
  "Shift-ArrowUp": shiftArrow("vert", -1),
  "Shift-ArrowDown": shiftArrow("vert", 1),
  Backspace: deleteCellSelection,
  "Mod-Backspace": deleteCellSelection,
  Delete: deleteCellSelection,
  "Mod-Delete": deleteCellSelection
});
function maybeSetSelection(state, dispatch, selection) {
  if (selection.eq(state.selection)) return false;
  if (dispatch) dispatch(state.tr.setSelection(selection).scrollIntoView());
  return true;
}
function arrow(axis, dir) {
  return (state, dispatch, view) => {
    if (!view) return false;
    const sel = state.selection;
    if (sel instanceof CellSelection) return maybeSetSelection(state, dispatch, Selection.near(sel.$headCell, dir));
    if (axis != "horiz" && !sel.empty) return false;
    const end = atEndOfCell(view, axis, dir);
    if (end == null) return false;
    if (axis == "horiz") return maybeSetSelection(state, dispatch, Selection.near(state.doc.resolve(sel.head + dir), dir));
    else {
      const $cell = state.doc.resolve(end);
      const $next = nextCell($cell, axis, dir);
      let newSel;
      if ($next) newSel = Selection.near($next, 1);
      else if (dir < 0) newSel = Selection.near(state.doc.resolve($cell.before(-1)), -1);
      else newSel = Selection.near(state.doc.resolve($cell.after(-1)), 1);
      return maybeSetSelection(state, dispatch, newSel);
    }
  };
}
function shiftArrow(axis, dir) {
  return (state, dispatch, view) => {
    if (!view) return false;
    const sel = state.selection;
    let cellSel;
    if (sel instanceof CellSelection) cellSel = sel;
    else {
      const end = atEndOfCell(view, axis, dir);
      if (end == null) return false;
      cellSel = new CellSelection(state.doc.resolve(end));
    }
    const $head = nextCell(cellSel.$headCell, axis, dir);
    if (!$head) return false;
    return maybeSetSelection(state, dispatch, new CellSelection(cellSel.$anchorCell, $head));
  };
}
function handleTripleClick2(view, pos) {
  const doc4 = view.state.doc, $cell = cellAround(doc4.resolve(pos));
  if (!$cell) return false;
  view.dispatch(view.state.tr.setSelection(new CellSelection($cell)));
  return true;
}
function handlePaste(view, _2, slice2) {
  if (!isInTable(view.state)) return false;
  let cells2 = pastedCells(slice2);
  const sel = view.state.selection;
  if (sel instanceof CellSelection) {
    if (!cells2) cells2 = {
      width: 1,
      height: 1,
      rows: [Fragment.from(fitSlice(tableNodeTypes(view.state.schema).cell, slice2))]
    };
    const table3 = sel.$anchorCell.node(-1);
    const start = sel.$anchorCell.start(-1);
    const rect = TableMap.get(table3).rectBetween(sel.$anchorCell.pos - start, sel.$headCell.pos - start);
    cells2 = clipCells(cells2, rect.right - rect.left, rect.bottom - rect.top);
    insertCells(view.state, view.dispatch, start, rect, cells2);
    return true;
  } else if (cells2) {
    const $cell = selectionCell(view.state);
    const start = $cell.start(-1);
    insertCells(view.state, view.dispatch, start, TableMap.get($cell.node(-1)).findCell($cell.pos - start), cells2);
    return true;
  } else return false;
}
function handleMouseDown$1(view, startEvent) {
  var _cellUnderMouse;
  if (startEvent.button != 0) return;
  if (startEvent.ctrlKey || startEvent.metaKey) return;
  const startDOMCell = domInCell(view, startEvent.target);
  let $anchor;
  if (startEvent.shiftKey && view.state.selection instanceof CellSelection) {
    setCellSelection(view.state.selection.$anchorCell, startEvent);
    startEvent.preventDefault();
  } else if (startEvent.shiftKey && startDOMCell && ($anchor = cellAround(view.state.selection.$anchor)) != null && ((_cellUnderMouse = cellUnderMouse(view, startEvent)) === null || _cellUnderMouse === void 0 ? void 0 : _cellUnderMouse.pos) != $anchor.pos) {
    setCellSelection($anchor, startEvent);
    startEvent.preventDefault();
  } else if (!startDOMCell) return;
  function setCellSelection($anchor$1, event) {
    let $head = cellUnderMouse(view, event);
    const starting = tableEditingKey.getState(view.state) == null;
    if (!$head || !inSameTable($anchor$1, $head)) if (starting) $head = $anchor$1;
    else return;
    const selection = new CellSelection($anchor$1, $head);
    if (starting || !view.state.selection.eq(selection)) {
      const tr4 = view.state.tr.setSelection(selection);
      if (starting) tr4.setMeta(tableEditingKey, $anchor$1.pos);
      view.dispatch(tr4);
    }
  }
  function stop() {
    view.root.removeEventListener("mouseup", stop);
    view.root.removeEventListener("dragstart", stop);
    view.root.removeEventListener("mousemove", move);
    if (tableEditingKey.getState(view.state) != null) view.dispatch(view.state.tr.setMeta(tableEditingKey, -1));
  }
  function move(_event) {
    const event = _event;
    const anchor = tableEditingKey.getState(view.state);
    let $anchor$1;
    if (anchor != null) $anchor$1 = view.state.doc.resolve(anchor);
    else if (domInCell(view, event.target) != startDOMCell) {
      $anchor$1 = cellUnderMouse(view, startEvent);
      if (!$anchor$1) return stop();
    }
    if ($anchor$1) setCellSelection($anchor$1, event);
  }
  view.root.addEventListener("mouseup", stop);
  view.root.addEventListener("dragstart", stop);
  view.root.addEventListener("mousemove", move);
}
function atEndOfCell(view, axis, dir) {
  if (!(view.state.selection instanceof TextSelection)) return null;
  const { $head } = view.state.selection;
  for (let d = $head.depth - 1; d >= 0; d--) {
    const parent = $head.node(d);
    if ((dir < 0 ? $head.index(d) : $head.indexAfter(d)) != (dir < 0 ? 0 : parent.childCount)) return null;
    if (parent.type.spec.tableRole == "cell" || parent.type.spec.tableRole == "header_cell") {
      const cellPos = $head.before(d);
      const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left";
      return view.endOfTextblock(dirStr) ? cellPos : null;
    }
  }
  return null;
}
function domInCell(view, dom) {
  for (; dom && dom != view.dom; dom = dom.parentNode) if (dom.nodeName == "TD" || dom.nodeName == "TH") return dom;
  return null;
}
function cellUnderMouse(view, event) {
  const mousePos = view.posAtCoords({
    left: event.clientX,
    top: event.clientY
  });
  if (!mousePos) return null;
  let { inside, pos } = mousePos;
  return inside >= 0 && cellAround(view.state.doc.resolve(inside)) || cellAround(view.state.doc.resolve(pos));
}
var TableView = class {
  constructor(node2, defaultCellMinWidth) {
    this.node = node2;
    this.defaultCellMinWidth = defaultCellMinWidth;
    this.dom = document.createElement("div");
    this.dom.className = "tableWrapper";
    this.table = this.dom.appendChild(document.createElement("table"));
    this.table.style.setProperty("--default-cell-min-width", `${defaultCellMinWidth}px`);
    this.colgroup = this.table.appendChild(document.createElement("colgroup"));
    updateColumnsOnResize(node2, this.colgroup, this.table, defaultCellMinWidth);
    this.contentDOM = this.table.appendChild(document.createElement("tbody"));
  }
  update(node2) {
    if (node2.type != this.node.type) return false;
    this.node = node2;
    updateColumnsOnResize(node2, this.colgroup, this.table, this.defaultCellMinWidth);
    return true;
  }
  ignoreMutation(record) {
    return record.type == "attributes" && (record.target == this.table || this.colgroup.contains(record.target));
  }
};
function updateColumnsOnResize(node2, colgroup2, table3, defaultCellMinWidth, overrideCol, overrideValue) {
  let totalWidth = 0;
  let fixedWidth = true;
  let nextDOM = colgroup2.firstChild;
  const row2 = node2.firstChild;
  if (!row2) return;
  for (let i3 = 0, col = 0; i3 < row2.childCount; i3++) {
    const { colspan, colwidth } = row2.child(i3).attrs;
    for (let j4 = 0; j4 < colspan; j4++, col++) {
      const hasWidth = overrideCol == col ? overrideValue : colwidth && colwidth[j4];
      const cssWidth = hasWidth ? hasWidth + "px" : "";
      totalWidth += hasWidth || defaultCellMinWidth;
      if (!hasWidth) fixedWidth = false;
      if (!nextDOM) {
        const col$1 = document.createElement("col");
        col$1.style.width = cssWidth;
        colgroup2.appendChild(col$1);
      } else {
        if (nextDOM.style.width != cssWidth) nextDOM.style.width = cssWidth;
        nextDOM = nextDOM.nextSibling;
      }
    }
  }
  while (nextDOM) {
    var _nextDOM$parentNode;
    const after = nextDOM.nextSibling;
    (_nextDOM$parentNode = nextDOM.parentNode) === null || _nextDOM$parentNode === void 0 || _nextDOM$parentNode.removeChild(nextDOM);
    nextDOM = after;
  }
  if (fixedWidth) {
    table3.style.width = totalWidth + "px";
    table3.style.minWidth = "";
  } else {
    table3.style.width = "";
    table3.style.minWidth = totalWidth + "px";
  }
}
var columnResizingPluginKey = new PluginKey("tableColumnResizing");
function columnResizing({ handleWidth = 5, cellMinWidth = 25, defaultCellMinWidth = 100, View = TableView, lastColumnResizable = true } = {}) {
  const plugin = new Plugin({
    key: columnResizingPluginKey,
    state: {
      init(_2, state) {
        var _plugin$spec;
        const nodeViews = (_plugin$spec = plugin.spec) === null || _plugin$spec === void 0 || (_plugin$spec = _plugin$spec.props) === null || _plugin$spec === void 0 ? void 0 : _plugin$spec.nodeViews;
        const tableName = tableNodeTypes(state.schema).table.name;
        if (View && nodeViews) nodeViews[tableName] = (node2, view) => {
          return new View(node2, defaultCellMinWidth, view);
        };
        return new ResizeState(-1, false);
      },
      apply(tr4, prev) {
        return prev.apply(tr4);
      }
    },
    props: {
      attributes: (state) => {
        const pluginState = columnResizingPluginKey.getState(state);
        return pluginState && pluginState.activeHandle > -1 ? { class: "resize-cursor" } : {};
      },
      handleDOMEvents: {
        mousemove: (view, event) => {
          handleMouseMove(view, event, handleWidth, lastColumnResizable);
        },
        mouseleave: (view) => {
          handleMouseLeave(view);
        },
        mousedown: (view, event) => {
          handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth);
        }
      },
      decorations: (state) => {
        const pluginState = columnResizingPluginKey.getState(state);
        if (pluginState && pluginState.activeHandle > -1) return handleDecorations(state, pluginState.activeHandle);
      },
      nodeViews: {}
    }
  });
  return plugin;
}
var ResizeState = class ResizeState2 {
  constructor(activeHandle, dragging) {
    this.activeHandle = activeHandle;
    this.dragging = dragging;
  }
  apply(tr4) {
    const state = this;
    const action = tr4.getMeta(columnResizingPluginKey);
    if (action && action.setHandle != null) return new ResizeState2(action.setHandle, false);
    if (action && action.setDragging !== void 0) return new ResizeState2(state.activeHandle, action.setDragging);
    if (state.activeHandle > -1 && tr4.docChanged) {
      let handle4 = tr4.mapping.map(state.activeHandle, -1);
      if (!pointsAtCell(tr4.doc.resolve(handle4))) handle4 = -1;
      return new ResizeState2(handle4, state.dragging);
    }
    return state;
  }
};
function handleMouseMove(view, event, handleWidth, lastColumnResizable) {
  if (!view.editable) return;
  const pluginState = columnResizingPluginKey.getState(view.state);
  if (!pluginState) return;
  if (!pluginState.dragging) {
    const target = domCellAround(event.target);
    let cell2 = -1;
    if (target) {
      const { left, right } = target.getBoundingClientRect();
      if (event.clientX - left <= handleWidth) cell2 = edgeCell(view, event, "left", handleWidth);
      else if (right - event.clientX <= handleWidth) cell2 = edgeCell(view, event, "right", handleWidth);
    }
    if (cell2 != pluginState.activeHandle) {
      if (!lastColumnResizable && cell2 !== -1) {
        const $cell = view.state.doc.resolve(cell2);
        const table3 = $cell.node(-1);
        const map7 = TableMap.get(table3);
        const tableStart = $cell.start(-1);
        if (map7.colCount($cell.pos - tableStart) + $cell.nodeAfter.attrs.colspan - 1 == map7.width - 1) return;
      }
      updateHandle(view, cell2);
    }
  }
}
function handleMouseLeave(view) {
  if (!view.editable) return;
  const pluginState = columnResizingPluginKey.getState(view.state);
  if (pluginState && pluginState.activeHandle > -1 && !pluginState.dragging) updateHandle(view, -1);
}
function handleMouseDown(view, event, cellMinWidth, defaultCellMinWidth) {
  var _view$dom$ownerDocume;
  if (!view.editable) return false;
  const win = (_view$dom$ownerDocume = view.dom.ownerDocument.defaultView) !== null && _view$dom$ownerDocume !== void 0 ? _view$dom$ownerDocume : window;
  const pluginState = columnResizingPluginKey.getState(view.state);
  if (!pluginState || pluginState.activeHandle == -1 || pluginState.dragging) return false;
  const cell2 = view.state.doc.nodeAt(pluginState.activeHandle);
  const width = currentColWidth(view, pluginState.activeHandle, cell2.attrs);
  view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setDragging: {
    startX: event.clientX,
    startWidth: width
  } }));
  function finish(event$1) {
    win.removeEventListener("mouseup", finish);
    win.removeEventListener("mousemove", move);
    const pluginState$1 = columnResizingPluginKey.getState(view.state);
    if (pluginState$1 === null || pluginState$1 === void 0 ? void 0 : pluginState$1.dragging) {
      updateColumnWidth(view, pluginState$1.activeHandle, draggedWidth(pluginState$1.dragging, event$1, cellMinWidth));
      view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setDragging: null }));
    }
  }
  function move(event$1) {
    if (!event$1.which) return finish(event$1);
    const pluginState$1 = columnResizingPluginKey.getState(view.state);
    if (!pluginState$1) return;
    if (pluginState$1.dragging) {
      const dragged = draggedWidth(pluginState$1.dragging, event$1, cellMinWidth);
      displayColumnWidth(view, pluginState$1.activeHandle, dragged, defaultCellMinWidth);
    }
  }
  displayColumnWidth(view, pluginState.activeHandle, width, defaultCellMinWidth);
  win.addEventListener("mouseup", finish);
  win.addEventListener("mousemove", move);
  event.preventDefault();
  return true;
}
function currentColWidth(view, cellPos, { colspan, colwidth }) {
  const width = colwidth && colwidth[colwidth.length - 1];
  if (width) return width;
  const dom = view.domAtPos(cellPos);
  let domWidth = dom.node.childNodes[dom.offset].offsetWidth, parts = colspan;
  if (colwidth) {
    for (let i3 = 0; i3 < colspan; i3++) if (colwidth[i3]) {
      domWidth -= colwidth[i3];
      parts--;
    }
  }
  return domWidth / parts;
}
function domCellAround(target) {
  while (target && target.nodeName != "TD" && target.nodeName != "TH") target = target.classList && target.classList.contains("ProseMirror") ? null : target.parentNode;
  return target;
}
function edgeCell(view, event, side, handleWidth) {
  const offset4 = side == "right" ? -handleWidth : handleWidth;
  const found2 = view.posAtCoords({
    left: event.clientX + offset4,
    top: event.clientY
  });
  if (!found2) return -1;
  const { pos } = found2;
  const $cell = cellAround(view.state.doc.resolve(pos));
  if (!$cell) return -1;
  if (side == "right") return $cell.pos;
  const map7 = TableMap.get($cell.node(-1)), start = $cell.start(-1);
  const index4 = map7.map.indexOf($cell.pos - start);
  return index4 % map7.width == 0 ? -1 : start + map7.map[index4 - 1];
}
function draggedWidth(dragging, event, resizeMinWidth) {
  const offset4 = event.clientX - dragging.startX;
  return Math.max(resizeMinWidth, dragging.startWidth + offset4);
}
function updateHandle(view, value) {
  view.dispatch(view.state.tr.setMeta(columnResizingPluginKey, { setHandle: value }));
}
function updateColumnWidth(view, cell2, width) {
  const $cell = view.state.doc.resolve(cell2);
  const table3 = $cell.node(-1), map7 = TableMap.get(table3), start = $cell.start(-1);
  const col = map7.colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1;
  const tr4 = view.state.tr;
  for (let row2 = 0; row2 < map7.height; row2++) {
    const mapIndex = row2 * map7.width + col;
    if (row2 && map7.map[mapIndex] == map7.map[mapIndex - map7.width]) continue;
    const pos = map7.map[mapIndex];
    const attrs = table3.nodeAt(pos).attrs;
    const index4 = attrs.colspan == 1 ? 0 : col - map7.colCount(pos);
    if (attrs.colwidth && attrs.colwidth[index4] == width) continue;
    const colwidth = attrs.colwidth ? attrs.colwidth.slice() : zeroes(attrs.colspan);
    colwidth[index4] = width;
    tr4.setNodeMarkup(start + pos, null, {
      ...attrs,
      colwidth
    });
  }
  if (tr4.docChanged) view.dispatch(tr4);
}
function displayColumnWidth(view, cell2, width, defaultCellMinWidth) {
  const $cell = view.state.doc.resolve(cell2);
  const table3 = $cell.node(-1), start = $cell.start(-1);
  const col = TableMap.get(table3).colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1;
  let dom = view.domAtPos($cell.start(-1)).node;
  while (dom && dom.nodeName != "TABLE") dom = dom.parentNode;
  if (!dom) return;
  updateColumnsOnResize(table3, dom.firstChild, dom, defaultCellMinWidth, col, width);
}
function zeroes(n) {
  return Array(n).fill(0);
}
function handleDecorations(state, cell2) {
  const decorations = [];
  const $cell = state.doc.resolve(cell2);
  const table3 = $cell.node(-1);
  if (!table3) return DecorationSet.empty;
  const map7 = TableMap.get(table3);
  const start = $cell.start(-1);
  const col = map7.colCount($cell.pos - start) + $cell.nodeAfter.attrs.colspan - 1;
  for (let row2 = 0; row2 < map7.height; row2++) {
    const index4 = col + row2 * map7.width;
    if ((col == map7.width - 1 || map7.map[index4] != map7.map[index4 + 1]) && (row2 == 0 || map7.map[index4] != map7.map[index4 - map7.width])) {
      var _columnResizingPlugin;
      const cellPos = map7.map[index4];
      const pos = start + cellPos + table3.nodeAt(cellPos).nodeSize - 1;
      const dom = document.createElement("div");
      dom.className = "column-resize-handle";
      if ((_columnResizingPlugin = columnResizingPluginKey.getState(state)) === null || _columnResizingPlugin === void 0 ? void 0 : _columnResizingPlugin.dragging) decorations.push(Decoration.node(start + cellPos, start + cellPos + table3.nodeAt(cellPos).nodeSize, { class: "column-resize-dragging" }));
      decorations.push(Decoration.widget(pos, dom));
    }
  }
  return DecorationSet.create(state.doc, decorations);
}
function tableEditing({ allowTableNodeSelection = false } = {}) {
  return new Plugin({
    key: tableEditingKey,
    state: {
      init() {
        return null;
      },
      apply(tr4, cur) {
        const set = tr4.getMeta(tableEditingKey);
        if (set != null) return set == -1 ? null : set;
        if (cur == null || !tr4.docChanged) return cur;
        const { deleted, pos } = tr4.mapping.mapResult(cur);
        return deleted ? null : pos;
      }
    },
    props: {
      decorations: drawCellSelection,
      handleDOMEvents: { mousedown: handleMouseDown$1 },
      createSelectionBetween(view) {
        return tableEditingKey.getState(view.state) != null ? view.state.selection : null;
      },
      handleTripleClick: handleTripleClick2,
      handleKeyDown,
      handlePaste
    },
    appendTransaction(_2, oldState, state) {
      return normalizeSelection(state, fixTables(state, oldState), allowTableNodeSelection);
    }
  });
}

// ../../node_modules/.pnpm/@tiptap+core@3.14.0_@tiptap+pm@3.14.0/node_modules/@tiptap/core/dist/jsx-runtime/jsx-runtime.js
var h2 = (tag, attributes) => {
  if (tag === "slot") {
    return 0;
  }
  if (tag instanceof Function) {
    return tag(attributes);
  }
  const { children, ...rest } = attributes != null ? attributes : {};
  if (tag === "svg") {
    throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");
  }
  return [tag, rest, children];
};

// ../../node_modules/.pnpm/@tiptap+extension-bold@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-bold/dist/index.js
var starInputRegex = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/;
var starPasteRegex = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g;
var underscoreInputRegex = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/;
var underscorePasteRegex = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;
var Bold = Mark2.create({
  name: "bold",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "strong"
      },
      {
        tag: "b",
        getAttrs: (node2) => node2.style.fontWeight !== "normal" && null
      },
      {
        style: "font-weight=400",
        clearMark: (mark2) => mark2.type.name === this.name
      },
      {
        style: "font-weight",
        getAttrs: (value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return h2("strong", { ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), children: h2("slot", {}) });
  },
  markdownTokenName: "strong",
  parseMarkdown: (token, helpers) => {
    return helpers.applyMark("bold", helpers.parseInline(token.tokens || []));
  },
  renderMarkdown: (node2, h7) => {
    return `**${h7.renderChildren(node2)}**`;
  },
  addCommands() {
    return {
      setBold: () => ({ commands }) => {
        return commands.setMark(this.name);
      },
      toggleBold: () => ({ commands }) => {
        return commands.toggleMark(this.name);
      },
      unsetBold: () => ({ commands }) => {
        return commands.unsetMark(this.name);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-b": () => this.editor.commands.toggleBold(),
      "Mod-B": () => this.editor.commands.toggleBold()
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: starInputRegex,
        type: this.type
      }),
      markInputRule({
        find: underscoreInputRegex,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: starPasteRegex,
        type: this.type
      }),
      markPasteRule({
        find: underscorePasteRegex,
        type: this.type
      })
    ];
  }
});
var index_default = Bold;

// ../../node_modules/.pnpm/@tiptap+extension-code@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-code/dist/index.js
var inputRegex = /(^|[^`])`([^`]+)`(?!`)$/;
var pasteRegex = /(^|[^`])`([^`]+)`(?!`)/g;
var Code = Mark2.create({
  name: "code",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  excludes: "_",
  code: true,
  exitable: true,
  parseHTML() {
    return [{ tag: "code" }];
  },
  renderHTML({ HTMLAttributes }) {
    return ["code", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  markdownTokenName: "codespan",
  parseMarkdown: (token, helpers) => {
    return helpers.applyMark("code", [{ type: "text", text: token.text || "" }]);
  },
  renderMarkdown: (node2, h7) => {
    if (!node2.content) {
      return "";
    }
    return `\`${h7.renderChildren(node2.content)}\``;
  },
  addCommands() {
    return {
      setCode: () => ({ commands }) => {
        return commands.setMark(this.name);
      },
      toggleCode: () => ({ commands }) => {
        return commands.toggleMark(this.name);
      },
      unsetCode: () => ({ commands }) => {
        return commands.unsetMark(this.name);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-e": () => this.editor.commands.toggleCode()
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: inputRegex,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: pasteRegex,
        type: this.type
      })
    ];
  }
});
var index_default2 = Code;

// ../../node_modules/.pnpm/@tiptap+extension-italic@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-italic/dist/index.js
var starInputRegex2 = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/;
var starPasteRegex2 = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g;
var underscoreInputRegex2 = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/;
var underscorePasteRegex2 = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;
var Italic = Mark2.create({
  name: "italic",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "em"
      },
      {
        tag: "i",
        getAttrs: (node2) => node2.style.fontStyle !== "normal" && null
      },
      {
        style: "font-style=normal",
        clearMark: (mark2) => mark2.type.name === this.name
      },
      {
        style: "font-style=italic"
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["em", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      setItalic: () => ({ commands }) => {
        return commands.setMark(this.name);
      },
      toggleItalic: () => ({ commands }) => {
        return commands.toggleMark(this.name);
      },
      unsetItalic: () => ({ commands }) => {
        return commands.unsetMark(this.name);
      }
    };
  },
  markdownTokenName: "em",
  parseMarkdown: (token, helpers) => {
    return helpers.applyMark("italic", helpers.parseInline(token.tokens || []));
  },
  renderMarkdown: (node2, h7) => {
    return `*${h7.renderChildren(node2)}*`;
  },
  addKeyboardShortcuts() {
    return {
      "Mod-i": () => this.editor.commands.toggleItalic(),
      "Mod-I": () => this.editor.commands.toggleItalic()
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: starInputRegex2,
        type: this.type
      }),
      markInputRule({
        find: underscoreInputRegex2,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: starPasteRegex2,
        type: this.type
      }),
      markPasteRule({
        find: underscorePasteRegex2,
        type: this.type
      })
    ];
  }
});
var index_default3 = Italic;

// ../../node_modules/.pnpm/@tiptap+extension-strike@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-strike/dist/index.js
var inputRegex2 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/;
var pasteRegex2 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g;
var Strike = Mark2.create({
  name: "strike",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "s"
      },
      {
        tag: "del"
      },
      {
        tag: "strike"
      },
      {
        style: "text-decoration",
        consuming: false,
        getAttrs: (style3) => style3.includes("line-through") ? {} : false
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["s", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  markdownTokenName: "del",
  parseMarkdown: (token, helpers) => {
    return helpers.applyMark("strike", helpers.parseInline(token.tokens || []));
  },
  renderMarkdown: (node2, h7) => {
    return `~~${h7.renderChildren(node2)}~~`;
  },
  addCommands() {
    return {
      setStrike: () => ({ commands }) => {
        return commands.setMark(this.name);
      },
      toggleStrike: () => ({ commands }) => {
        return commands.toggleMark(this.name);
      },
      unsetStrike: () => ({ commands }) => {
        return commands.unsetMark(this.name);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-s": () => this.editor.commands.toggleStrike()
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: inputRegex2,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: pasteRegex2,
        type: this.type
      })
    ];
  }
});
var index_default4 = Strike;

// ../../node_modules/.pnpm/@tiptap+extension-underline@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-underline/dist/index.js
var Underline = Mark2.create({
  name: "underline",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "u"
      },
      {
        style: "text-decoration",
        consuming: false,
        getAttrs: (style3) => style3.includes("underline") ? {} : false
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["u", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  parseMarkdown(token, helpers) {
    return helpers.applyMark(this.name || "underline", helpers.parseInline(token.tokens || []));
  },
  renderMarkdown(node2, helpers) {
    return `++${helpers.renderChildren(node2)}++`;
  },
  markdownTokenizer: {
    name: "underline",
    level: "inline",
    start(src) {
      return src.indexOf("++");
    },
    tokenize(src, _tokens, lexer) {
      const rule = /^(\+\+)([\s\S]+?)(\+\+)/;
      const match2 = rule.exec(src);
      if (!match2) {
        return void 0;
      }
      const innerContent = match2[2].trim();
      return {
        type: "underline",
        raw: match2[0],
        text: innerContent,
        tokens: lexer.inlineTokens(innerContent)
      };
    }
  },
  addCommands() {
    return {
      setUnderline: () => ({ commands }) => {
        return commands.setMark(this.name);
      },
      toggleUnderline: () => ({ commands }) => {
        return commands.toggleMark(this.name);
      },
      unsetUnderline: () => ({ commands }) => {
        return commands.unsetMark(this.name);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-u": () => this.editor.commands.toggleUnderline(),
      "Mod-U": () => this.editor.commands.toggleUnderline()
    };
  }
});
var index_default5 = Underline;

// ../../node_modules/.pnpm/prosemirror-highlight@0.13.0_@shikijs+types@3.13.0_@types+hast@3.0.4_highlight.js@11.11_df16c183cc63c612ec9e976187502a02/node_modules/prosemirror-highlight/dist/index.js
var DecorationCache = class _DecorationCache {
  constructor(cache) {
    this.cache = new Map(cache);
  }
  /**
   * Gets the cache entry at the given doc position, or null if it doesn't exist
   * @param pos The doc position of the node you want the cache for
   */
  get(pos) {
    return this.cache.get(pos);
  }
  /**
   * Sets the cache entry at the given position with the give node/decoration
   * values
   * @param pos The doc position of the node to set the cache for
   * @param node The node to place in cache
   * @param decorations The decorations to place in cache
   */
  set(pos, node2, decorations) {
    if (pos < 0) {
      return;
    }
    this.cache.set(pos, [node2, decorations]);
  }
  /**
   * Removes the value at the oldPos (if it exists) and sets the new position to
   * the given values
   * @param oldPos The old node position to overwrite
   * @param newPos The new node position to set the cache for
   * @param node The new node to place in cache
   * @param decorations The new decorations to place in cache
   */
  replace(oldPos, newPos, node2, decorations) {
    this.remove(oldPos);
    this.set(newPos, node2, decorations);
  }
  /**
   * Removes the cache entry at the given position
   * @param pos The doc position to remove from cache
   */
  remove(pos) {
    this.cache.delete(pos);
  }
  /**
   * Invalidates the cache by removing all decoration entries on nodes that have
   * changed, updating the positions of the nodes that haven't and removing all
   * the entries that have been deleted; NOTE: this does not affect the current
   * cache, but returns an entirely new one
   * @param tr A transaction to map the current cache to
   */
  invalidate(tr4) {
    const returnCache = new _DecorationCache(this.cache);
    const mapping = tr4.mapping;
    this.cache.forEach(([node2, decorations], pos) => {
      if (pos < 0) {
        return;
      }
      const result = mapping.mapResult(pos);
      const mappedNode = tr4.doc.nodeAt(result.pos);
      if (result.deleted || !(mappedNode == null ? void 0 : mappedNode.eq(node2))) {
        returnCache.remove(pos);
      } else if (pos !== result.pos) {
        const updatedDecorations = decorations.map((d) => {
          return d.map(mapping, 0, 0);
        }).filter((d) => d != null);
        returnCache.replace(pos, result.pos, mappedNode, updatedDecorations);
      }
    });
    return returnCache;
  }
};
function createHighlightPlugin({
  parser,
  nodeTypes = ["code_block", "codeBlock"],
  languageExtractor = (node2) => node2.attrs.language
}) {
  const key2 = new PluginKey("prosemirror-highlight");
  return new Plugin({
    key: key2,
    state: {
      init(_2, instance) {
        const cache = new DecorationCache();
        const [decorations, promises] = calculateDecoration(
          instance.doc,
          parser,
          nodeTypes,
          languageExtractor,
          cache
        );
        return { cache, decorations, promises };
      },
      apply: (tr4, data) => {
        const cache = data.cache.invalidate(tr4);
        const refresh = !!tr4.getMeta("prosemirror-highlight-refresh");
        if (!tr4.docChanged && !refresh) {
          const decorations2 = data.decorations.map(tr4.mapping, tr4.doc);
          const promises2 = data.promises;
          return { cache, decorations: decorations2, promises: promises2 };
        }
        const [decorations, promises] = calculateDecoration(
          tr4.doc,
          parser,
          nodeTypes,
          languageExtractor,
          cache
        );
        return { cache, decorations, promises };
      }
    },
    view: (view) => {
      const promises = /* @__PURE__ */ new Set();
      const refresh = () => {
        if (promises.size > 0) {
          return;
        }
        const tr4 = view.state.tr.setMeta("prosemirror-highlight-refresh", true);
        view.dispatch(tr4);
      };
      const check = () => {
        var _a2;
        const state = key2.getState(view.state);
        for (const promise of (_a2 = state == null ? void 0 : state.promises) != null ? _a2 : []) {
          promises.add(promise);
          promise.then(() => {
            promises.delete(promise);
            refresh();
          }).catch(() => {
            promises.delete(promise);
          });
        }
      };
      check();
      return {
        update: () => {
          check();
        }
      };
    },
    props: {
      decorations(state) {
        var _a2;
        return (_a2 = this.getState(state)) == null ? void 0 : _a2.decorations;
      }
    }
  });
}
function calculateDecoration(doc4, parser, nodeTypes, languageExtractor, cache) {
  const result = [];
  const promises = [];
  doc4.descendants((node2, pos) => {
    if (!node2.type.isTextblock) {
      return true;
    }
    if (nodeTypes.includes(node2.type.name)) {
      const language = languageExtractor(node2);
      const cached = cache.get(pos);
      if (cached) {
        const [_2, decorations] = cached;
        result.push(...decorations);
      } else {
        const decorations = parser({
          content: node2.textContent,
          language: language || void 0,
          pos,
          size: node2.nodeSize
        });
        if (decorations && Array.isArray(decorations)) {
          cache.set(pos, node2, decorations);
          result.push(...decorations);
        } else if (decorations instanceof Promise) {
          cache.remove(pos);
          promises.push(decorations);
        }
      }
    }
    return false;
  });
  return [DecorationSet.create(doc4, result), promises];
}

// ../../node_modules/.pnpm/prosemirror-highlight@0.13.0_@shikijs+types@3.13.0_@types+hast@3.0.4_highlight.js@11.11_df16c183cc63c612ec9e976187502a02/node_modules/prosemirror-highlight/dist/shiki.js
function createParser(highlighter, options2) {
  return function parser({ content: content5, language, pos, size: size5 }) {
    var _a2;
    const decorations = [];
    const { tokens, fg, bg, rootStyle } = highlighter.codeToTokens(content5, {
      lang: language,
      // Use provided options for themes or just use first loaded theme
      ...options2 != null ? options2 : {
        theme: highlighter.getLoadedThemes()[0]
      }
    });
    const style3 = rootStyle || (fg && bg ? `--prosemirror-highlight:${fg};--prosemirror-highlight-bg:${bg}` : "");
    if (style3) {
      const decoration = Decoration.node(pos, pos + size5, { style: style3 });
      decorations.push(decoration);
    }
    let from4 = pos + 1;
    for (const line of tokens) {
      for (const token of line) {
        const to2 = from4 + token.content.length;
        const decoration = Decoration.inline(from4, to2, {
          // When using `options.themes` the `htmlStyle` field will be set, otherwise `color` will be set
          style: stringifyTokenStyle(
            (_a2 = token.htmlStyle) != null ? _a2 : `color: ${token.color}`
          ),
          class: "shiki"
        });
        decorations.push(decoration);
        from4 = to2;
      }
      from4 += 1;
    }
    return decorations;
  };
}
function stringifyTokenStyle(token) {
  if (typeof token === "string") return token;
  return Object.entries(token).map(([key2, value]) => `${key2}:${value}`).join(";");
}

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/defaultBlocks-DvCGYzqu.js
var Oe = Object.defineProperty;
var _e = (e2, t2, n) => t2 in e2 ? Oe(e2, t2, { enumerable: true, configurable: true, writable: true, value: n }) : e2[t2] = n;
var M3 = (e2, t2, n) => _e(e2, typeof t2 != "symbol" ? t2 + "" : t2, n);
var mt2 = () => typeof navigator < "u" && (/Mac/.test(navigator.platform) || /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent));
function L2(e2, t2 = "Ctrl") {
  return mt2() ? e2.replace("Mod", "⌘") : e2.replace("Mod", t2);
}
function D2(...e2) {
  return [
    // Converts to & from set to remove duplicates.
    ...new Set(
      e2.filter((t2) => t2).join(" ").split(" ")
    )
  ].join(" ");
}
function gt2(e2, t2, n, o2) {
  const r4 = document.createElement("div");
  r4.className = D2(
    "bn-block-content",
    n.class
  ), r4.setAttribute("data-content-type", e2);
  for (const [s2, i3] of Object.entries(n))
    s2 !== "class" && r4.setAttribute(s2, i3);
  const a3 = document.createElement(t2);
  a3.className = D2(
    "bn-inline-content",
    o2.class
  );
  for (const [s2, i3] of Object.entries(
    o2
  ))
    s2 !== "class" && a3.setAttribute(s2, i3);
  return r4.appendChild(a3), {
    dom: r4,
    contentDOM: a3
  };
}
var le = (e2, t2) => {
  let n = bt(e2, t2.pmSchema);
  n.type.name === "blockContainer" && (n = n.firstChild);
  const o2 = t2.pmSchema.nodes[n.type.name].spec.toDOM;
  if (o2 === void 0)
    throw new Error(
      "This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`."
    );
  const r4 = o2(n);
  if (typeof r4 != "object" || !("dom" in r4))
    throw new Error(
      "Cannot use this block's default HTML serialization as its corresponding TipTap node's `renderHTML` function does not return an object with the `dom` property."
    );
  return r4;
};
function bt2(e2, t2 = "<br>") {
  const n = e2.querySelectorAll("p");
  if (n.length > 1) {
    const o2 = n[0];
    for (let r4 = 1; r4 < n.length; r4++) {
      const a3 = n[r4];
      o2.innerHTML += t2 + a3.innerHTML, a3.remove();
    }
  }
}
function W(e2) {
  return "data-" + e2.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}
function po(e2) {
  const t2 = e2.split("/");
  return !t2.length || // invalid?
  t2[t2.length - 1] === "" ? e2 : t2[t2.length - 1];
}
function fo(e2) {
  var n;
  const t2 = [
    "mp4",
    "webm",
    "ogg",
    "mov",
    "mkv",
    "flv",
    "avi",
    "wmv",
    "m4v"
  ];
  try {
    const r4 = ((n = new URL(e2).pathname.split(".").pop()) == null ? void 0 : n.toLowerCase()) || "";
    return t2.includes(r4);
  } catch {
    return false;
  }
}
function Ct2(e2) {
  const t2 = {};
  return Object.entries(e2).forEach(([n, o2]) => {
    t2[n] = {
      default: o2.default,
      keepOnSplit: true,
      // Props are displayed in kebab-case as HTML attributes. If a prop's
      // value is the same as its default, we don't display an HTML
      // attribute for it.
      parseHTML: (r4) => {
        const a3 = r4.getAttribute(W(n));
        if (a3 === null)
          return null;
        if (o2.default === void 0 && o2.type === "boolean" || o2.default !== void 0 && typeof o2.default == "boolean")
          return a3 === "true" ? true : a3 === "false" ? false : null;
        if (o2.default === void 0 && o2.type === "number" || o2.default !== void 0 && typeof o2.default == "number") {
          const s2 = parseFloat(a3);
          return !Number.isNaN(s2) && Number.isFinite(s2) ? s2 : null;
        }
        return a3;
      },
      renderHTML: (r4) => r4[n] !== o2.default ? {
        [W(n)]: r4[n]
      } : {}
    };
  }), t2;
}
function kt2(e2, t2, n, o2) {
  const r4 = e2();
  if (r4 === void 0)
    throw new Error("Cannot find node position");
  const s2 = n.state.doc.resolve(r4).node().attrs.id;
  if (!s2)
    throw new Error("Block doesn't have id");
  const i3 = t2.getBlock(s2);
  if (i3.type !== o2)
    throw new Error("Block type does not match");
  return i3;
}
function Z2(e2, t2, n, o2, r4 = false, a3) {
  const s2 = document.createElement("div");
  if (a3 !== void 0)
    for (const [i3, c3] of Object.entries(a3))
      i3 !== "class" && s2.setAttribute(i3, c3);
  s2.className = D2(
    "bn-block-content",
    (a3 == null ? void 0 : a3.class) || ""
  ), s2.setAttribute("data-content-type", t2);
  for (const [i3, c3] of Object.entries(n)) {
    const u2 = o2[i3].default;
    c3 !== u2 && s2.setAttribute(W(i3), c3);
  }
  return r4 && s2.setAttribute("data-file-block", ""), s2.appendChild(e2.dom), e2.contentDOM && (e2.contentDOM.className = D2(
    "bn-inline-content",
    e2.contentDOM.className
  )), {
    ...e2,
    dom: s2
  };
}
function yt2(e2, t2, n) {
  return {
    config: {
      type: e2.type,
      content: e2.content,
      propSchema: t2
    },
    implementation: {
      node: e2.node,
      render: le,
      toExternalHTML: le
    },
    extensions: n
  };
}
function vt(e2, t2) {
  e2.stopEvent = (n) => (n.type === "mousedown" && setTimeout(() => {
    t2.view.dom.blur();
  }, 10), true);
}
function Et(e2, t2) {
  const n = [
    {
      tag: "[data-content-type=" + e2.type + "]",
      contentElement: ".bn-inline-content"
    }
  ];
  return t2.parse && n.push({
    tag: "*",
    getAttrs(o2) {
      var a3;
      if (typeof o2 == "string")
        return false;
      const r4 = (a3 = t2.parse) == null ? void 0 : a3.call(t2, o2);
      return r4 === void 0 ? false : r4;
    },
    // Because we do the parsing ourselves, we want to preserve whitespace for content we've parsed
    preserveWhitespace: true,
    getContent: e2.content === "inline" || e2.content === "none" ? (o2, r4) => {
      var a3;
      if (t2.parseContent)
        return t2.parseContent({
          el: o2,
          schema: r4
        });
      if (e2.content === "inline") {
        const i3 = o2.cloneNode(true);
        return bt2(
          i3,
          (a3 = t2.meta) != null && a3.code ? `
` : "<br>"
        ), DOMParser2.fromSchema(r4).parse(i3, {
          topNode: r4.nodes.paragraph.create(),
          preserveWhitespace: true
        }).content;
      }
      return Fragment.empty;
    } : void 0
  }), n;
}
function ho(e2, t2, n, o2) {
  var a3, s2, i3, c3;
  const r4 = t2.node || Node3.create({
    name: e2.type,
    content: e2.content === "inline" ? "inline*" : e2.content === "none" ? "" : e2.content,
    group: "blockContent",
    selectable: ((a3 = t2.meta) == null ? void 0 : a3.selectable) ?? true,
    isolating: ((s2 = t2.meta) == null ? void 0 : s2.isolating) ?? true,
    code: ((i3 = t2.meta) == null ? void 0 : i3.code) ?? false,
    defining: ((c3 = t2.meta) == null ? void 0 : c3.defining) ?? true,
    priority: o2,
    addAttributes() {
      return Ct2(e2.propSchema);
    },
    parseHTML() {
      return Et(e2, t2);
    },
    renderHTML({ HTMLAttributes: l2 }) {
      var d;
      const u2 = document.createElement("div");
      return Z2(
        {
          dom: u2,
          contentDOM: e2.content === "inline" ? u2 : void 0
        },
        e2.type,
        {},
        e2.propSchema,
        ((d = t2.meta) == null ? void 0 : d.fileBlockAccept) !== void 0,
        l2
      );
    },
    addNodeView() {
      return (l2) => {
        var f6, E4;
        const u2 = this.options.editor, d = kt2(
          l2.getPos,
          u2,
          this.editor,
          e2.type
        ), p4 = ((f6 = this.options.domAttributes) == null ? void 0 : f6.blockContent) || {}, m2 = t2.render.call(
          { blockContentDOMAttributes: p4, props: l2, renderType: "nodeView" },
          d,
          u2
        );
        return ((E4 = t2.meta) == null ? void 0 : E4.selectable) === false && vt(m2, this.editor), m2;
      };
    }
  });
  if (r4.name !== e2.type)
    throw new Error(
      "Node name does not match block type. This is a bug in BlockNote."
    );
  return {
    config: e2,
    implementation: {
      ...t2,
      node: r4,
      render(l2, u2) {
        var p4;
        const d = ((p4 = r4.options.domAttributes) == null ? void 0 : p4.blockContent) || {};
        return t2.render.call(
          {
            blockContentDOMAttributes: d,
            props: void 0,
            renderType: "dom"
          },
          l2,
          u2
        );
      },
      // TODO: this should not have wrapInBlockStructure and generally be a lot simpler
      // post-processing in externalHTMLExporter should not be necessary
      toExternalHTML: (l2, u2) => {
        var p4, m2;
        const d = ((p4 = r4.options.domAttributes) == null ? void 0 : p4.blockContent) || {};
        return ((m2 = t2.toExternalHTML) == null ? void 0 : m2.call(
          { blockContentDOMAttributes: d },
          l2,
          u2
        )) ?? t2.render.call(
          { blockContentDOMAttributes: d, renderType: "dom", props: void 0 },
          l2,
          u2
        );
      }
    },
    extensions: n
  };
}
function mo(e2) {
  return e2;
}
function v2(e2, t2, n) {
  return (o2 = {}) => {
    const r4 = typeof e2 == "function" ? e2(o2) : e2, a3 = typeof t2 == "function" ? t2(o2) : t2, s2 = n ? typeof n == "function" ? n(o2) : n : void 0;
    return {
      config: r4,
      implementation: {
        ...a3,
        // TODO: this should not have wrapInBlockStructure and generally be a lot simpler
        // post-processing in externalHTMLExporter should not be necessary
        toExternalHTML(i3, c3) {
          var u2, d;
          const l2 = (u2 = a3.toExternalHTML) == null ? void 0 : u2.call(
            { blockContentDOMAttributes: this.blockContentDOMAttributes },
            i3,
            c3
          );
          if (l2 !== void 0)
            return Z2(
              l2,
              i3.type,
              i3.props,
              r4.propSchema,
              ((d = a3.meta) == null ? void 0 : d.fileBlockAccept) !== void 0
            );
        },
        render(i3, c3) {
          var d;
          const l2 = a3.render.call(
            {
              blockContentDOMAttributes: this.blockContentDOMAttributes,
              renderType: this.renderType,
              props: this.props
            },
            i3,
            c3
          );
          return Z2(
            l2,
            i3.type,
            i3.props,
            r4.propSchema,
            ((d = a3.meta) == null ? void 0 : d.fileBlockAccept) !== void 0,
            this.blockContentDOMAttributes
          );
        }
      },
      extensions: s2
    };
  };
}
function go(e2, t2, n, o2) {
  return e2.dom.setAttribute("data-inline-content-type", t2), Object.entries(n).filter(([r4, a3]) => {
    const s2 = o2[r4];
    return a3 !== s2.default;
  }).map(([r4, a3]) => [W(r4), a3]).forEach(([r4, a3]) => e2.dom.setAttribute(r4, a3)), e2.contentDOM && e2.contentDOM.setAttribute("data-editable", ""), e2;
}
function bo(e2) {
  return {
    Backspace: ({ editor: t2 }) => {
      const n = t2.state.selection.$from;
      return t2.state.selection.empty && n.node().type.name === e2.type && n.parentOffset === 0;
    }
  };
}
function xt(e2, t2) {
  return {
    config: e2,
    implementation: t2
  };
}
function wt2(e2) {
  return Object.fromEntries(
    Object.entries(e2).map(([t2, n]) => [t2, n.config])
  );
}
function St2(e2) {
  return e2 === "boolean" ? {} : {
    stringValue: {
      default: void 0,
      keepOnSplit: true,
      parseHTML: (t2) => t2.getAttribute("data-value"),
      renderHTML: (t2) => t2.stringValue !== void 0 ? {
        "data-value": t2.stringValue
      } : {}
    }
  };
}
function V2(e2, t2, n, o2) {
  return e2.dom.setAttribute("data-style-type", t2), o2 === "string" && e2.dom.setAttribute("data-value", n), e2.contentDOM && e2.contentDOM.setAttribute("data-editable", ""), e2;
}
function Me(e2, t2) {
  return {
    config: e2,
    implementation: t2
  };
}
function H2(e2, t2) {
  return Me(
    {
      type: e2.name,
      propSchema: t2
    },
    {
      mark: e2,
      render(n, o2) {
        const r4 = o2.pmSchema.marks[e2.name].spec.toDOM;
        if (r4 === void 0)
          throw new Error(
            "This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`."
          );
        const a3 = o2.pmSchema.mark(e2.name, {
          stringValue: n
        }), s2 = DOMSerializer.renderSpec(
          document,
          r4(a3, true)
        );
        if (typeof s2 != "object" || !("dom" in s2))
          throw new Error(
            "Cannot use this block's default HTML serialization as its corresponding TipTap mark's `renderHTML` function does not return an object with the `dom` property."
          );
        return s2;
      },
      toExternalHTML(n, o2) {
        const r4 = o2.pmSchema.marks[e2.name].spec.toDOM;
        if (r4 === void 0)
          throw new Error(
            "This block has no default HTML serialization as its corresponding TipTap node doesn't implement `renderHTML`."
          );
        const a3 = o2.pmSchema.mark(e2.name, {
          stringValue: n
        }), s2 = DOMSerializer.renderSpec(
          document,
          r4(a3, true)
        );
        if (typeof s2 != "object" || !("dom" in s2))
          throw new Error(
            "Cannot use this block's default HTML serialization as its corresponding TipTap mark's `renderHTML` function does not return an object with the `dom` property."
          );
        return s2;
      }
    }
  );
}
function Mt2(e2) {
  return Object.fromEntries(
    Object.entries(e2).map(([t2, n]) => [t2, n.config])
  );
}
function Lt(e2, t2) {
  const n = [
    {
      tag: `[data-style-type="${e2.type}"]`,
      contentElement: (o2) => {
        const r4 = o2;
        return r4.matches("[data-editable]") ? r4 : r4.querySelector("[data-editable]") || r4;
      }
    }
  ];
  return t2 && n.push({
    tag: "*",
    // By default, styles can overlap each other, so the rules should not
    // completely consume the element they parse (which can have multiple
    // styles).
    consuming: false,
    getAttrs(o2) {
      if (typeof o2 == "string")
        return false;
      const r4 = t2 == null ? void 0 : t2(o2);
      return r4 === void 0 ? false : { stringValue: r4 };
    }
  }), n;
}
function Le(e2, t2) {
  const n = Mark2.create({
    name: e2.type,
    addAttributes() {
      return St2(e2.propSchema);
    },
    parseHTML() {
      return Lt(e2, t2.parse);
    },
    renderHTML({ mark: o2 }) {
      const r4 = (t2.toExternalHTML || t2.render)(o2.attrs.stringValue);
      return V2(
        r4,
        e2.type,
        o2.attrs.stringValue,
        e2.propSchema
      );
    },
    addMarkView() {
      return ({ mark: o2 }) => {
        const r4 = t2.render(o2.attrs.stringValue);
        return V2(
          r4,
          e2.type,
          o2.attrs.stringValue,
          e2.propSchema
        );
      };
    }
  });
  return Me(e2, {
    ...t2,
    mark: n,
    render: (o2) => {
      const r4 = t2.render(o2);
      return V2(
        r4,
        e2.type,
        o2,
        e2.propSchema
      );
    },
    toExternalHTML: (o2) => {
      const r4 = (t2.toExternalHTML || t2.render)(o2);
      return V2(
        r4,
        e2.type,
        o2,
        e2.propSchema
      );
    }
  });
}
function Tt2(e2, t2) {
  let n, o2;
  if (t2.firstChild.descendants((r4, a3) => n ? false : !Bt(r4) || r4.attrs.id !== e2 ? true : (n = r4, o2 = a3 + 1, false)), !(n === void 0 || o2 === void 0))
    return {
      node: n,
      posBeforeNode: o2
    };
}
function Bt(e2) {
  return e2.type.isInGroup("bnBlock");
}
var ko = (e2, t2) => ({
  tr: n,
  dispatch: o2
}) => (o2 && K4(n, e2, t2), true);
function K4(e2, t2, n, o2, r4) {
  const a3 = It(e2.doc.resolve(t2));
  let s2 = null;
  a3.blockNoteType === "table" && (s2 = Pt2(e2));
  const i3 = ht(e2);
  if (o2 !== void 0 && r4 !== void 0 && o2 > r4)
    throw new Error("Invalid replaceFromPos or replaceToPos");
  const c3 = i3.nodes[a3.blockNoteType], l2 = i3.nodes[n.type || a3.blockNoteType], u2 = l2.isInGroup("bnBlock") ? l2 : i3.nodes.blockContainer;
  if (a3.isBlockContainer && l2.isInGroup("blockContent")) {
    const d = o2 !== void 0 && o2 > a3.blockContent.beforePos && o2 < a3.blockContent.afterPos ? o2 - a3.blockContent.beforePos - 1 : void 0, p4 = r4 !== void 0 && r4 > a3.blockContent.beforePos && r4 < a3.blockContent.afterPos ? r4 - a3.blockContent.beforePos - 1 : void 0;
    de(n, e2, a3), At2(
      n,
      e2,
      c3,
      l2,
      a3,
      d,
      p4
    );
  } else if (!a3.isBlockContainer && l2.isInGroup("bnBlock"))
    de(n, e2, a3);
  else {
    const d = L(a3.bnBlock.node, i3);
    e2.replaceWith(
      a3.bnBlock.beforePos,
      a3.bnBlock.afterPos,
      bt(
        {
          children: d.children,
          // if no children are passed in, use existing children
          ...n
        },
        i3
      )
    );
    return;
  }
  e2.setNodeMarkup(a3.bnBlock.beforePos, u2, {
    ...a3.bnBlock.node.attrs,
    ...n.props
  }), s2 && Nt(e2, a3, s2);
}
function At2(e2, t2, n, o2, r4, a3, s2) {
  const i3 = ht(t2);
  let c3 = "keep";
  if (e2.content)
    if (typeof e2.content == "string")
      c3 = T(
        [e2.content],
        i3,
        o2.name
      );
    else if (Array.isArray(e2.content))
      c3 = T(e2.content, i3, o2.name);
    else if (e2.content.type === "tableContent")
      c3 = kt(e2.content, i3);
    else
      throw new O(e2.content.type);
  else
    n.spec.content === "" || o2.spec.content !== n.spec.content && (c3 = []);
  if (c3 === "keep")
    t2.setNodeMarkup(r4.blockContent.beforePos, o2, {
      ...r4.blockContent.node.attrs,
      ...e2.props
    });
  else if (a3 !== void 0 || s2 !== void 0) {
    t2.setNodeMarkup(r4.blockContent.beforePos, o2, {
      ...r4.blockContent.node.attrs,
      ...e2.props
    });
    const l2 = r4.blockContent.beforePos + 1 + (a3 ?? 0), u2 = r4.blockContent.beforePos + 1 + (s2 ?? r4.blockContent.node.content.size), d = t2.doc.resolve(r4.blockContent.beforePos).depth, p4 = t2.doc.resolve(l2).depth, m2 = t2.doc.resolve(u2).depth;
    t2.replace(
      l2,
      u2,
      new Slice(
        Fragment.from(c3),
        p4 - d - 1,
        m2 - d - 1
      )
    );
  } else
    t2.replaceWith(
      r4.blockContent.beforePos,
      r4.blockContent.afterPos,
      o2.createChecked(
        {
          ...r4.blockContent.node.attrs,
          ...e2.props
        },
        c3
      )
    );
}
function de(e2, t2, n) {
  const o2 = ht(t2);
  if (e2.children !== void 0 && e2.children.length > 0) {
    const r4 = e2.children.map((a3) => bt(a3, o2));
    if (n.childContainer)
      t2.step(
        new ReplaceStep(
          n.childContainer.beforePos + 1,
          n.childContainer.afterPos - 1,
          new Slice(Fragment.from(r4), 0, 0)
        )
      );
    else {
      if (!n.isBlockContainer)
        throw new Error("impossible");
      t2.insert(
        n.blockContent.afterPos,
        o2.nodes.blockGroup.createChecked({}, r4)
      );
    }
  }
}
function yo(e2, t2, n, o2, r4) {
  const a3 = typeof t2 == "string" ? t2 : t2.id, s2 = Tt2(a3, e2.doc);
  if (!s2)
    throw new Error(`Block with ID ${a3} not found`);
  K4(
    e2,
    s2.posBeforeNode,
    n,
    o2,
    r4
  );
  const i3 = e2.doc.resolve(s2.posBeforeNode + 1).node(), c3 = ht(e2);
  return L(i3, c3);
}
function Pt2(e2) {
  const t2 = "selection" in e2 ? e2.selection : null;
  if (!(t2 instanceof TextSelection))
    return null;
  const n = e2.doc.resolve(t2.head);
  let o2 = -1, r4 = -1;
  for (let w3 = n.depth; w3 >= 0; w3--) {
    const x5 = n.node(w3).type.name;
    if (o2 < 0 && (x5 === "tableCell" || x5 === "tableHeader") && (o2 = w3), x5 === "table") {
      r4 = w3;
      break;
    }
  }
  if (o2 < 0 || r4 < 0)
    return null;
  const a3 = n.before(o2), s2 = n.before(r4), i3 = e2.doc.nodeAt(s2);
  if (!i3 || i3.type.name !== "table")
    return null;
  const c3 = TableMap.get(i3), l2 = a3 - (s2 + 1), u2 = c3.map.indexOf(l2);
  if (u2 < 0)
    return null;
  const d = Math.floor(u2 / c3.width), p4 = u2 % c3.width, f6 = a3 + 1 + 1, E4 = Math.max(0, t2.head - f6);
  return { row: d, col: p4, offset: E4 };
}
function Nt(e2, t2, n) {
  var w3;
  if (t2.blockNoteType !== "table")
    return false;
  let o2 = -1;
  if (t2.isBlockContainer)
    o2 = e2.mapping.map(t2.blockContent.beforePos);
  else {
    const x5 = e2.mapping.map(t2.bnBlock.beforePos), P4 = x5 + (((w3 = e2.doc.nodeAt(x5)) == null ? void 0 : w3.nodeSize) || 0);
    e2.doc.nodesBetween(x5, P4, (g, S4) => g.type.name === "table" ? (o2 = S4, false) : true);
  }
  const r4 = o2 >= 0 ? e2.doc.nodeAt(o2) : null;
  if (!r4 || r4.type.name !== "table")
    return false;
  const a3 = TableMap.get(r4), s2 = Math.max(0, Math.min(n.row, a3.height - 1)), i3 = Math.max(0, Math.min(n.col, a3.width - 1)), c3 = s2 * a3.width + i3, l2 = a3.map[c3];
  if (l2 == null)
    return false;
  const d = o2 + 1 + l2 + 1, p4 = e2.doc.nodeAt(d), m2 = d + 1, f6 = p4 ? p4.content.size : 0, E4 = m2 + Math.max(0, Math.min(n.offset, f6));
  return "selection" in e2 && e2.setSelection(TextSelection.create(e2.doc, E4)), true;
}
var T2 = {
  gray: {
    text: "#9b9a97",
    background: "#ebeced"
  },
  brown: {
    text: "#64473a",
    background: "#e9e5e3"
  },
  red: {
    text: "#e03e3e",
    background: "#fbe4e4"
  },
  orange: {
    text: "#d9730d",
    background: "#f6e9d9"
  },
  yellow: {
    text: "#dfab01",
    background: "#fbf3db"
  },
  green: {
    text: "#4d6461",
    background: "#ddedea"
  },
  blue: {
    text: "#0b6e99",
    background: "#ddebf1"
  },
  purple: {
    text: "#6940a5",
    background: "#eae4f2"
  },
  pink: {
    text: "#ad1a72",
    background: "#f4dfeb"
  }
};
var h3 = {
  backgroundColor: {
    default: "default"
  },
  textColor: {
    default: "default"
  },
  textAlignment: {
    default: "left",
    values: ["left", "center", "right", "justify"]
  }
};
var y = (e2) => {
  const t2 = {};
  return e2.hasAttribute("data-background-color") ? t2.backgroundColor = e2.getAttribute("data-background-color") : e2.style.backgroundColor && (t2.backgroundColor = e2.style.backgroundColor), e2.hasAttribute("data-text-color") ? t2.textColor = e2.getAttribute("data-text-color") : e2.style.color && (t2.textColor = e2.style.color), t2.textAlignment = h3.textAlignment.values.includes(
    e2.style.textAlign
  ) ? e2.style.textAlign : void 0, t2;
};
var A2 = (e2, t2) => {
  e2.backgroundColor && e2.backgroundColor !== h3.backgroundColor.default && (t2.style.backgroundColor = e2.backgroundColor in T2 ? T2[e2.backgroundColor].background : e2.backgroundColor), e2.textColor && e2.textColor !== h3.textColor.default && (t2.style.color = e2.textColor in T2 ? T2[e2.textColor].text : e2.textColor), e2.textAlignment && e2.textAlignment !== h3.textAlignment.default && (t2.style.textAlign = e2.textAlignment);
};
var Eo = (e2 = "backgroundColor") => ({
  default: h3.backgroundColor.default,
  parseHTML: (t2) => t2.hasAttribute("data-background-color") ? t2.getAttribute("data-background-color") : t2.style.backgroundColor ? t2.style.backgroundColor : h3.backgroundColor.default,
  renderHTML: (t2) => t2[e2] === h3.backgroundColor.default ? {} : {
    "data-background-color": t2[e2]
  }
});
var xo = (e2 = "textColor") => ({
  default: h3.textColor.default,
  parseHTML: (t2) => t2.hasAttribute("data-text-color") ? t2.getAttribute("data-text-color") : t2.style.color ? t2.style.color : h3.textColor.default,
  renderHTML: (t2) => t2[e2] === h3.textColor.default ? {} : {
    "data-text-color": t2[e2]
  }
});
var $3 = (e2, t2) => {
  const n = e2.querySelector(
    t2
  );
  if (!n)
    return;
  const o2 = e2.querySelector("figcaption"), r4 = (o2 == null ? void 0 : o2.textContent) ?? void 0;
  return { targetElement: n, caption: r4 };
};
var I2 = a(({ editor: e2 }) => {
  const t2 = f(void 0);
  function n() {
    t2.setState(void 0);
  }
  return {
    key: "filePanel",
    store: t2,
    mount({ signal: o2 }) {
      const r4 = e2.onChange(
        n,
        // Don't trigger if the changes are caused by a remote user.
        false
      ), a3 = e2.onSelectionChange(
        n,
        // Don't trigger if the changes are caused by a remote user.
        false
      );
      o2.addEventListener("abort", () => {
        r4(), a3();
      });
    },
    closeMenu: n,
    showMenu(o2) {
      t2.setState(o2);
    }
  };
});
var Ht2 = (e2, t2, n) => {
  const o2 = document.createElement("div");
  o2.className = "bn-add-file-button";
  const r4 = document.createElement("div");
  r4.className = "bn-add-file-button-icon", n ? r4.appendChild(n) : r4.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M3 8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8ZM10 4V9H5V20H19V4H10Z"></path></svg>', o2.appendChild(r4);
  const a3 = document.createElement("p");
  a3.className = "bn-add-file-button-text", a3.innerHTML = e2.type in t2.dictionary.file_blocks.add_button_text ? t2.dictionary.file_blocks.add_button_text[e2.type] : t2.dictionary.file_blocks.add_button_text.file, o2.appendChild(a3);
  const s2 = (c3) => {
    c3.preventDefault(), c3.stopPropagation();
  }, i3 = () => {
    var c3;
    t2.isEditable && ((c3 = t2.getExtension(I2)) == null || c3.showMenu(e2.id));
  };
  return o2.addEventListener(
    "mousedown",
    s2,
    true
  ), o2.addEventListener("click", i3, true), {
    dom: o2,
    destroy: () => {
      o2.removeEventListener(
        "mousedown",
        s2,
        true
      ), o2.removeEventListener(
        "click",
        i3,
        true
      );
    }
  };
};
var It2 = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M3 8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8ZM10 4V9H5V20H19V4H10Z"></path></svg>';
var Dt2 = (e2) => {
  const t2 = document.createElement("div");
  t2.className = "bn-file-name-with-icon";
  const n = document.createElement("div");
  n.className = "bn-file-icon", n.innerHTML = It2, t2.appendChild(n);
  const o2 = document.createElement("p");
  return o2.className = "bn-file-name", o2.textContent = e2.props.name, t2.appendChild(o2), {
    dom: t2
  };
};
var Q2 = (e2, t2, n, o2) => {
  const r4 = document.createElement("div");
  if (r4.className = "bn-file-block-content-wrapper", e2.props.url === "") {
    const s2 = Ht2(e2, t2, o2);
    r4.appendChild(s2.dom);
    const i3 = t2.onUploadStart((c3) => {
      if (c3 === e2.id) {
        r4.removeChild(s2.dom);
        const l2 = document.createElement("div");
        l2.className = "bn-file-loading-preview", l2.textContent = "Loading...", r4.appendChild(l2);
      }
    });
    return {
      dom: r4,
      destroy: () => {
        i3(), s2.destroy();
      }
    };
  }
  const a3 = { dom: r4 };
  if (e2.props.showPreview === false || !n) {
    const s2 = Dt2(e2);
    r4.appendChild(s2.dom), a3.destroy = () => {
      var i3;
      (i3 = s2.destroy) == null || i3.call(s2);
    };
  } else
    r4.appendChild(n.dom);
  if (e2.props.caption) {
    const s2 = document.createElement("p");
    s2.className = "bn-file-caption", s2.textContent = e2.props.caption, r4.appendChild(s2);
  }
  return a3;
};
var J2 = (e2, t2) => {
  const n = document.createElement("figure"), o2 = document.createElement("figcaption");
  return o2.textContent = t2, n.appendChild(e2), n.appendChild(o2), { dom: n };
};
var U = (e2, t2) => {
  const n = document.createElement("div"), o2 = document.createElement("p");
  return o2.textContent = t2, n.appendChild(e2), n.appendChild(o2), {
    dom: n
  };
};
var ue = (e2) => ({ url: e2.src || void 0 });
var Ot2 = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M2 16.0001H5.88889L11.1834 20.3319C11.2727 20.405 11.3846 20.4449 11.5 20.4449C11.7761 20.4449 12 20.2211 12 19.9449V4.05519C12 3.93977 11.9601 3.8279 11.887 3.73857C11.7121 3.52485 11.3971 3.49335 11.1834 3.66821L5.88889 8.00007H2C1.44772 8.00007 1 8.44778 1 9.00007V15.0001C1 15.5524 1.44772 16.0001 2 16.0001ZM23 12C23 15.292 21.5539 18.2463 19.2622 20.2622L17.8445 18.8444C19.7758 17.1937 21 14.7398 21 12C21 9.26016 19.7758 6.80629 17.8445 5.15557L19.2622 3.73779C21.5539 5.75368 23 8.70795 23 12ZM18 12C18 10.0883 17.106 8.38548 15.7133 7.28673L14.2842 8.71584C15.3213 9.43855 16 10.64 16 12C16 13.36 15.3213 14.5614 14.2842 15.2841L15.7133 16.7132C17.106 15.6145 18 13.9116 18 12Z"></path></svg>';
var _t3 = (e2) => ({
  type: "audio",
  propSchema: {
    backgroundColor: h3.backgroundColor,
    // File name.
    name: {
      default: ""
    },
    // File url.
    url: {
      default: ""
    },
    // File caption.
    caption: {
      default: ""
    },
    showPreview: {
      default: true
    }
  },
  content: "none"
});
var Vt = (e2 = {}) => (t2) => {
  if (t2.tagName === "AUDIO") {
    if (t2.closest("figure"))
      return;
    const { backgroundColor: n } = y(t2);
    return {
      ...ue(t2),
      backgroundColor: n
    };
  }
  if (t2.tagName === "FIGURE") {
    const n = $3(t2, "audio");
    if (!n)
      return;
    const { targetElement: o2, caption: r4 } = n, { backgroundColor: a3 } = y(t2);
    return {
      ...ue(o2),
      backgroundColor: a3,
      caption: r4
    };
  }
};
var Rt2 = (e2 = {}) => (t2, n) => {
  const o2 = document.createElement("div");
  o2.innerHTML = e2.icon ?? Ot2;
  const r4 = document.createElement("audio");
  return r4.className = "bn-audio", n.resolveFileUrl ? n.resolveFileUrl(t2.props.url).then((a3) => {
    r4.src = a3;
  }) : r4.src = t2.props.url, r4.controls = true, r4.contentEditable = "false", r4.draggable = false, Q2(
    t2,
    n,
    { dom: r4 },
    o2.firstElementChild
  );
};
var Wt = (e2 = {}) => (t2, n) => {
  if (!t2.props.url) {
    const r4 = document.createElement("p");
    return r4.textContent = "Add audio", {
      dom: r4
    };
  }
  let o2;
  return t2.props.showPreview ? (o2 = document.createElement("audio"), o2.src = t2.props.url) : (o2 = document.createElement("a"), o2.href = t2.props.url, o2.textContent = t2.props.name || t2.props.url), t2.props.caption ? t2.props.showPreview ? J2(o2, t2.props.caption) : U(o2, t2.props.caption) : {
    dom: o2
  };
};
var Ft = v2(
  _t3,
  (e2) => ({
    meta: {
      fileBlockAccept: ["audio/*"]
    },
    parse: Vt(e2),
    render: Rt2(e2),
    toExternalHTML: Wt(e2),
    runsBefore: ["file"]
  })
);
var pe = Symbol.for("blocknote.shikiParser");
var j2 = Symbol.for(
  "blocknote.shikiHighlighterPromise"
);
function $t2(e2) {
  const t2 = globalThis;
  let n, o2, r4 = false;
  return createHighlightPlugin({
    parser: (s2) => {
      if (!e2.createHighlighter)
        return !r4 && (console.log(
          "For syntax highlighting of code blocks, you must provide a `createCodeBlockSpec({ createHighlighter: () => ... })` function"
        ), r4 = true), [];
      if (!n)
        return t2[j2] = t2[j2] || e2.createHighlighter(), t2[j2].then(
          (c3) => {
            n = c3;
          }
        );
      const i3 = Te(e2, s2.language);
      return !i3 || i3 === "text" || i3 === "none" || i3 === "plaintext" || i3 === "txt" ? [] : n.getLoadedLanguages().includes(i3) ? (o2 || (o2 = t2[pe] || createParser(n), t2[pe] = o2), o2(s2)) : n.loadLanguage(i3);
    },
    languageExtractor: (s2) => s2.attrs.language,
    nodeTypes: ["codeBlock"]
  });
}
var Ut = ({ defaultLanguage: e2 = "text" }) => ({
  type: "codeBlock",
  propSchema: {
    language: {
      default: e2
    }
  },
  content: "inline"
});
var qt = v2(
  Ut,
  (e2) => ({
    meta: {
      code: true,
      defining: true,
      isolating: false
    },
    parse: (t2) => {
      var r4, a3;
      if (t2.tagName !== "PRE" || t2.childElementCount !== 1 || ((r4 = t2.firstElementChild) == null ? void 0 : r4.tagName) !== "CODE")
        return;
      const n = t2.firstElementChild;
      return { language: n.getAttribute("data-language") || ((a3 = n.className.split(" ").find((s2) => s2.includes("language-"))) == null ? void 0 : a3.replace("language-", "")) };
    },
    parseContent: ({ el: t2, schema: n }) => {
      const o2 = DOMParser2.fromSchema(n), r4 = t2.firstElementChild;
      return o2.parse(r4, {
        preserveWhitespace: "full",
        topNode: n.nodes.codeBlock.create()
      }).content;
    },
    render(t2, n) {
      const o2 = document.createDocumentFragment(), r4 = document.createElement("pre"), a3 = document.createElement("code");
      r4.appendChild(a3);
      let s2;
      if (e2.supportedLanguages) {
        const i3 = document.createElement("select");
        Object.entries(e2.supportedLanguages ?? {}).forEach(
          ([u2, { name: d }]) => {
            const p4 = document.createElement("option");
            p4.value = u2, p4.text = d, i3.appendChild(p4);
          }
        ), i3.value = t2.props.language || e2.defaultLanguage || "text";
        const c3 = (u2) => {
          const d = u2.target.value;
          n.updateBlock(t2.id, { props: { language: d } });
        };
        i3.addEventListener("change", c3), s2 = () => i3.removeEventListener("change", c3);
        const l2 = document.createElement("div");
        l2.contentEditable = "false", l2.appendChild(i3), o2.appendChild(l2);
      }
      return o2.appendChild(r4), {
        dom: o2,
        contentDOM: a3,
        destroy: () => {
          s2 == null || s2();
        }
      };
    },
    toExternalHTML(t2) {
      const n = document.createElement("pre"), o2 = document.createElement("code");
      return o2.className = `language-${t2.props.language}`, o2.dataset.language = t2.props.language, n.appendChild(o2), {
        dom: n,
        contentDOM: o2
      };
    }
  }),
  (e2) => [
    a({
      key: "code-block-highlighter",
      prosemirrorPlugins: [$t2(e2)]
    }),
    a({
      key: "code-block-keyboard-shortcuts",
      keyboardShortcuts: {
        Delete: ({ editor: t2 }) => t2.transact((n) => {
          const { block: o2 } = t2.getTextCursorPosition();
          if (o2.type !== "codeBlock")
            return false;
          const { $from: r4 } = n.selection;
          return r4.parent.textContent ? false : (t2.removeBlocks([o2]), true);
        }),
        Tab: ({ editor: t2 }) => e2.indentLineWithTab === false ? false : t2.transact((n) => {
          const { block: o2 } = t2.getTextCursorPosition();
          return o2.type === "codeBlock" ? (n.insertText("  "), true) : false;
        }),
        Enter: ({ editor: t2 }) => t2.transact((n) => {
          const { block: o2, nextBlock: r4 } = t2.getTextCursorPosition();
          if (o2.type !== "codeBlock")
            return false;
          const { $from: a3 } = n.selection, s2 = a3.parentOffset === a3.parent.nodeSize - 2, i3 = a3.parent.textContent.endsWith(`

`);
          if (s2 && i3) {
            if (n.delete(a3.pos - 2, a3.pos), r4)
              return t2.setTextCursorPosition(r4, "start"), true;
            const [c3] = t2.insertBlocks(
              [{ type: "paragraph" }],
              o2,
              "after"
            );
            return t2.setTextCursorPosition(c3, "start"), true;
          }
          return n.insertText(`
`), true;
        }),
        "Shift-Enter": ({ editor: t2 }) => t2.transact(() => {
          const { block: n } = t2.getTextCursorPosition();
          if (n.type !== "codeBlock")
            return false;
          const [o2] = t2.insertBlocks(
            // insert a new paragraph
            [{ type: "paragraph" }],
            n,
            "after"
          );
          return t2.setTextCursorPosition(o2, "start"), true;
        })
      },
      inputRules: [
        {
          find: /^```(.*?)\s$/,
          replace: ({ match: t2 }) => {
            const n = t2[1].trim();
            return {
              type: "codeBlock",
              props: {
                language: {
                  language: Te(e2, n) ?? n
                }.language
              },
              content: []
            };
          }
        }
      ]
    })
  ]
);
function Te(e2, t2) {
  var n;
  return (n = Object.entries(e2.supportedLanguages ?? {}).find(
    ([o2, { aliases: r4 }]) => (r4 == null ? void 0 : r4.includes(t2)) || o2 === t2
  )) == null ? void 0 : n[0];
}
var jt = () => ({
  type: "divider",
  propSchema: {},
  content: "none"
});
var Gt = v2(
  jt,
  {
    meta: {
      isolating: false
    },
    parse(e2) {
      if (e2.tagName === "HR")
        return {};
    },
    render() {
      return {
        dom: document.createElement("hr")
      };
    }
  },
  [
    a({
      key: "divider-block-shortcuts",
      inputRules: [
        {
          find: new RegExp("^---$"),
          replace() {
            return { type: "divider", props: {}, content: [] };
          }
        }
      ]
    })
  ]
);
var fe = (e2) => ({ url: e2.src || void 0 });
var Zt = () => ({
  type: "file",
  propSchema: {
    backgroundColor: h3.backgroundColor,
    // File name.
    name: {
      default: ""
    },
    // File url.
    url: {
      default: ""
    },
    // File caption.
    caption: {
      default: ""
    }
  },
  content: "none"
});
var zt = () => (e2) => {
  if (e2.tagName === "EMBED") {
    if (e2.closest("figure"))
      return;
    const { backgroundColor: t2 } = y(e2);
    return {
      ...fe(e2),
      backgroundColor: t2
    };
  }
  if (e2.tagName === "FIGURE") {
    const t2 = $3(e2, "embed");
    if (!t2)
      return;
    const { targetElement: n, caption: o2 } = t2, { backgroundColor: r4 } = y(e2);
    return {
      ...fe(n),
      backgroundColor: r4,
      caption: o2
    };
  }
};
var Xt = v2(Zt, {
  meta: {
    fileBlockAccept: ["*/*"]
  },
  parse: zt(),
  render(e2, t2) {
    return Q2(e2, t2);
  },
  toExternalHTML(e2) {
    if (!e2.props.url) {
      const n = document.createElement("p");
      return n.textContent = "Add file", {
        dom: n
      };
    }
    const t2 = document.createElement("a");
    return t2.href = e2.props.url, t2.textContent = e2.props.name || e2.props.url, e2.props.caption ? U(t2, e2.props.caption) : {
      dom: t2
    };
  }
});
var Kt = {
  set: (e2, t2) => window.localStorage.setItem(
    `toggle-${e2.id}`,
    t2 ? "true" : "false"
  ),
  get: (e2) => window.localStorage.getItem(`toggle-${e2.id}`) === "true"
};
var Be = (e2, t2, n, o2 = Kt) => {
  if ("isToggleable" in e2.props && !e2.props.isToggleable)
    return {
      dom: n
    };
  const r4 = document.createElement("div"), a3 = document.createElement("div");
  a3.className = "bn-toggle-wrapper";
  const s2 = document.createElement("button");
  s2.className = "bn-toggle-button", s2.type = "button", s2.innerHTML = // https://fonts.google.com/icons?selected=Material+Symbols+Rounded:chevron_right:FILL@0;wght@700;GRAD@0;opsz@24&icon.query=chevron&icon.style=Rounded&icon.size=24&icon.color=%23e8eaed
  '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="CURRENTCOLOR"><path d="M320-200v-560l440 280-440 280Z"/></svg>';
  const i3 = (f6) => f6.preventDefault();
  s2.addEventListener("mousedown", i3);
  const c3 = () => {
    var f6;
    a3.getAttribute("data-show-children") === "true" ? (a3.setAttribute("data-show-children", "false"), o2.set(t2.getBlock(e2), false), r4.contains(l2) && r4.removeChild(l2)) : (a3.setAttribute("data-show-children", "true"), o2.set(t2.getBlock(e2), true), t2.isEditable && ((f6 = t2.getBlock(e2)) == null ? void 0 : f6.children.length) === 0 && !r4.contains(l2) && r4.appendChild(l2));
  };
  s2.addEventListener("click", c3), a3.appendChild(s2), a3.appendChild(n);
  const l2 = document.createElement("button");
  l2.className = "bn-toggle-add-block-button", l2.type = "button", l2.textContent = t2.dictionary.toggle_blocks.add_block_button;
  const u2 = (f6) => f6.preventDefault();
  l2.addEventListener(
    "mousedown",
    u2
  );
  const d = () => {
    t2.transact(() => {
      const f6 = t2.updateBlock(e2, {
        // Single empty block with default type.
        children: [{}]
      });
      t2.setTextCursorPosition(f6.children[0].id, "end"), t2.focus();
    });
  };
  l2.addEventListener("click", d), r4.appendChild(a3);
  let p4 = e2.children.length;
  const m2 = t2.onChange(() => {
    var E4;
    const f6 = ((E4 = t2.getBlock(e2)) == null ? void 0 : E4.children.length) ?? 0;
    f6 > p4 ? (a3.getAttribute("data-show-children") === "false" && (a3.setAttribute("data-show-children", "true"), o2.set(t2.getBlock(e2), true)), r4.contains(l2) && r4.removeChild(l2)) : f6 === 0 && f6 < p4 && (a3.getAttribute("data-show-children") === "true" && (a3.setAttribute("data-show-children", "false"), o2.set(t2.getBlock(e2), false)), r4.contains(l2) && r4.removeChild(l2)), p4 = f6;
  });
  return o2.get(e2) ? (a3.setAttribute("data-show-children", "true"), t2.isEditable && e2.children.length === 0 && r4.appendChild(l2)) : a3.setAttribute("data-show-children", "false"), {
    dom: r4,
    // Prevents re-renders when the toggle button is clicked.
    ignoreMutation: (f6) => f6 instanceof MutationRecord && // We want to prevent re-renders when the view changes, so we ignore
    // all mutations where the `data-show-children` attribute is changed
    // or the "add block" button is added/removed.
    (f6.type === "attributes" && f6.target === a3 && f6.attributeName === "data-show-children" || f6.type === "childList" && (f6.addedNodes[0] === l2 || f6.removedNodes[0] === l2)),
    destroy: () => {
      s2.removeEventListener("mousedown", i3), s2.removeEventListener("click", c3), l2.removeEventListener(
        "mousedown",
        u2
      ), l2.removeEventListener(
        "click",
        d
      ), m2 == null || m2();
    }
  };
};
var Ae = [1, 2, 3, 4, 5, 6];
var Qt = (e2) => ({ editor: t2 }) => {
  const n = t2.getTextCursorPosition();
  return t2.schema.blockSchema[n.block.type].content !== "inline" ? false : (t2.updateBlock(n.block, {
    type: "heading",
    props: { level: e2 }
  }), true);
};
var Jt2 = ({
  defaultLevel: e2 = 1,
  levels: t2 = Ae,
  allowToggleHeadings: n = true
} = {}) => ({
  type: "heading",
  propSchema: {
    ...h3,
    level: { default: e2, values: t2 },
    ...n ? { isToggleable: { default: false, optional: true } } : {}
  },
  content: "inline"
});
var Yt = v2(
  Jt2,
  ({ allowToggleHeadings: e2 = true } = {}) => ({
    meta: {
      isolating: false
    },
    parse(t2) {
      let n;
      switch (t2.tagName) {
        case "H1":
          n = 1;
          break;
        case "H2":
          n = 2;
          break;
        case "H3":
          n = 3;
          break;
        case "H4":
          n = 4;
          break;
        case "H5":
          n = 5;
          break;
        case "H6":
          n = 6;
          break;
        default:
          return;
      }
      return {
        ...y(t2),
        level: n
      };
    },
    render(t2, n) {
      const o2 = document.createElement(`h${t2.props.level}`);
      return e2 ? { ...Be(t2, n, o2), contentDOM: o2 } : {
        dom: o2,
        contentDOM: o2
      };
    },
    toExternalHTML(t2) {
      const n = document.createElement(`h${t2.props.level}`);
      return A2(t2.props, n), {
        dom: n,
        contentDOM: n
      };
    }
  }),
  ({ levels: e2 = Ae } = {}) => [
    a({
      key: "heading-shortcuts",
      keyboardShortcuts: Object.fromEntries(
        e2.map((t2) => [
          `Mod-Alt-${t2}`,
          Qt(t2)
        ]) ?? []
      ),
      inputRules: e2.map((t2) => ({
        find: new RegExp(`^(#{${t2}})\\s$`),
        replace({ match: n }) {
          return {
            type: "heading",
            props: {
              level: n[1].length
            }
          };
        }
      }))
    })
  ]
);
var Pe = (e2, t2, n, o2, r4) => {
  const { dom: a3, destroy: s2 } = Q2(
    e2,
    t2,
    n,
    r4
  ), i3 = a3;
  i3.style.position = "relative", e2.props.url && e2.props.showPreview && (e2.props.previewWidth ? i3.style.width = `${e2.props.previewWidth}px` : i3.style.width = "fit-content");
  const c3 = document.createElement("div");
  c3.className = "bn-resize-handle", c3.style.left = "4px";
  const l2 = document.createElement("div");
  l2.className = "bn-resize-handle", l2.style.right = "4px";
  const u2 = document.createElement("div");
  u2.style.position = "absolute", u2.style.height = "100%", u2.style.width = "100%";
  let d, p4 = e2.props.previewWidth;
  const m2 = (g) => {
    var ee3, te2;
    if (!d) {
      !t2.isEditable && o2.contains(c3) && o2.contains(l2) && (o2.removeChild(c3), o2.removeChild(l2));
      return;
    }
    let S4;
    const _2 = "touches" in g ? g.touches[0].clientX : g.clientX;
    e2.props.textAlignment === "center" ? d.handleUsed === "left" ? S4 = d.initialWidth + (d.initialClientX - _2) * 2 : S4 = d.initialWidth + (_2 - d.initialClientX) * 2 : d.handleUsed === "left" ? S4 = d.initialWidth + d.initialClientX - _2 : S4 = d.initialWidth + _2 - d.initialClientX, p4 = Math.min(
      Math.max(S4, 64),
      ((te2 = (ee3 = t2.domElement) == null ? void 0 : ee3.firstElementChild) == null ? void 0 : te2.clientWidth) || Number.MAX_VALUE
    ), i3.style.width = `${p4}px`;
  }, f6 = (g) => {
    (!g.target || !i3.contains(g.target) || !t2.isEditable) && o2.contains(c3) && o2.contains(l2) && (o2.removeChild(c3), o2.removeChild(l2)), d && (d = void 0, i3.contains(u2) && i3.removeChild(u2), t2.updateBlock(e2, {
      props: {
        previewWidth: p4
      }
    }));
  }, E4 = () => {
    t2.isEditable && (o2.appendChild(c3), o2.appendChild(l2));
  }, w3 = (g) => {
    g.relatedTarget === c3 || g.relatedTarget === l2 || d || t2.isEditable && o2.contains(c3) && o2.contains(l2) && (o2.removeChild(c3), o2.removeChild(l2));
  }, x5 = (g) => {
    g.preventDefault(), i3.contains(u2) || i3.appendChild(u2);
    const S4 = "touches" in g ? g.touches[0].clientX : g.clientX;
    d = {
      handleUsed: "left",
      initialWidth: i3.clientWidth,
      initialClientX: S4
    };
  }, P4 = (g) => {
    g.preventDefault(), i3.contains(u2) || i3.appendChild(u2);
    const S4 = "touches" in g ? g.touches[0].clientX : g.clientX;
    d = {
      handleUsed: "right",
      initialWidth: i3.clientWidth,
      initialClientX: S4
    };
  };
  return window.addEventListener("mousemove", m2), window.addEventListener("touchmove", m2), window.addEventListener("mouseup", f6), window.addEventListener("touchend", f6), i3.addEventListener("mouseenter", E4), i3.addEventListener("mouseleave", w3), c3.addEventListener(
    "mousedown",
    x5
  ), c3.addEventListener(
    "touchstart",
    x5
  ), l2.addEventListener(
    "mousedown",
    P4
  ), l2.addEventListener(
    "touchstart",
    P4
  ), {
    dom: i3,
    destroy: () => {
      s2 == null || s2(), window.removeEventListener("mousemove", m2), window.removeEventListener("touchmove", m2), window.removeEventListener("mouseup", f6), window.removeEventListener("touchend", f6), i3.removeEventListener("mouseenter", E4), i3.removeEventListener("mouseleave", w3), c3.removeEventListener(
        "mousedown",
        x5
      ), c3.removeEventListener(
        "touchstart",
        x5
      ), l2.removeEventListener(
        "mousedown",
        P4
      ), l2.removeEventListener(
        "touchstart",
        P4
      );
    }
  };
};
var he = (e2) => {
  const t2 = e2.src || void 0, n = e2.width || void 0, o2 = e2.alt || void 0;
  return { url: t2, previewWidth: n, name: o2 };
};
var en = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M5 11.1005L7 9.1005L12.5 14.6005L16 11.1005L19 14.1005V5H5V11.1005ZM4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM15.5 10C14.6716 10 14 9.32843 14 8.5C14 7.67157 14.6716 7 15.5 7C16.3284 7 17 7.67157 17 8.5C17 9.32843 16.3284 10 15.5 10Z"></path></svg>';
var tn = (e2 = {}) => ({
  type: "image",
  propSchema: {
    textAlignment: h3.textAlignment,
    backgroundColor: h3.backgroundColor,
    // File name.
    name: {
      default: ""
    },
    // File url.
    url: {
      default: ""
    },
    // File caption.
    caption: {
      default: ""
    },
    showPreview: {
      default: true
    },
    // File preview width in px.
    previewWidth: {
      default: void 0,
      type: "number"
    }
  },
  content: "none"
});
var nn = (e2 = {}) => (t2) => {
  if (t2.tagName === "IMG") {
    if (t2.closest("figure"))
      return;
    const { backgroundColor: n } = y(t2);
    return {
      ...he(t2),
      backgroundColor: n
    };
  }
  if (t2.tagName === "FIGURE") {
    const n = $3(t2, "img");
    if (!n)
      return;
    const { targetElement: o2, caption: r4 } = n, { backgroundColor: a3 } = y(t2);
    return {
      ...he(o2),
      backgroundColor: a3,
      caption: r4
    };
  }
};
var on = (e2 = {}) => (t2, n) => {
  const o2 = document.createElement("div");
  o2.innerHTML = e2.icon ?? en;
  const r4 = document.createElement("div");
  r4.className = "bn-visual-media-wrapper";
  const a3 = document.createElement("img");
  return a3.className = "bn-visual-media", n.resolveFileUrl ? n.resolveFileUrl(t2.props.url).then((s2) => {
    a3.src = s2;
  }) : a3.src = t2.props.url, a3.alt = t2.props.name || t2.props.caption || "BlockNote image", a3.contentEditable = "false", a3.draggable = false, r4.appendChild(a3), Pe(
    t2,
    n,
    { dom: r4 },
    r4,
    o2.firstElementChild
  );
};
var rn = (e2 = {}) => (t2, n) => {
  if (!t2.props.url) {
    const r4 = document.createElement("p");
    return r4.textContent = "Add image", {
      dom: r4
    };
  }
  let o2;
  return t2.props.showPreview ? (o2 = document.createElement("img"), o2.src = t2.props.url, o2.alt = t2.props.name || t2.props.caption || "BlockNote image", t2.props.previewWidth && (o2.width = t2.props.previewWidth)) : (o2 = document.createElement("a"), o2.href = t2.props.url, o2.textContent = t2.props.name || t2.props.url), t2.props.caption ? t2.props.showPreview ? J2(o2, t2.props.caption) : U(o2, t2.props.caption) : {
    dom: o2
  };
};
var an = v2(
  tn,
  (e2) => ({
    meta: {
      fileBlockAccept: ["image/*"]
    },
    parse: nn(e2),
    render: on(e2),
    toExternalHTML: rn(e2),
    runsBefore: ["file"]
  })
);
var So = (e2, t2, n) => ({
  state: o2,
  dispatch: r4
}) => r4 ? Ne(o2.tr, e2, t2, n) : true;
var Ne = (e2, t2, n, o2) => {
  const r4 = Y2(e2.doc, t2), a3 = Z(r4);
  if (!a3.isBlockContainer)
    return false;
  const s2 = ht(e2), i3 = [
    {
      type: a3.bnBlock.node.type,
      // always keep blockcontainer type
      attrs: o2 ? { ...a3.bnBlock.node.attrs, id: void 0 } : {}
    },
    {
      type: n ? a3.blockContent.node.type : s2.nodes.paragraph,
      attrs: o2 ? { ...a3.blockContent.node.attrs } : {}
    }
  ];
  return e2.split(t2, 2, i3), true;
};
var q = (e2, t2) => {
  const { blockInfo: n, selectionEmpty: o2 } = e2.transact((s2) => ({
    blockInfo: Ot(s2),
    selectionEmpty: s2.selection.anchor === s2.selection.head
  }));
  if (!n.isBlockContainer)
    return false;
  const { bnBlock: r4, blockContent: a3 } = n;
  return a3.node.type.name !== t2 || !o2 ? false : a3.node.childCount === 0 ? (e2.transact((s2) => {
    K4(s2, r4.beforePos, {
      type: "paragraph",
      props: {}
    });
  }), true) : a3.node.childCount > 0 ? e2.transact((s2) => (s2.deleteSelection(), Ne(s2, s2.selection.from, true))) : false;
};
function Y3(e2, t2, n) {
  var d, p4, m2;
  const o2 = DOMParser2.fromSchema(t2), r4 = e2, a3 = document.createElement("div");
  a3.setAttribute("data-node-type", "blockGroup");
  for (const f6 of Array.from(r4.childNodes))
    a3.appendChild(f6.cloneNode(true));
  let s2 = o2.parse(a3, {
    topNode: t2.nodes.blockGroup.create()
  });
  ((p4 = (d = s2.firstChild) == null ? void 0 : d.firstChild) == null ? void 0 : p4.type.name) === "checkListItem" && (s2 = s2.copy(
    s2.content.cut(
      s2.firstChild.firstChild.nodeSize + 2
    )
  ));
  const i3 = (m2 = s2.firstChild) == null ? void 0 : m2.firstChild;
  if (!(i3 != null && i3.isTextblock))
    return Fragment.from(s2);
  const c3 = t2.nodes[n].create(
    {},
    i3.content
  ), l2 = s2.content.cut(
    // +2 for the `blockGroup` node's start and end markers
    i3.nodeSize + 2
  );
  if (l2.size > 0) {
    const f6 = s2.copy(l2);
    return c3.content.addToEnd(f6);
  }
  return c3.content;
}
var sn = () => ({
  type: "bulletListItem",
  propSchema: {
    ...h3
  },
  content: "inline"
});
var cn = v2(
  sn,
  {
    meta: {
      isolating: false
    },
    parse(e2) {
      var n;
      if (e2.tagName !== "LI")
        return;
      const t2 = e2.parentElement;
      if (t2 !== null && (t2.tagName === "UL" || t2.tagName === "DIV" && ((n = t2.parentElement) == null ? void 0 : n.tagName) === "UL"))
        return y(e2);
    },
    // As `li` elements can contain multiple paragraphs, we need to merge their contents
    // into a single one so that ProseMirror can parse everything correctly.
    parseContent: ({ el: e2, schema: t2 }) => Y3(e2, t2, "bulletListItem"),
    render() {
      const e2 = document.createElement("p");
      return {
        dom: e2,
        contentDOM: e2
      };
    },
    toExternalHTML(e2) {
      const t2 = document.createElement("li"), n = document.createElement("p");
      return A2(e2.props, t2), t2.appendChild(n), {
        dom: t2,
        contentDOM: n
      };
    }
  },
  [
    a({
      key: "bullet-list-item-shortcuts",
      keyboardShortcuts: {
        Enter: ({ editor: e2 }) => q(e2, "bulletListItem"),
        "Mod-Shift-8": ({ editor: e2 }) => {
          const t2 = e2.getTextCursorPosition();
          return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, {
            type: "bulletListItem",
            props: {}
          }), true);
        }
      },
      inputRules: [
        {
          find: new RegExp("^[-+*]\\s$"),
          replace({ editor: e2 }) {
            if (Tt(
              e2.prosemirrorState
            ).blockNoteType !== "heading")
              return {
                type: "bulletListItem",
                props: {}
              };
          }
        }
      ]
    })
  ]
);
var ln = () => ({
  type: "checkListItem",
  propSchema: {
    ...h3,
    checked: { default: false, type: "boolean" }
  },
  content: "inline"
});
var dn = v2(
  ln,
  {
    meta: {
      isolating: false
    },
    parse(e2) {
      var n;
      if (e2.tagName === "input")
        return e2.closest("[data-content-type]") || e2.closest("li") ? void 0 : e2.type === "checkbox" ? { checked: e2.checked } : void 0;
      if (e2.tagName !== "LI")
        return;
      const t2 = e2.parentElement;
      if (t2 !== null && (t2.tagName === "UL" || t2.tagName === "DIV" && ((n = t2.parentElement) == null ? void 0 : n.tagName) === "UL")) {
        const o2 = e2.querySelector("input[type=checkbox]") || null;
        return o2 === null ? void 0 : { ...y(e2), checked: o2.checked };
      }
    },
    // As `li` elements can contain multiple paragraphs, we need to merge their contents
    // into a single one so that ProseMirror can parse everything correctly.
    parseContent: ({ el: e2, schema: t2 }) => Y3(e2, t2, "checkListItem"),
    render(e2, t2) {
      const n = document.createDocumentFragment(), o2 = document.createElement("input");
      o2.type = "checkbox", o2.checked = e2.props.checked, e2.props.checked && o2.setAttribute("checked", ""), o2.addEventListener("change", () => {
        t2.updateBlock(e2, { props: { checked: !e2.props.checked } });
      });
      const r4 = document.createElement("p");
      return n.appendChild(o2), n.appendChild(r4), {
        dom: n,
        contentDOM: r4
      };
    },
    toExternalHTML(e2) {
      const t2 = document.createElement("li"), n = document.createElement("input");
      n.type = "checkbox", n.checked = e2.props.checked, e2.props.checked && n.setAttribute("checked", "");
      const o2 = document.createElement("p");
      return A2(e2.props, t2), t2.appendChild(n), t2.appendChild(o2), {
        dom: t2,
        contentDOM: o2
      };
    },
    runsBefore: ["bulletListItem"]
  },
  [
    a({
      key: "check-list-item-shortcuts",
      keyboardShortcuts: {
        Enter: ({ editor: e2 }) => q(e2, "checkListItem"),
        "Mod-Shift-9": ({ editor: e2 }) => {
          const t2 = e2.getTextCursorPosition();
          return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, {
            type: "checkListItem",
            props: {}
          }), true);
        }
      },
      inputRules: [
        {
          find: new RegExp("^\\[\\s*\\]\\s$"),
          replace() {
            return {
              type: "checkListItem",
              props: {
                checked: false
              },
              content: []
            };
          }
        },
        {
          find: new RegExp("^\\[[Xx]\\]\\s$"),
          replace() {
            return {
              type: "checkListItem",
              props: {
                checked: true
              }
            };
          }
        }
      ]
    })
  ]
);
function He(e2, t2, n, o2) {
  let r4 = e2.firstChild.attrs.start || 1, a3 = true;
  const s2 = !!e2.firstChild.attrs.start, i3 = Z({
    posBeforeNode: t2,
    node: e2
  });
  if (!i3.isBlockContainer)
    throw new Error("impossible");
  const c3 = n.doc.resolve(i3.bnBlock.beforePos).nodeBefore, l2 = c3 ? o2.get(c3) : void 0;
  return l2 !== void 0 ? (r4 = l2 + 1, a3 = false) : c3 && Z({
    posBeforeNode: i3.bnBlock.beforePos - c3.nodeSize,
    node: c3
  }).blockNoteType === "numberedListItem" && (r4 = He(
    c3,
    i3.bnBlock.beforePos - c3.nodeSize,
    n,
    o2
  ).index + 1, a3 = false), o2.set(e2, r4), { index: r4, isFirst: a3, hasStart: s2 };
}
function me(e2, t2) {
  const n = /* @__PURE__ */ new Map(), o2 = t2.decorations.map(
    e2.mapping,
    e2.doc
  ), r4 = [];
  e2.doc.nodesBetween(0, e2.doc.nodeSize - 2, (s2, i3) => {
    if (s2.type.name === "blockContainer" && s2.firstChild.type.name === "numberedListItem") {
      const { index: c3, isFirst: l2, hasStart: u2 } = He(
        s2,
        i3,
        e2,
        n
      );
      if (o2.find(
        i3,
        i3 + s2.nodeSize,
        (p4) => p4.index === c3 && p4.isFirst === l2 && p4.hasStart === u2
      ).length === 0) {
        const p4 = e2.doc.nodeAt(i3 + 1);
        r4.push(
          // move in by 1 to account for the block container
          Decoration.node(i3 + 1, i3 + 1 + p4.nodeSize, {
            "data-index": c3.toString()
          })
        );
      }
    }
  });
  const a3 = r4.flatMap(
    (s2) => o2.find(s2.from, s2.to)
  );
  return {
    decorations: o2.remove(a3).add(e2.doc, r4)
  };
}
var un = () => new Plugin({
  key: new PluginKey("numbered-list-indexing-decorations"),
  state: {
    init(e2, t2) {
      return me(t2.tr, {
        decorations: DecorationSet.empty
      });
    },
    apply(e2, t2) {
      return !e2.docChanged && !e2.selectionSet && t2.decorations ? t2 : me(e2, t2);
    }
  },
  props: {
    decorations(e2) {
      var t2;
      return ((t2 = this.getState(e2)) == null ? void 0 : t2.decorations) ?? DecorationSet.empty;
    }
  }
});
var pn = () => ({
  type: "numberedListItem",
  propSchema: {
    ...h3,
    start: { default: void 0, type: "number" }
  },
  content: "inline"
});
var fn = v2(
  pn,
  {
    meta: {
      isolating: false
    },
    parse(e2) {
      var n;
      if (e2.tagName !== "LI")
        return;
      const t2 = e2.parentElement;
      if (t2 !== null && (t2.tagName === "OL" || t2.tagName === "DIV" && ((n = t2.parentElement) == null ? void 0 : n.tagName) === "OL")) {
        const o2 = parseInt(t2.getAttribute("start") || "1"), r4 = y(e2);
        return e2.previousElementSibling || o2 === 1 ? r4 : {
          ...r4,
          start: o2
        };
      }
    },
    // As `li` elements can contain multiple paragraphs, we need to merge their contents
    // into a single one so that ProseMirror can parse everything correctly.
    parseContent: ({ el: e2, schema: t2 }) => Y3(e2, t2, "numberedListItem"),
    render() {
      const e2 = document.createElement("p");
      return {
        dom: e2,
        contentDOM: e2
      };
    },
    toExternalHTML(e2) {
      const t2 = document.createElement("li"), n = document.createElement("p");
      return A2(e2.props, t2), t2.appendChild(n), {
        dom: t2,
        contentDOM: n
      };
    }
  },
  [
    a({
      key: "numbered-list-item-shortcuts",
      inputRules: [
        {
          find: new RegExp("^(\\d+)\\.\\s$"),
          replace({ match: e2, editor: t2 }) {
            if (Tt(
              t2.prosemirrorState
            ).blockNoteType === "heading")
              return;
            const o2 = parseInt(e2[1]);
            return {
              type: "numberedListItem",
              props: {
                start: o2 !== 1 ? o2 : void 0
              }
            };
          }
        }
      ],
      keyboardShortcuts: {
        Enter: ({ editor: e2 }) => q(e2, "numberedListItem"),
        "Mod-Shift-7": ({ editor: e2 }) => {
          const t2 = e2.getTextCursorPosition();
          return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, {
            type: "numberedListItem",
            props: {}
          }), true);
        }
      },
      prosemirrorPlugins: [un()]
    })
  ]
);
var hn = () => ({
  type: "toggleListItem",
  propSchema: {
    ...h3
  },
  content: "inline"
});
var mn = v2(
  hn,
  {
    meta: {
      isolating: false
    },
    render(e2, t2) {
      const n = document.createElement("p");
      return { ...Be(
        e2,
        t2,
        n
      ), contentDOM: n };
    },
    toExternalHTML(e2) {
      const t2 = document.createElement("li"), n = document.createElement("p");
      return A2(e2.props, t2), t2.appendChild(n), {
        dom: t2,
        contentDOM: n
      };
    }
  },
  [
    a({
      key: "toggle-list-item-shortcuts",
      keyboardShortcuts: {
        Enter: ({ editor: e2 }) => q(e2, "toggleListItem"),
        "Mod-Shift-6": ({ editor: e2 }) => {
          const t2 = e2.getTextCursorPosition();
          return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, {
            type: "toggleListItem",
            props: {}
          }), true);
        }
      }
    })
  ]
);
var gn = () => ({
  type: "paragraph",
  propSchema: h3,
  content: "inline"
});
var bn = v2(
  gn,
  {
    meta: {
      isolating: false
    },
    parse: (e2) => {
      var t2;
      if (e2.tagName === "P" && (t2 = e2.textContent) != null && t2.trim())
        return y(e2);
    },
    render: () => {
      const e2 = document.createElement("p");
      return {
        dom: e2,
        contentDOM: e2
      };
    },
    toExternalHTML: (e2) => {
      const t2 = document.createElement("p");
      return A2(e2.props, t2), {
        dom: t2,
        contentDOM: t2
      };
    },
    runsBefore: ["default"]
  },
  [
    a({
      key: "paragraph-shortcuts",
      keyboardShortcuts: {
        "Mod-Alt-0": ({ editor: e2 }) => {
          const t2 = e2.getTextCursorPosition();
          return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, {
            type: "paragraph",
            props: {}
          }), true);
        }
      }
    })
  ]
);
var Cn = () => ({
  type: "quote",
  propSchema: {
    backgroundColor: h3.backgroundColor,
    textColor: h3.textColor
  },
  content: "inline"
});
var kn = v2(
  Cn,
  {
    meta: {
      isolating: false
    },
    parse(e2) {
      if (e2.tagName === "BLOCKQUOTE") {
        const { backgroundColor: t2, textColor: n } = y(e2);
        return { backgroundColor: t2, textColor: n };
      }
    },
    render() {
      const e2 = document.createElement("blockquote");
      return {
        dom: e2,
        contentDOM: e2
      };
    },
    toExternalHTML(e2) {
      const t2 = document.createElement("blockquote");
      return A2(e2.props, t2), {
        dom: t2,
        contentDOM: t2
      };
    }
  },
  [
    a({
      key: "quote-block-shortcuts",
      keyboardShortcuts: {
        "Mod-Alt-q": ({ editor: e2 }) => {
          const t2 = e2.getTextCursorPosition();
          return e2.schema.blockSchema[t2.block.type].content !== "inline" ? false : (e2.updateBlock(t2.block, {
            type: "quote",
            props: {}
          }), true);
        }
      },
      inputRules: [
        {
          find: new RegExp("^>\\s$"),
          replace() {
            return {
              type: "quote",
              props: {}
            };
          }
        }
      ]
    })
  ]
);
var yn = 35;
var Ie = 120;
var Mo = 31;
var vn = Extension.create({
  name: "BlockNoteTableExtension",
  addProseMirrorPlugins: () => [
    columnResizing({
      cellMinWidth: yn,
      defaultCellMinWidth: Ie,
      // We set this to null as we implement our own node view in the table
      // block content. This node view is the same as what's used by default,
      // but is wrapped in a `blockContent` HTML element.
      View: null
    }),
    tableEditing()
  ],
  addKeyboardShortcuts() {
    return {
      // Makes enter create a new line within the cell.
      Enter: () => this.editor.state.selection.empty && this.editor.state.selection.$head.parent.type.name === "tableParagraph" ? (this.editor.commands.insertContent({ type: "hardBreak" }), true) : false,
      // Ensures that backspace won't delete the table if the text cursor is at
      // the start of a cell and the selection is empty.
      Backspace: () => {
        const e2 = this.editor.state.selection, t2 = e2.empty, n = e2.$head.parentOffset === 0, o2 = e2.$head.node().type.name === "tableParagraph";
        return t2 && n && o2;
      },
      // Enables navigating cells using the tab key.
      Tab: () => this.editor.commands.command(
        ({ state: e2, dispatch: t2, view: n }) => goToNextCell(1)(e2, t2, n)
      ),
      "Shift-Tab": () => this.editor.commands.command(
        ({ state: e2, dispatch: t2, view: n }) => goToNextCell(-1)(e2, t2, n)
      )
    };
  },
  extendNodeSchema(e2) {
    const t2 = {
      name: e2.name,
      options: e2.options,
      storage: e2.storage
    };
    return {
      tableRole: callOrReturn(
        getExtensionField(e2, "tableRole", t2)
      )
    };
  }
});
var En = {
  textColor: h3.textColor
};
var xn = Node3.create({
  name: "tableHeader",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  /**
   * We allow table headers and cells to have multiple tableContent nodes because
   * when merging cells, prosemirror-tables will concat the contents of the cells naively.
   * This would cause that content to overflow into other cells when prosemirror tries to enforce the cell structure.
   *
   * So, we manually fix this up when reading back in the `nodeToBlock` and only ever place a single tableContent back into the cell.
   */
  content: "tableContent+",
  addAttributes() {
    return {
      colspan: {
        default: 1
      },
      rowspan: {
        default: 1
      },
      colwidth: {
        default: null,
        parseHTML: (e2) => {
          const t2 = e2.getAttribute("colwidth");
          return t2 ? t2.split(",").map((o2) => parseInt(o2, 10)) : null;
        }
      }
    };
  },
  tableRole: "header_cell",
  isolating: true,
  parseHTML() {
    return [
      {
        tag: "th",
        // As `th` elements can contain multiple paragraphs, we need to merge their contents
        // into a single one so that ProseMirror can parse everything correctly.
        getContent: (e2, t2) => De(e2, t2)
      }
    ];
  },
  renderHTML({ HTMLAttributes: e2 }) {
    return [
      "th",
      mergeAttributes(this.options.HTMLAttributes, e2),
      0
    ];
  }
});
var wn = Node3.create({
  name: "tableCell",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  content: "tableContent+",
  addAttributes() {
    return {
      colspan: {
        default: 1
      },
      rowspan: {
        default: 1
      },
      colwidth: {
        default: null,
        parseHTML: (e2) => {
          const t2 = e2.getAttribute("colwidth");
          return t2 ? t2.split(",").map((o2) => parseInt(o2, 10)) : null;
        }
      }
    };
  },
  tableRole: "cell",
  isolating: true,
  parseHTML() {
    return [
      {
        tag: "td",
        // As `td` elements can contain multiple paragraphs, we need to merge their contents
        // into a single one so that ProseMirror can parse everything correctly.
        getContent: (e2, t2) => De(e2, t2)
      }
    ];
  },
  renderHTML({ HTMLAttributes: e2 }) {
    return [
      "td",
      mergeAttributes(this.options.HTMLAttributes, e2),
      0
    ];
  }
});
var Sn = Node3.create({
  name: "table",
  content: "tableRow+",
  group: "blockContent",
  tableRole: "table",
  marks: "deletion insertion modification",
  isolating: true,
  parseHTML() {
    return [
      {
        tag: "table"
      }
    ];
  },
  renderHTML({ node: e2, HTMLAttributes: t2 }) {
    var r4, a3, s2;
    const n = gt2(
      this.name,
      "table",
      {
        ...((r4 = this.options.domAttributes) == null ? void 0 : r4.blockContent) || {},
        ...t2
      },
      ((a3 = this.options.domAttributes) == null ? void 0 : a3.inlineContent) || {}
    ), o2 = document.createElement("colgroup");
    for (const i3 of e2.children[0].children)
      if (i3.attrs.colwidth)
        for (const l2 of i3.attrs.colwidth) {
          const u2 = document.createElement("col");
          l2 && (u2.style = `width: ${l2}px`), o2.appendChild(u2);
        }
      else
        o2.appendChild(document.createElement("col"));
    return (s2 = n.dom.firstChild) == null || s2.appendChild(o2), n;
  },
  // This node view is needed for the `columnResizing` plugin. By default, the
  // plugin adds its own node view, which overrides how the node is rendered vs
  // `renderHTML`. This means that the wrapping `blockContent` HTML element is
  // no longer rendered. The `columnResizing` plugin uses the `TableView` as its
  // default node view. `BlockNoteTableView` extends it by wrapping it in a
  // `blockContent` element, so the DOM structure is consistent with other block
  // types.
  addNodeView() {
    return ({ node: e2, HTMLAttributes: t2 }) => {
      var o2;
      class n extends TableView {
        constructor(a3, s2, i3) {
          super(a3, s2), this.node = a3, this.cellMinWidth = s2, this.blockContentHTMLAttributes = i3;
          const c3 = document.createElement("div");
          c3.className = D2(
            "bn-block-content",
            i3.class
          ), c3.setAttribute("data-content-type", "table");
          for (const [p4, m2] of Object.entries(
            i3
          ))
            p4 !== "class" && c3.setAttribute(p4, m2);
          const l2 = this.dom, u2 = document.createElement("div");
          u2.className = "tableWrapper-inner", u2.appendChild(l2.firstChild), l2.appendChild(u2), c3.appendChild(l2);
          const d = document.createElement("div");
          d.className = "table-widgets-container", d.style.position = "relative", l2.appendChild(d), this.dom = c3;
        }
        ignoreMutation(a3) {
          return !a3.target.closest(".tableWrapper-inner") || super.ignoreMutation(a3);
        }
      }
      return new n(e2, Ie, {
        ...((o2 = this.options.domAttributes) == null ? void 0 : o2.blockContent) || {},
        ...t2
      });
    };
  }
});
var Mn = Node3.create({
  name: "tableParagraph",
  group: "tableContent",
  content: "inline*",
  parseHTML() {
    return [
      {
        tag: "p",
        getAttrs: (e2) => {
          if (typeof e2 == "string" || !e2.textContent || !e2.closest("[data-content-type]"))
            return false;
          const t2 = e2.parentElement;
          return t2 === null ? false : t2.tagName === "TD" || t2.tagName === "TH" ? {} : false;
        },
        node: "tableParagraph"
      }
    ];
  },
  renderHTML({ HTMLAttributes: e2 }) {
    return ["p", e2, 0];
  }
});
var Ln = Node3.create({
  name: "tableRow",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  content: "(tableCell | tableHeader)+",
  tableRole: "row",
  marks: "deletion insertion modification",
  parseHTML() {
    return [{ tag: "tr" }];
  },
  renderHTML({ HTMLAttributes: e2 }) {
    return [
      "tr",
      mergeAttributes(this.options.HTMLAttributes, e2),
      0
    ];
  }
});
function De(e2, t2) {
  const o2 = DOMParser2.fromSchema(t2).parse(e2, {
    topNode: t2.nodes.blockGroup.create()
  }), r4 = [];
  return o2.content.descendants((a3) => {
    if (a3.isInline)
      return r4.push(a3), false;
  }), Fragment.fromArray(r4);
}
var Tn = () => yt2(
  { node: Sn, type: "table", content: "table" },
  En,
  [
    a({
      key: "table-extensions",
      tiptapExtensions: [
        vn,
        Mn,
        xn,
        wn,
        Ln
      ]
    }),
    // Extension for keyboard shortcut which deletes the table if it's empty
    // and all cells are selected. Uses a separate extension as it needs
    // priority over keyboard handlers in the `TableExtension`'s
    // `tableEditing` plugin.
    a({
      key: "table-keyboard-delete",
      keyboardShortcuts: {
        Backspace: ({ editor: e2 }) => {
          if (!(e2.prosemirrorState.selection instanceof CellSelection))
            return false;
          const t2 = e2.getTextCursorPosition().block, n = t2.content;
          let o2 = 0;
          for (const a3 of n.rows)
            for (const s2 of a3.cells) {
              if ("type" in s2 && s2.content.length > 0 || !("type" in s2) && s2.length > 0)
                return false;
              o2++;
            }
          let r4 = 0;
          return e2.prosemirrorState.selection.forEachCell(() => {
            r4++;
          }), r4 < o2 ? false : (e2.transact(() => {
            (e2.getPrevBlock(t2) || e2.getNextBlock(t2)) && e2.setTextCursorPosition(t2), e2.removeBlocks([t2]);
          }), true);
        }
      }
    })
  ]
);
var ge = (e2) => {
  const t2 = e2.src || void 0, n = e2.width || void 0;
  return { url: t2, previewWidth: n };
};
var Bn = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M2 3.9934C2 3.44476 2.45531 3 2.9918 3H21.0082C21.556 3 22 3.44495 22 3.9934V20.0066C22 20.5552 21.5447 21 21.0082 21H2.9918C2.44405 21 2 20.5551 2 20.0066V3.9934ZM8 5V19H16V5H8ZM4 5V7H6V5H4ZM18 5V7H20V5H18ZM4 9V11H6V9H4ZM18 9V11H20V9H18ZM4 13V15H6V13H4ZM18 13V15H20V13H18ZM4 17V19H6V17H4ZM18 17V19H20V17H18Z"></path></svg>';
var An = (e2) => ({
  type: "video",
  propSchema: {
    textAlignment: h3.textAlignment,
    backgroundColor: h3.backgroundColor,
    name: { default: "" },
    url: { default: "" },
    caption: { default: "" },
    showPreview: { default: true },
    previewWidth: { default: void 0, type: "number" }
  },
  content: "none"
});
var Pn = (e2) => (t2) => {
  if (t2.tagName === "VIDEO") {
    if (t2.closest("figure"))
      return;
    const { backgroundColor: n } = y(t2);
    return {
      ...ge(t2),
      backgroundColor: n
    };
  }
  if (t2.tagName === "FIGURE") {
    const n = $3(t2, "video");
    if (!n)
      return;
    const { targetElement: o2, caption: r4 } = n, { backgroundColor: a3 } = y(t2);
    return {
      ...ge(o2),
      backgroundColor: a3,
      caption: r4
    };
  }
};
var Nn = v2(
  An,
  (e2) => ({
    meta: {
      fileBlockAccept: ["video/*"]
    },
    parse: Pn(),
    render(t2, n) {
      const o2 = document.createElement("div");
      o2.innerHTML = e2.icon ?? Bn;
      const r4 = document.createElement("div");
      r4.className = "bn-visual-media-wrapper";
      const a3 = document.createElement("video");
      return a3.className = "bn-visual-media", n.resolveFileUrl ? n.resolveFileUrl(t2.props.url).then((s2) => {
        a3.src = s2;
      }) : a3.src = t2.props.url, a3.controls = true, a3.contentEditable = "false", a3.draggable = false, a3.width = t2.props.previewWidth, r4.appendChild(a3), Pe(
        t2,
        n,
        { dom: r4 },
        r4,
        o2.firstElementChild
      );
    },
    toExternalHTML(t2) {
      if (!t2.props.url) {
        const o2 = document.createElement("p");
        return o2.textContent = "Add video", {
          dom: o2
        };
      }
      let n;
      return t2.props.showPreview ? (n = document.createElement("video"), n.src = t2.props.url, t2.props.previewWidth && (n.width = t2.props.previewWidth)) : (n = document.createElement("a"), n.href = t2.props.url, n.textContent = t2.props.name || t2.props.url), t2.props.caption ? t2.props.showPreview ? J2(n, t2.props.caption) : U(n, t2.props.caption) : {
        dom: n
      };
    },
    runsBefore: ["file"]
  })
);
function b2(e2, t2, n) {
  if (!(t2 in e2.schema.blockSpecs))
    return false;
  if (!n)
    return true;
  for (const [o2, r4] of Object.entries(n)) {
    if (!(o2 in e2.schema.blockSpecs[t2].config.propSchema))
      return false;
    if (typeof r4 == "string") {
      if (e2.schema.blockSpecs[t2].config.propSchema[o2].default !== void 0 && typeof e2.schema.blockSpecs[t2].config.propSchema[o2].default !== r4 || e2.schema.blockSpecs[t2].config.propSchema[o2].type !== void 0 && e2.schema.blockSpecs[t2].config.propSchema[o2].type !== r4)
        return false;
    } else {
      if (e2.schema.blockSpecs[t2].config.propSchema[o2].default !== r4.default || e2.schema.blockSpecs[t2].config.propSchema[o2].default === void 0 && r4.default === void 0 && e2.schema.blockSpecs[t2].config.propSchema[o2].type !== r4.type || typeof e2.schema.blockSpecs[t2].config.propSchema[o2].values != typeof r4.values)
        return false;
      if (typeof e2.schema.blockSpecs[t2].config.propSchema[o2].values == "object" && typeof r4.values == "object") {
        for (const a3 of r4.values)
          if (!e2.schema.blockSpecs[t2].config.propSchema[o2].values.includes(a3))
            return false;
      }
    }
  }
  return true;
}
function Lo(e2, t2, n, o2) {
  return b2(t2, n, o2) && e2.type === n;
}
function To(e2) {
  return e2 instanceof CellSelection;
}
var R2 = /* @__PURE__ */ new Map();
function Hn(e2) {
  if (R2.has(e2))
    return R2.get(e2);
  const t2 = new Mapping();
  return e2._tiptapEditor.on("transaction", ({ transaction: n }) => {
    t2.appendMapping(n.mapping);
  }), e2._tiptapEditor.on("destroy", () => {
    R2.delete(e2);
  }), R2.set(e2, t2), t2;
}
function In(e2, t2, n = "left") {
  const o2 = ySyncPluginKey.getState(e2.prosemirrorState);
  if (!o2) {
    const a3 = Hn(e2), s2 = a3.maps.length;
    return () => a3.slice(s2).map(t2, n === "left" ? -1 : 1);
  }
  const r4 = absolutePositionToRelativePosition(
    // Track the position after the position if we are on the right side
    t2 + (n === "right" ? 1 : -1),
    o2.binding.type,
    o2.binding.mapping
  );
  return () => {
    const a3 = ySyncPluginKey.getState(
      e2.prosemirrorState
    ), s2 = relativePositionToAbsolutePosition(
      a3.doc,
      a3.binding.type,
      r4,
      a3.binding.mapping
    );
    if (s2 === null)
      throw new Error("Position not found, cannot track positions");
    return s2 + (n === "right" ? -1 : 1);
  };
}
var Dn = findParentNode((e2) => e2.type.name === "blockContainer");
var On = class {
  constructor(t2, n, o2) {
    M3(this, "state");
    M3(this, "emitUpdate");
    M3(this, "rootEl");
    M3(this, "pluginState");
    M3(this, "handleScroll", () => {
      var t3, n2;
      if ((t3 = this.state) != null && t3.show) {
        const o3 = (n2 = this.rootEl) == null ? void 0 : n2.querySelector(
          `[data-decoration-id="${this.pluginState.decorationId}"]`
        );
        if (!o3)
          return;
        this.state.referencePos = o3.getBoundingClientRect().toJSON(), this.emitUpdate(this.pluginState.triggerCharacter);
      }
    });
    M3(this, "closeMenu", () => {
      this.editor.transact((t3) => t3.setMeta(B2, null));
    });
    M3(this, "clearQuery", () => {
      this.pluginState !== void 0 && this.editor._tiptapEditor.chain().focus().deleteRange({
        from: this.pluginState.queryStartPos() - (this.pluginState.deleteTriggerCharacter ? this.pluginState.triggerCharacter.length : 0),
        to: this.editor.transact((t3) => t3.selection.from)
      }).run();
    });
    var r4;
    this.editor = t2, this.pluginState = void 0, this.emitUpdate = (a3) => {
      var s2;
      if (!this.state)
        throw new Error("Attempting to update uninitialized suggestions menu");
      n(a3, {
        ...this.state,
        ignoreQueryLength: (s2 = this.pluginState) == null ? void 0 : s2.ignoreQueryLength
      });
    }, this.rootEl = o2.root, (r4 = this.rootEl) == null || r4.addEventListener("scroll", this.handleScroll, true);
  }
  update(t2, n) {
    var l2;
    const o2 = B2.getState(n), r4 = B2.getState(
      t2.state
    ), a3 = o2 === void 0 && r4 !== void 0, s2 = o2 !== void 0 && r4 === void 0;
    if (!a3 && !(o2 !== void 0 && r4 !== void 0) && !s2)
      return;
    if (this.pluginState = s2 ? o2 : r4, s2 || !this.editor.isEditable) {
      this.state && (this.state.show = false), this.emitUpdate(this.pluginState.triggerCharacter);
      return;
    }
    const c3 = (l2 = this.rootEl) == null ? void 0 : l2.querySelector(
      `[data-decoration-id="${this.pluginState.decorationId}"]`
    );
    this.editor.isEditable && c3 && (this.state = {
      show: true,
      referencePos: c3.getBoundingClientRect().toJSON(),
      query: this.pluginState.query
    }, this.emitUpdate(this.pluginState.triggerCharacter));
  }
  destroy() {
    var t2;
    (t2 = this.rootEl) == null || t2.removeEventListener("scroll", this.handleScroll, true);
  }
};
var B2 = new PluginKey("SuggestionMenuPlugin");
var _n = a(({ editor: e2 }) => {
  const t2 = [];
  let n;
  const o2 = f(void 0);
  return {
    key: "suggestionMenu",
    store: o2,
    addTriggerCharacter: (r4) => {
      t2.push(r4);
    },
    removeTriggerCharacter: (r4) => {
      t2.splice(t2.indexOf(r4), 1);
    },
    closeMenu: () => {
      n == null || n.closeMenu();
    },
    clearQuery: () => {
      n == null || n.clearQuery();
    },
    shown: () => {
      var r4;
      return ((r4 = n == null ? void 0 : n.state) == null ? void 0 : r4.show) || false;
    },
    openSuggestionMenu: (r4, a3) => {
      e2.headless || (e2.focus(), e2.transact((s2) => {
        a3 != null && a3.deleteTriggerCharacter && s2.insertText(r4), s2.scrollIntoView().setMeta(B2, {
          triggerCharacter: r4,
          deleteTriggerCharacter: (a3 == null ? void 0 : a3.deleteTriggerCharacter) || false,
          ignoreQueryLength: (a3 == null ? void 0 : a3.ignoreQueryLength) || false
        });
      }));
    },
    // TODO this whole plugin needs to be refactored (but I've done the minimal)
    prosemirrorPlugins: [
      new Plugin({
        key: B2,
        view: (r4) => (n = new On(
          e2,
          (a3, s2) => {
            o2.setState({ ...s2, triggerCharacter: a3 });
          },
          r4
        ), n),
        state: {
          // Initialize the plugin's internal state.
          init() {
          },
          // Apply changes to the plugin state from an editor transaction.
          apply: (r4, a3, s2, i3) => {
            if (r4.selection.$from.parent.type.spec.code)
              return a3;
            const c3 = r4.getMeta(B2);
            if (typeof c3 == "object" && c3 !== null) {
              a3 && (n == null || n.closeMenu());
              const u2 = In(
                e2,
                i3.selection.from - // Need to account for the trigger char that was inserted, so we offset the position by the length of the trigger character.
                c3.triggerCharacter.length
              );
              return {
                triggerCharacter: c3.triggerCharacter,
                deleteTriggerCharacter: c3.deleteTriggerCharacter !== false,
                // When reading the queryStartPos, we offset the result by the length of the trigger character, to make it easy on the caller
                queryStartPos: () => u2() + c3.triggerCharacter.length,
                query: "",
                decorationId: `id_${Math.floor(Math.random() * 4294967295)}`,
                ignoreQueryLength: c3 == null ? void 0 : c3.ignoreQueryLength
              };
            }
            if (a3 === void 0)
              return a3;
            if (
              // Highlighting text should hide the menu.
              i3.selection.from !== i3.selection.to || // Transactions with plugin metadata should hide the menu.
              c3 === null || // Certain mouse events should hide the menu.
              // TODO: Change to global mousedown listener.
              r4.getMeta("focus") || r4.getMeta("blur") || r4.getMeta("pointer") || // Moving the caret before the character which triggered the menu should hide it.
              a3.triggerCharacter !== void 0 && i3.selection.from < a3.queryStartPos() || // Moving the caret to a new block should hide the menu.
              !i3.selection.$from.sameParent(
                i3.doc.resolve(a3.queryStartPos())
              )
            )
              return;
            const l2 = { ...a3 };
            return l2.query = i3.doc.textBetween(
              a3.queryStartPos(),
              i3.selection.from
            ), l2;
          }
        },
        props: {
          handleTextInput(r4, a3, s2, i3) {
            if (a3 === s2) {
              const c3 = r4.state.doc;
              for (const l2 of t2) {
                const u2 = l2.length > 1 ? c3.textBetween(a3 - l2.length, a3) + i3 : i3;
                if (l2 === u2)
                  return r4.dispatch(r4.state.tr.insertText(i3)), r4.dispatch(
                    r4.state.tr.setMeta(B2, {
                      triggerCharacter: u2
                    }).scrollIntoView()
                  ), true;
              }
            }
            return false;
          },
          // Setup decorator on the currently active suggestion.
          decorations(r4) {
            const a3 = this.getState(r4);
            if (a3 === void 0)
              return null;
            if (!a3.deleteTriggerCharacter) {
              const s2 = Dn(r4.selection);
              if (s2)
                return DecorationSet.create(r4.doc, [
                  Decoration.node(
                    s2.pos,
                    s2.pos + s2.node.nodeSize,
                    {
                      nodeName: "span",
                      class: "bn-suggestion-decorator",
                      "data-decoration-id": a3.decorationId
                    }
                  )
                ]);
            }
            return DecorationSet.create(r4.doc, [
              Decoration.inline(
                a3.queryStartPos() - a3.triggerCharacter.length,
                a3.queryStartPos(),
                {
                  nodeName: "span",
                  class: "bn-suggestion-decorator",
                  "data-decoration-id": a3.decorationId
                }
              )
            ]);
          }
        }
      })
    ]
  };
});
function Vn(e2) {
  let t2 = e2.getTextCursorPosition().block, n = e2.schema.blockSchema[t2.type].content;
  for (; n === "none"; ) {
    if (t2 = e2.getTextCursorPosition().nextBlock, t2 === void 0)
      return;
    n = e2.schema.blockSchema[t2.type].content, e2.setTextCursorPosition(t2, "end");
  }
}
function C(e2, t2) {
  const n = e2.getTextCursorPosition().block;
  if (n.content === void 0)
    throw new Error("Slash Menu open in a block that doesn't contain content.");
  let o2;
  return Array.isArray(n.content) && (n.content.length === 1 && B(n.content[0]) && n.content[0].type === "text" && n.content[0].text === "/" || n.content.length === 0) ? (o2 = e2.updateBlock(n, t2), e2.setTextCursorPosition(o2)) : (o2 = e2.insertBlocks([t2], n, "after")[0], e2.setTextCursorPosition(e2.getTextCursorPosition().nextBlock)), Vn(e2), o2;
}
function Bo(e2) {
  const t2 = [];
  return b2(e2, "heading", { level: "number" }) && (e2.schema.blockSchema.heading.propSchema.level.values || []).filter((n) => n <= 3).forEach((n) => {
    t2.push({
      onItemClick: () => {
        C(e2, {
          type: "heading",
          props: { level: n }
        });
      },
      badge: L2(`Mod-Alt-${n}`),
      key: n === 1 ? "heading" : `heading_${n}`,
      ...e2.dictionary.slash_menu[n === 1 ? "heading" : `heading_${n}`]
    });
  }), b2(e2, "quote") && t2.push({
    onItemClick: () => {
      C(e2, {
        type: "quote"
      });
    },
    key: "quote",
    ...e2.dictionary.slash_menu.quote
  }), b2(e2, "toggleListItem") && t2.push({
    onItemClick: () => {
      C(e2, {
        type: "toggleListItem"
      });
    },
    badge: L2("Mod-Shift-6"),
    key: "toggle_list",
    ...e2.dictionary.slash_menu.toggle_list
  }), b2(e2, "numberedListItem") && t2.push({
    onItemClick: () => {
      C(e2, {
        type: "numberedListItem"
      });
    },
    badge: L2("Mod-Shift-7"),
    key: "numbered_list",
    ...e2.dictionary.slash_menu.numbered_list
  }), b2(e2, "bulletListItem") && t2.push({
    onItemClick: () => {
      C(e2, {
        type: "bulletListItem"
      });
    },
    badge: L2("Mod-Shift-8"),
    key: "bullet_list",
    ...e2.dictionary.slash_menu.bullet_list
  }), b2(e2, "checkListItem") && t2.push({
    onItemClick: () => {
      C(e2, {
        type: "checkListItem"
      });
    },
    badge: L2("Mod-Shift-9"),
    key: "check_list",
    ...e2.dictionary.slash_menu.check_list
  }), b2(e2, "paragraph") && t2.push({
    onItemClick: () => {
      C(e2, {
        type: "paragraph"
      });
    },
    badge: L2("Mod-Alt-0"),
    key: "paragraph",
    ...e2.dictionary.slash_menu.paragraph
  }), b2(e2, "codeBlock") && t2.push({
    onItemClick: () => {
      C(e2, {
        type: "codeBlock"
      });
    },
    badge: L2("Mod-Alt-c"),
    key: "code_block",
    ...e2.dictionary.slash_menu.code_block
  }), b2(e2, "divider") && t2.push({
    onItemClick: () => {
      C(e2, { type: "divider" });
    },
    key: "divider",
    ...e2.dictionary.slash_menu.divider
  }), b2(e2, "table") && t2.push({
    onItemClick: () => {
      C(e2, {
        type: "table",
        content: {
          type: "tableContent",
          rows: [
            {
              cells: ["", "", ""]
            },
            {
              cells: ["", "", ""]
            }
          ]
        }
      });
    },
    badge: void 0,
    key: "table",
    ...e2.dictionary.slash_menu.table
  }), b2(e2, "image", { url: "string" }) && t2.push({
    onItemClick: () => {
      var o2;
      const n = C(e2, {
        type: "image"
      });
      (o2 = e2.getExtension(I2)) == null || o2.showMenu(n.id);
    },
    key: "image",
    ...e2.dictionary.slash_menu.image
  }), b2(e2, "video", { url: "string" }) && t2.push({
    onItemClick: () => {
      var o2;
      const n = C(e2, {
        type: "video"
      });
      (o2 = e2.getExtension(I2)) == null || o2.showMenu(n.id);
    },
    key: "video",
    ...e2.dictionary.slash_menu.video
  }), b2(e2, "audio", { url: "string" }) && t2.push({
    onItemClick: () => {
      var o2;
      const n = C(e2, {
        type: "audio"
      });
      (o2 = e2.getExtension(I2)) == null || o2.showMenu(n.id);
    },
    key: "audio",
    ...e2.dictionary.slash_menu.audio
  }), b2(e2, "file", { url: "string" }) && t2.push({
    onItemClick: () => {
      var o2;
      const n = C(e2, {
        type: "file"
      });
      (o2 = e2.getExtension(I2)) == null || o2.showMenu(n.id);
    },
    key: "file",
    ...e2.dictionary.slash_menu.file
  }), b2(e2, "heading", {
    level: "number",
    isToggleable: "boolean"
  }) && (e2.schema.blockSchema.heading.propSchema.level.values || []).filter((n) => n <= 3).forEach((n) => {
    t2.push({
      onItemClick: () => {
        C(e2, {
          type: "heading",
          props: { level: n, isToggleable: true }
        });
      },
      key: n === 1 ? "toggle_heading" : `toggle_heading_${n}`,
      ...e2.dictionary.slash_menu[n === 1 ? "toggle_heading" : `toggle_heading_${n}`]
    });
  }), b2(e2, "heading", { level: "number" }) && (e2.schema.blockSchema.heading.propSchema.level.values || []).filter((n) => n > 3).forEach((n) => {
    t2.push({
      onItemClick: () => {
        C(e2, {
          type: "heading",
          props: { level: n }
        });
      },
      badge: L2(`Mod-Alt-${n}`),
      key: `heading_${n}`,
      ...e2.dictionary.slash_menu[`heading_${n}`]
    });
  }), t2.push({
    onItemClick: () => {
      var n;
      (n = e2.getExtension(_n)) == null || n.openSuggestionMenu(":", {
        deleteTriggerCharacter: true,
        ignoreQueryLength: true
      });
    },
    key: "emoji",
    ...e2.dictionary.slash_menu.emoji
  }), t2;
}
function Ao(e2, t2) {
  return e2.filter(
    ({ title: n, aliases: o2 }) => n.toLowerCase().includes(t2.toLowerCase()) || o2 && o2.filter(
      (r4) => r4.toLowerCase().includes(t2.toLowerCase())
    ).length !== 0
  );
}
var Po = {
  audio: Ft(),
  bulletListItem: cn(),
  checkListItem: dn(),
  codeBlock: qt(),
  divider: Gt(),
  file: Xt(),
  heading: Yt(),
  image: an(),
  numberedListItem: fn(),
  paragraph: bn(),
  quote: kn(),
  table: Tn(),
  toggleListItem: mn(),
  video: Nn()
};
var Rn = Le(
  {
    type: "textColor",
    propSchema: "string"
  },
  {
    render: () => {
      const e2 = document.createElement("span");
      return {
        dom: e2,
        contentDOM: e2
      };
    },
    toExternalHTML: (e2) => {
      const t2 = document.createElement("span");
      return e2 !== h3.textColor.default && (t2.style.color = e2 in T2 ? T2[e2].text : e2), {
        dom: t2,
        contentDOM: t2
      };
    },
    parse: (e2) => {
      if (e2.tagName === "SPAN" && e2.style.color)
        return e2.style.color;
    }
  }
);
var Wn = Le(
  {
    type: "backgroundColor",
    propSchema: "string"
  },
  {
    render: () => {
      const e2 = document.createElement("span");
      return {
        dom: e2,
        contentDOM: e2
      };
    },
    toExternalHTML: (e2) => {
      const t2 = document.createElement("span");
      return e2 !== h3.backgroundColor.default && (t2.style.backgroundColor = e2 in T2 ? T2[e2].background : e2), {
        dom: t2,
        contentDOM: t2
      };
    },
    parse: (e2) => {
      if (e2.tagName === "SPAN" && e2.style.backgroundColor)
        return e2.style.backgroundColor;
    }
  }
);
var Fn = {
  bold: H2(index_default, "boolean"),
  italic: H2(index_default3, "boolean"),
  underline: H2(index_default5, "boolean"),
  strike: H2(index_default4, "boolean"),
  code: H2(index_default2, "boolean"),
  textColor: Rn,
  backgroundColor: Wn
};
var No = Mt2(Fn);
var $n = {
  text: { config: "text", implementation: {} },
  link: { config: "link", implementation: {} }
};
var Ho = wt2(
  $n
);

// ../../node_modules/.pnpm/prosemirror-dropcursor@1.8.2/node_modules/prosemirror-dropcursor/dist/index.js
function dropCursor(options2 = {}) {
  return new Plugin({
    view(editorView) {
      return new DropCursorView(editorView, options2);
    }
  });
}
var DropCursorView = class {
  constructor(editorView, options2) {
    var _a2;
    this.editorView = editorView;
    this.cursorPos = null;
    this.element = null;
    this.timeout = -1;
    this.width = (_a2 = options2.width) !== null && _a2 !== void 0 ? _a2 : 1;
    this.color = options2.color === false ? void 0 : options2.color || "black";
    this.class = options2.class;
    this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((name) => {
      let handler = (e2) => {
        this[name](e2);
      };
      editorView.dom.addEventListener(name, handler);
      return { name, handler };
    });
  }
  destroy() {
    this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler));
  }
  update(editorView, prevState) {
    if (this.cursorPos != null && prevState.doc != editorView.state.doc) {
      if (this.cursorPos > editorView.state.doc.content.size)
        this.setCursor(null);
      else
        this.updateOverlay();
    }
  }
  setCursor(pos) {
    if (pos == this.cursorPos)
      return;
    this.cursorPos = pos;
    if (pos == null) {
      this.element.parentNode.removeChild(this.element);
      this.element = null;
    } else {
      this.updateOverlay();
    }
  }
  updateOverlay() {
    let $pos = this.editorView.state.doc.resolve(this.cursorPos);
    let isBlock = !$pos.parent.inlineContent, rect;
    let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect();
    let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight;
    if (isBlock) {
      let before = $pos.nodeBefore, after = $pos.nodeAfter;
      if (before || after) {
        let node2 = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));
        if (node2) {
          let nodeRect = node2.getBoundingClientRect();
          let top = before ? nodeRect.bottom : nodeRect.top;
          if (before && after)
            top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;
          let halfWidth = this.width / 2 * scaleY;
          rect = { left: nodeRect.left, right: nodeRect.right, top: top - halfWidth, bottom: top + halfWidth };
        }
      }
    }
    if (!rect) {
      let coords = this.editorView.coordsAtPos(this.cursorPos);
      let halfWidth = this.width / 2 * scaleX;
      rect = { left: coords.left - halfWidth, right: coords.left + halfWidth, top: coords.top, bottom: coords.bottom };
    }
    let parent = this.editorView.dom.offsetParent;
    if (!this.element) {
      this.element = parent.appendChild(document.createElement("div"));
      if (this.class)
        this.element.className = this.class;
      this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;";
      if (this.color) {
        this.element.style.backgroundColor = this.color;
      }
    }
    this.element.classList.toggle("prosemirror-dropcursor-block", isBlock);
    this.element.classList.toggle("prosemirror-dropcursor-inline", !isBlock);
    let parentLeft, parentTop;
    if (!parent || parent == document.body && getComputedStyle(parent).position == "static") {
      parentLeft = -pageXOffset;
      parentTop = -pageYOffset;
    } else {
      let rect2 = parent.getBoundingClientRect();
      let parentScaleX = rect2.width / parent.offsetWidth, parentScaleY = rect2.height / parent.offsetHeight;
      parentLeft = rect2.left - parent.scrollLeft * parentScaleX;
      parentTop = rect2.top - parent.scrollTop * parentScaleY;
    }
    this.element.style.left = (rect.left - parentLeft) / scaleX + "px";
    this.element.style.top = (rect.top - parentTop) / scaleY + "px";
    this.element.style.width = (rect.right - rect.left) / scaleX + "px";
    this.element.style.height = (rect.bottom - rect.top) / scaleY + "px";
  }
  scheduleRemoval(timeout2) {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => this.setCursor(null), timeout2);
  }
  dragover(event) {
    if (!this.editorView.editable)
      return;
    let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY });
    let node2 = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);
    let disableDropCursor = node2 && node2.type.spec.disableDropCursor;
    let disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor;
    if (pos && !disabled) {
      let target = pos.pos;
      if (this.editorView.dragging && this.editorView.dragging.slice) {
        let point5 = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice);
        if (point5 != null)
          target = point5;
      }
      this.setCursor(target);
      this.scheduleRemoval(5e3);
    }
  }
  dragend() {
    this.scheduleRemoval(20);
  }
  drop() {
    this.scheduleRemoval(20);
  }
  dragleave(event) {
    if (!this.editorView.dom.contains(event.relatedTarget))
      this.setCursor(null);
  }
};

// ../../node_modules/.pnpm/rope-sequence@1.3.4/node_modules/rope-sequence/dist/index.js
var GOOD_LEAF_SIZE = 200;
var RopeSequence = function RopeSequence2() {
};
RopeSequence.prototype.append = function append2(other) {
  if (!other.length) {
    return this;
  }
  other = RopeSequence.from(other);
  return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other);
};
RopeSequence.prototype.prepend = function prepend(other) {
  if (!other.length) {
    return this;
  }
  return RopeSequence.from(other).append(this);
};
RopeSequence.prototype.appendInner = function appendInner(other) {
  return new Append(this, other);
};
RopeSequence.prototype.slice = function slice(from4, to2) {
  if (from4 === void 0) from4 = 0;
  if (to2 === void 0) to2 = this.length;
  if (from4 >= to2) {
    return RopeSequence.empty;
  }
  return this.sliceInner(Math.max(0, from4), Math.min(this.length, to2));
};
RopeSequence.prototype.get = function get(i3) {
  if (i3 < 0 || i3 >= this.length) {
    return void 0;
  }
  return this.getInner(i3);
};
RopeSequence.prototype.forEach = function forEach4(f6, from4, to2) {
  if (from4 === void 0) from4 = 0;
  if (to2 === void 0) to2 = this.length;
  if (from4 <= to2) {
    this.forEachInner(f6, from4, to2, 0);
  } else {
    this.forEachInvertedInner(f6, from4, to2, 0);
  }
};
RopeSequence.prototype.map = function map3(f6, from4, to2) {
  if (from4 === void 0) from4 = 0;
  if (to2 === void 0) to2 = this.length;
  var result = [];
  this.forEach(function(elt, i3) {
    return result.push(f6(elt, i3));
  }, from4, to2);
  return result;
};
RopeSequence.from = function from3(values2) {
  if (values2 instanceof RopeSequence) {
    return values2;
  }
  return values2 && values2.length ? new Leaf(values2) : RopeSequence.empty;
};
var Leaf = (function(RopeSequence3) {
  function Leaf2(values2) {
    RopeSequence3.call(this);
    this.values = values2;
  }
  if (RopeSequence3) Leaf2.__proto__ = RopeSequence3;
  Leaf2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Leaf2.prototype.constructor = Leaf2;
  var prototypeAccessors = { length: { configurable: true }, depth: { configurable: true } };
  Leaf2.prototype.flatten = function flatten2() {
    return this.values;
  };
  Leaf2.prototype.sliceInner = function sliceInner(from4, to2) {
    if (from4 == 0 && to2 == this.length) {
      return this;
    }
    return new Leaf2(this.values.slice(from4, to2));
  };
  Leaf2.prototype.getInner = function getInner(i3) {
    return this.values[i3];
  };
  Leaf2.prototype.forEachInner = function forEachInner(f6, from4, to2, start) {
    for (var i3 = from4; i3 < to2; i3++) {
      if (f6(this.values[i3], start + i3) === false) {
        return false;
      }
    }
  };
  Leaf2.prototype.forEachInvertedInner = function forEachInvertedInner(f6, from4, to2, start) {
    for (var i3 = from4 - 1; i3 >= to2; i3--) {
      if (f6(this.values[i3], start + i3) === false) {
        return false;
      }
    }
  };
  Leaf2.prototype.leafAppend = function leafAppend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(this.values.concat(other.flatten()));
    }
  };
  Leaf2.prototype.leafPrepend = function leafPrepend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(other.flatten().concat(this.values));
    }
  };
  prototypeAccessors.length.get = function() {
    return this.values.length;
  };
  prototypeAccessors.depth.get = function() {
    return 0;
  };
  Object.defineProperties(Leaf2.prototype, prototypeAccessors);
  return Leaf2;
})(RopeSequence);
RopeSequence.empty = new Leaf([]);
var Append = (function(RopeSequence3) {
  function Append2(left, right) {
    RopeSequence3.call(this);
    this.left = left;
    this.right = right;
    this.length = left.length + right.length;
    this.depth = Math.max(left.depth, right.depth) + 1;
  }
  if (RopeSequence3) Append2.__proto__ = RopeSequence3;
  Append2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Append2.prototype.constructor = Append2;
  Append2.prototype.flatten = function flatten2() {
    return this.left.flatten().concat(this.right.flatten());
  };
  Append2.prototype.getInner = function getInner(i3) {
    return i3 < this.left.length ? this.left.get(i3) : this.right.get(i3 - this.left.length);
  };
  Append2.prototype.forEachInner = function forEachInner(f6, from4, to2, start) {
    var leftLen = this.left.length;
    if (from4 < leftLen && this.left.forEachInner(f6, from4, Math.min(to2, leftLen), start) === false) {
      return false;
    }
    if (to2 > leftLen && this.right.forEachInner(f6, Math.max(from4 - leftLen, 0), Math.min(this.length, to2) - leftLen, start + leftLen) === false) {
      return false;
    }
  };
  Append2.prototype.forEachInvertedInner = function forEachInvertedInner(f6, from4, to2, start) {
    var leftLen = this.left.length;
    if (from4 > leftLen && this.right.forEachInvertedInner(f6, from4 - leftLen, Math.max(to2, leftLen) - leftLen, start + leftLen) === false) {
      return false;
    }
    if (to2 < leftLen && this.left.forEachInvertedInner(f6, Math.min(from4, leftLen), to2, start) === false) {
      return false;
    }
  };
  Append2.prototype.sliceInner = function sliceInner(from4, to2) {
    if (from4 == 0 && to2 == this.length) {
      return this;
    }
    var leftLen = this.left.length;
    if (to2 <= leftLen) {
      return this.left.slice(from4, to2);
    }
    if (from4 >= leftLen) {
      return this.right.slice(from4 - leftLen, to2 - leftLen);
    }
    return this.left.slice(from4, leftLen).append(this.right.slice(0, to2 - leftLen));
  };
  Append2.prototype.leafAppend = function leafAppend(other) {
    var inner = this.right.leafAppend(other);
    if (inner) {
      return new Append2(this.left, inner);
    }
  };
  Append2.prototype.leafPrepend = function leafPrepend(other) {
    var inner = this.left.leafPrepend(other);
    if (inner) {
      return new Append2(inner, this.right);
    }
  };
  Append2.prototype.appendInner = function appendInner2(other) {
    if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) {
      return new Append2(this.left, new Append2(this.right, other));
    }
    return new Append2(this, other);
  };
  return Append2;
})(RopeSequence);
var dist_default2 = RopeSequence;

// ../../node_modules/.pnpm/prosemirror-history@1.5.0/node_modules/prosemirror-history/dist/index.js
var max_empty_items = 500;
var Branch = class _Branch {
  constructor(items, eventCount) {
    this.items = items;
    this.eventCount = eventCount;
  }
  // Pop the latest event off the branch's history and apply it
  // to a document transform.
  popEvent(state, preserveItems) {
    if (this.eventCount == 0)
      return null;
    let end = this.items.length;
    for (; ; end--) {
      let next2 = this.items.get(end - 1);
      if (next2.selection) {
        --end;
        break;
      }
    }
    let remap, mapFrom;
    if (preserveItems) {
      remap = this.remapping(end, this.items.length);
      mapFrom = remap.maps.length;
    }
    let transform2 = state.tr;
    let selection, remaining;
    let addAfter = [], addBefore = [];
    this.items.forEach((item, i3) => {
      if (!item.step) {
        if (!remap) {
          remap = this.remapping(end, i3 + 1);
          mapFrom = remap.maps.length;
        }
        mapFrom--;
        addBefore.push(item);
        return;
      }
      if (remap) {
        addBefore.push(new Item2(item.map));
        let step = item.step.map(remap.slice(mapFrom)), map7;
        if (step && transform2.maybeStep(step).doc) {
          map7 = transform2.mapping.maps[transform2.mapping.maps.length - 1];
          addAfter.push(new Item2(map7, void 0, void 0, addAfter.length + addBefore.length));
        }
        mapFrom--;
        if (map7)
          remap.appendMap(map7, mapFrom);
      } else {
        transform2.maybeStep(item.step);
      }
      if (item.selection) {
        selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;
        remaining = new _Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);
        return false;
      }
    }, this.items.length, 0);
    return { remaining, transform: transform2, selection };
  }
  // Create a new branch with the given transform added.
  addTransform(transform2, selection, histOptions, preserveItems) {
    let newItems = [], eventCount = this.eventCount;
    let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;
    for (let i3 = 0; i3 < transform2.steps.length; i3++) {
      let step = transform2.steps[i3].invert(transform2.docs[i3]);
      let item = new Item2(transform2.mapping.maps[i3], step, selection), merged;
      if (merged = lastItem && lastItem.merge(item)) {
        item = merged;
        if (i3)
          newItems.pop();
        else
          oldItems = oldItems.slice(0, oldItems.length - 1);
      }
      newItems.push(item);
      if (selection) {
        eventCount++;
        selection = void 0;
      }
      if (!preserveItems)
        lastItem = item;
    }
    let overflow = eventCount - histOptions.depth;
    if (overflow > DEPTH_OVERFLOW) {
      oldItems = cutOffEvents(oldItems, overflow);
      eventCount -= overflow;
    }
    return new _Branch(oldItems.append(newItems), eventCount);
  }
  remapping(from4, to2) {
    let maps = new Mapping();
    this.items.forEach((item, i3) => {
      let mirrorPos = item.mirrorOffset != null && i3 - item.mirrorOffset >= from4 ? maps.maps.length - item.mirrorOffset : void 0;
      maps.appendMap(item.map, mirrorPos);
    }, from4, to2);
    return maps;
  }
  addMaps(array) {
    if (this.eventCount == 0)
      return this;
    return new _Branch(this.items.append(array.map((map7) => new Item2(map7))), this.eventCount);
  }
  // When the collab module receives remote changes, the history has
  // to know about those, so that it can adjust the steps that were
  // rebased on top of the remote changes, and include the position
  // maps for the remote changes in its array of items.
  rebased(rebasedTransform, rebasedCount) {
    if (!this.eventCount)
      return this;
    let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount);
    let mapping = rebasedTransform.mapping;
    let newUntil = rebasedTransform.steps.length;
    let eventCount = this.eventCount;
    this.items.forEach((item) => {
      if (item.selection)
        eventCount--;
    }, start);
    let iRebased = rebasedCount;
    this.items.forEach((item) => {
      let pos = mapping.getMirror(--iRebased);
      if (pos == null)
        return;
      newUntil = Math.min(newUntil, pos);
      let map7 = mapping.maps[pos];
      if (item.step) {
        let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);
        let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));
        if (selection)
          eventCount++;
        rebasedItems.push(new Item2(map7, step, selection));
      } else {
        rebasedItems.push(new Item2(map7));
      }
    }, start);
    let newMaps = [];
    for (let i3 = rebasedCount; i3 < newUntil; i3++)
      newMaps.push(new Item2(mapping.maps[i3]));
    let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);
    let branch = new _Branch(items, eventCount);
    if (branch.emptyItemCount() > max_empty_items)
      branch = branch.compress(this.items.length - rebasedItems.length);
    return branch;
  }
  emptyItemCount() {
    let count2 = 0;
    this.items.forEach((item) => {
      if (!item.step)
        count2++;
    });
    return count2;
  }
  // Compressing a branch means rewriting it to push the air (map-only
  // items) out. During collaboration, these naturally accumulate
  // because each remote change adds one. The `upto` argument is used
  // to ensure that only the items below a given level are compressed,
  // because `rebased` relies on a clean, untouched set of items in
  // order to associate old items with rebased steps.
  compress(upto = this.items.length) {
    let remap = this.remapping(0, upto), mapFrom = remap.maps.length;
    let items = [], events = 0;
    this.items.forEach((item, i3) => {
      if (i3 >= upto) {
        items.push(item);
        if (item.selection)
          events++;
      } else if (item.step) {
        let step = item.step.map(remap.slice(mapFrom)), map7 = step && step.getMap();
        mapFrom--;
        if (map7)
          remap.appendMap(map7, mapFrom);
        if (step) {
          let selection = item.selection && item.selection.map(remap.slice(mapFrom));
          if (selection)
            events++;
          let newItem = new Item2(map7.invert(), step, selection), merged, last2 = items.length - 1;
          if (merged = items.length && items[last2].merge(newItem))
            items[last2] = merged;
          else
            items.push(newItem);
        }
      } else if (item.map) {
        mapFrom--;
      }
    }, this.items.length, 0);
    return new _Branch(dist_default2.from(items.reverse()), events);
  }
};
Branch.empty = new Branch(dist_default2.empty, 0);
function cutOffEvents(items, n) {
  let cutPoint;
  items.forEach((item, i3) => {
    if (item.selection && n-- == 0) {
      cutPoint = i3;
      return false;
    }
  });
  return items.slice(cutPoint);
}
var Item2 = class _Item {
  constructor(map7, step, selection, mirrorOffset) {
    this.map = map7;
    this.step = step;
    this.selection = selection;
    this.mirrorOffset = mirrorOffset;
  }
  merge(other) {
    if (this.step && other.step && !other.selection) {
      let step = other.step.merge(this.step);
      if (step)
        return new _Item(step.getMap().invert(), step, this.selection);
    }
  }
};
var HistoryState = class {
  constructor(done, undone, prevRanges, prevTime, prevComposition) {
    this.done = done;
    this.undone = undone;
    this.prevRanges = prevRanges;
    this.prevTime = prevTime;
    this.prevComposition = prevComposition;
  }
};
var DEPTH_OVERFLOW = 20;
function applyTransaction(history2, state, tr4, options2) {
  let historyTr = tr4.getMeta(historyKey), rebased;
  if (historyTr)
    return historyTr.historyState;
  if (tr4.getMeta(closeHistoryKey))
    history2 = new HistoryState(history2.done, history2.undone, null, 0, -1);
  let appended = tr4.getMeta("appendedTransaction");
  if (tr4.steps.length == 0) {
    return history2;
  } else if (appended && appended.getMeta(historyKey)) {
    if (appended.getMeta(historyKey).redo)
      return new HistoryState(history2.done.addTransform(tr4, void 0, options2, mustPreserveItems(state)), history2.undone, rangesFor(tr4.mapping.maps), history2.prevTime, history2.prevComposition);
    else
      return new HistoryState(history2.done, history2.undone.addTransform(tr4, void 0, options2, mustPreserveItems(state)), null, history2.prevTime, history2.prevComposition);
  } else if (tr4.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) {
    let composition = tr4.getMeta("composition");
    let newGroup = history2.prevTime == 0 || !appended && history2.prevComposition != composition && (history2.prevTime < (tr4.time || 0) - options2.newGroupDelay || !isAdjacentTo(tr4, history2.prevRanges));
    let prevRanges = appended ? mapRanges(history2.prevRanges, tr4.mapping) : rangesFor(tr4.mapping.maps);
    return new HistoryState(history2.done.addTransform(tr4, newGroup ? state.selection.getBookmark() : void 0, options2, mustPreserveItems(state)), Branch.empty, prevRanges, tr4.time, composition == null ? history2.prevComposition : composition);
  } else if (rebased = tr4.getMeta("rebased")) {
    return new HistoryState(history2.done.rebased(tr4, rebased), history2.undone.rebased(tr4, rebased), mapRanges(history2.prevRanges, tr4.mapping), history2.prevTime, history2.prevComposition);
  } else {
    return new HistoryState(history2.done.addMaps(tr4.mapping.maps), history2.undone.addMaps(tr4.mapping.maps), mapRanges(history2.prevRanges, tr4.mapping), history2.prevTime, history2.prevComposition);
  }
}
function isAdjacentTo(transform2, prevRanges) {
  if (!prevRanges)
    return false;
  if (!transform2.docChanged)
    return true;
  let adjacent = false;
  transform2.mapping.maps[0].forEach((start, end) => {
    for (let i3 = 0; i3 < prevRanges.length; i3 += 2)
      if (start <= prevRanges[i3 + 1] && end >= prevRanges[i3])
        adjacent = true;
  });
  return adjacent;
}
function rangesFor(maps) {
  let result = [];
  for (let i3 = maps.length - 1; i3 >= 0 && result.length == 0; i3--)
    maps[i3].forEach((_from, _to, from4, to2) => result.push(from4, to2));
  return result;
}
function mapRanges(ranges, mapping) {
  if (!ranges)
    return null;
  let result = [];
  for (let i3 = 0; i3 < ranges.length; i3 += 2) {
    let from4 = mapping.map(ranges[i3], 1), to2 = mapping.map(ranges[i3 + 1], -1);
    if (from4 <= to2)
      result.push(from4, to2);
  }
  return result;
}
function histTransaction(history2, state, redo3) {
  let preserveItems = mustPreserveItems(state);
  let histOptions = historyKey.get(state).spec.config;
  let pop = (redo3 ? history2.undone : history2.done).popEvent(state, preserveItems);
  if (!pop)
    return null;
  let selection = pop.selection.resolve(pop.transform.doc);
  let added = (redo3 ? history2.done : history2.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);
  let newHist = new HistoryState(redo3 ? added : pop.remaining, redo3 ? pop.remaining : added, null, 0, -1);
  return pop.transform.setSelection(selection).setMeta(historyKey, { redo: redo3, historyState: newHist });
}
var cachedPreserveItems = false;
var cachedPreserveItemsPlugins = null;
function mustPreserveItems(state) {
  let plugins = state.plugins;
  if (cachedPreserveItemsPlugins != plugins) {
    cachedPreserveItems = false;
    cachedPreserveItemsPlugins = plugins;
    for (let i3 = 0; i3 < plugins.length; i3++)
      if (plugins[i3].spec.historyPreserveItems) {
        cachedPreserveItems = true;
        break;
      }
  }
  return cachedPreserveItems;
}
function closeHistory(tr4) {
  return tr4.setMeta(closeHistoryKey, true);
}
var historyKey = new PluginKey("history");
var closeHistoryKey = new PluginKey("closeHistory");
function history(config = {}) {
  config = {
    depth: config.depth || 100,
    newGroupDelay: config.newGroupDelay || 500
  };
  return new Plugin({
    key: historyKey,
    state: {
      init() {
        return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);
      },
      apply(tr4, hist, state) {
        return applyTransaction(hist, state, tr4, config);
      }
    },
    config,
    props: {
      handleDOMEvents: {
        beforeinput(view, e2) {
          let inputType = e2.inputType;
          let command2 = inputType == "historyUndo" ? undo2 : inputType == "historyRedo" ? redo2 : null;
          if (!command2 || !view.editable)
            return false;
          e2.preventDefault();
          return command2(view.state, view.dispatch);
        }
      }
    }
  });
}
function buildCommand(redo3, scroll) {
  return (state, dispatch) => {
    let hist = historyKey.getState(state);
    if (!hist || (redo3 ? hist.undone : hist.done).eventCount == 0)
      return false;
    if (dispatch) {
      let tr4 = histTransaction(hist, state, redo3);
      if (tr4)
        dispatch(scroll ? tr4.scrollIntoView() : tr4);
    }
    return true;
  };
}
var undo2 = buildCommand(false, true);
var redo2 = buildCommand(true, true);
var undoNoScroll = buildCommand(false, false);
var redoNoScroll = buildCommand(true, false);

// ../../node_modules/.pnpm/devlop@1.1.0/node_modules/devlop/lib/development.js
var AssertionError = class extends Error {
  /**
   * Create an assertion error.
   *
   * @param {string} message
   *   Message explaining error.
   * @param {unknown} actual
   *   Value.
   * @param {unknown} expected
   *   Baseline.
   * @param {string} operator
   *   Name of equality operation.
   * @param {boolean} generated
   *   Whether `message` is a custom message or not
   * @returns
   *   Instance.
   */
  // eslint-disable-next-line max-params
  constructor(message, actual, expected, operator, generated) {
    super(message);
    __publicField(
      this,
      "name",
      /** @type {const} */
      "Assertion"
    );
    __publicField(
      this,
      "code",
      /** @type {const} */
      "ERR_ASSERTION"
    );
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor);
    }
    this.actual = actual;
    this.expected = expected;
    this.generated = generated;
    this.operator = operator;
  }
};
function ok(value, message) {
  assert2(
    Boolean(value),
    false,
    true,
    "ok",
    "Expected value to be truthy",
    message
  );
}
function assert2(bool2, actual, expected, operator, defaultMessage, userMessage) {
  if (!bool2) {
    throw userMessage instanceof Error ? userMessage : new AssertionError(
      userMessage || defaultMessage,
      actual,
      expected,
      operator,
      !userMessage
    );
  }
}

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/schema.js
var Schema3 = class {
  /**
   * @param {SchemaType['property']} property
   *   Property.
   * @param {SchemaType['normal']} normal
   *   Normal.
   * @param {Space | undefined} [space]
   *   Space.
   * @returns
   *   Schema.
   */
  constructor(property, normal, space2) {
    this.normal = normal;
    this.property = property;
    if (space2) {
      this.space = space2;
    }
  }
};
Schema3.prototype.normal = {};
Schema3.prototype.property = {};
Schema3.prototype.space = void 0;

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/merge.js
function merge(definitions, space2) {
  const property = {};
  const normal = {};
  for (const definition3 of definitions) {
    Object.assign(property, definition3.property);
    Object.assign(normal, definition3.normal);
  }
  return new Schema3(property, normal, space2);
}

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/normalize.js
function normalize2(value) {
  return value.toLowerCase();
}

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/info.js
var Info = class {
  /**
   * @param {string} property
   *   Property.
   * @param {string} attribute
   *   Attribute.
   * @returns
   *   Info.
   */
  constructor(property, attribute) {
    this.attribute = attribute;
    this.property = property;
  }
};
Info.prototype.attribute = "";
Info.prototype.booleanish = false;
Info.prototype.boolean = false;
Info.prototype.commaOrSpaceSeparated = false;
Info.prototype.commaSeparated = false;
Info.prototype.defined = false;
Info.prototype.mustUseProperty = false;
Info.prototype.number = false;
Info.prototype.overloadedBoolean = false;
Info.prototype.property = "";
Info.prototype.spaceSeparated = false;
Info.prototype.space = void 0;

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/types.js
var types_exports = {};
__export(types_exports, {
  boolean: () => boolean,
  booleanish: () => booleanish,
  commaOrSpaceSeparated: () => commaOrSpaceSeparated,
  commaSeparated: () => commaSeparated,
  number: () => number,
  overloadedBoolean: () => overloadedBoolean,
  spaceSeparated: () => spaceSeparated
});
var powers = 0;
var boolean = increment();
var booleanish = increment();
var overloadedBoolean = increment();
var number = increment();
var spaceSeparated = increment();
var commaSeparated = increment();
var commaOrSpaceSeparated = increment();
function increment() {
  return 2 ** ++powers;
}

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/defined-info.js
var checks = (
  /** @type {ReadonlyArray<keyof typeof types>} */
  Object.keys(types_exports)
);
var DefinedInfo = class extends Info {
  /**
   * @constructor
   * @param {string} property
   *   Property.
   * @param {string} attribute
   *   Attribute.
   * @param {number | null | undefined} [mask]
   *   Mask.
   * @param {Space | undefined} [space]
   *   Space.
   * @returns
   *   Info.
   */
  constructor(property, attribute, mask, space2) {
    let index4 = -1;
    super(property, attribute);
    mark(this, "space", space2);
    if (typeof mask === "number") {
      while (++index4 < checks.length) {
        const check = checks[index4];
        mark(this, checks[index4], (mask & types_exports[check]) === types_exports[check]);
      }
    }
  }
};
DefinedInfo.prototype.defined = true;
function mark(values2, key2, value) {
  if (value) {
    values2[key2] = value;
  }
}

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/create.js
function create7(definition3) {
  const properties = {};
  const normals = {};
  for (const [property, value] of Object.entries(definition3.properties)) {
    const info = new DefinedInfo(
      property,
      definition3.transform(definition3.attributes || {}, property),
      value,
      definition3.space
    );
    if (definition3.mustUseProperty && definition3.mustUseProperty.includes(property)) {
      info.mustUseProperty = true;
    }
    properties[property] = info;
    normals[normalize2(property)] = property;
    normals[normalize2(info.attribute)] = property;
  }
  return new Schema3(properties, normals, definition3.space);
}

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/aria.js
var aria = create7({
  properties: {
    ariaActiveDescendant: null,
    ariaAtomic: booleanish,
    ariaAutoComplete: null,
    ariaBusy: booleanish,
    ariaChecked: booleanish,
    ariaColCount: number,
    ariaColIndex: number,
    ariaColSpan: number,
    ariaControls: spaceSeparated,
    ariaCurrent: null,
    ariaDescribedBy: spaceSeparated,
    ariaDetails: null,
    ariaDisabled: booleanish,
    ariaDropEffect: spaceSeparated,
    ariaErrorMessage: null,
    ariaExpanded: booleanish,
    ariaFlowTo: spaceSeparated,
    ariaGrabbed: booleanish,
    ariaHasPopup: null,
    ariaHidden: booleanish,
    ariaInvalid: null,
    ariaKeyShortcuts: null,
    ariaLabel: null,
    ariaLabelledBy: spaceSeparated,
    ariaLevel: number,
    ariaLive: null,
    ariaModal: booleanish,
    ariaMultiLine: booleanish,
    ariaMultiSelectable: booleanish,
    ariaOrientation: null,
    ariaOwns: spaceSeparated,
    ariaPlaceholder: null,
    ariaPosInSet: number,
    ariaPressed: booleanish,
    ariaReadOnly: booleanish,
    ariaRelevant: null,
    ariaRequired: booleanish,
    ariaRoleDescription: spaceSeparated,
    ariaRowCount: number,
    ariaRowIndex: number,
    ariaRowSpan: number,
    ariaSelected: booleanish,
    ariaSetSize: number,
    ariaSort: null,
    ariaValueMax: number,
    ariaValueMin: number,
    ariaValueNow: number,
    ariaValueText: null,
    role: null
  },
  transform(_2, property) {
    return property === "role" ? property : "aria-" + property.slice(4).toLowerCase();
  }
});

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/case-sensitive-transform.js
function caseSensitiveTransform(attributes, attribute) {
  return attribute in attributes ? attributes[attribute] : attribute;
}

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/util/case-insensitive-transform.js
function caseInsensitiveTransform(attributes, property) {
  return caseSensitiveTransform(attributes, property.toLowerCase());
}

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/html.js
var html = create7({
  attributes: {
    acceptcharset: "accept-charset",
    classname: "class",
    htmlfor: "for",
    httpequiv: "http-equiv"
  },
  mustUseProperty: ["checked", "multiple", "muted", "selected"],
  properties: {
    // Standard Properties.
    abbr: null,
    accept: commaSeparated,
    acceptCharset: spaceSeparated,
    accessKey: spaceSeparated,
    action: null,
    allow: null,
    allowFullScreen: boolean,
    allowPaymentRequest: boolean,
    allowUserMedia: boolean,
    alt: null,
    as: null,
    async: boolean,
    autoCapitalize: null,
    autoComplete: spaceSeparated,
    autoFocus: boolean,
    autoPlay: boolean,
    blocking: spaceSeparated,
    capture: null,
    charSet: null,
    checked: boolean,
    cite: null,
    className: spaceSeparated,
    cols: number,
    colSpan: null,
    content: null,
    contentEditable: booleanish,
    controls: boolean,
    controlsList: spaceSeparated,
    coords: number | commaSeparated,
    crossOrigin: null,
    data: null,
    dateTime: null,
    decoding: null,
    default: boolean,
    defer: boolean,
    dir: null,
    dirName: null,
    disabled: boolean,
    download: overloadedBoolean,
    draggable: booleanish,
    encType: null,
    enterKeyHint: null,
    fetchPriority: null,
    form: null,
    formAction: null,
    formEncType: null,
    formMethod: null,
    formNoValidate: boolean,
    formTarget: null,
    headers: spaceSeparated,
    height: number,
    hidden: overloadedBoolean,
    high: number,
    href: null,
    hrefLang: null,
    htmlFor: spaceSeparated,
    httpEquiv: spaceSeparated,
    id: null,
    imageSizes: null,
    imageSrcSet: null,
    inert: boolean,
    inputMode: null,
    integrity: null,
    is: null,
    isMap: boolean,
    itemId: null,
    itemProp: spaceSeparated,
    itemRef: spaceSeparated,
    itemScope: boolean,
    itemType: spaceSeparated,
    kind: null,
    label: null,
    lang: null,
    language: null,
    list: null,
    loading: null,
    loop: boolean,
    low: number,
    manifest: null,
    max: null,
    maxLength: number,
    media: null,
    method: null,
    min: null,
    minLength: number,
    multiple: boolean,
    muted: boolean,
    name: null,
    nonce: null,
    noModule: boolean,
    noValidate: boolean,
    onAbort: null,
    onAfterPrint: null,
    onAuxClick: null,
    onBeforeMatch: null,
    onBeforePrint: null,
    onBeforeToggle: null,
    onBeforeUnload: null,
    onBlur: null,
    onCancel: null,
    onCanPlay: null,
    onCanPlayThrough: null,
    onChange: null,
    onClick: null,
    onClose: null,
    onContextLost: null,
    onContextMenu: null,
    onContextRestored: null,
    onCopy: null,
    onCueChange: null,
    onCut: null,
    onDblClick: null,
    onDrag: null,
    onDragEnd: null,
    onDragEnter: null,
    onDragExit: null,
    onDragLeave: null,
    onDragOver: null,
    onDragStart: null,
    onDrop: null,
    onDurationChange: null,
    onEmptied: null,
    onEnded: null,
    onError: null,
    onFocus: null,
    onFormData: null,
    onHashChange: null,
    onInput: null,
    onInvalid: null,
    onKeyDown: null,
    onKeyPress: null,
    onKeyUp: null,
    onLanguageChange: null,
    onLoad: null,
    onLoadedData: null,
    onLoadedMetadata: null,
    onLoadEnd: null,
    onLoadStart: null,
    onMessage: null,
    onMessageError: null,
    onMouseDown: null,
    onMouseEnter: null,
    onMouseLeave: null,
    onMouseMove: null,
    onMouseOut: null,
    onMouseOver: null,
    onMouseUp: null,
    onOffline: null,
    onOnline: null,
    onPageHide: null,
    onPageShow: null,
    onPaste: null,
    onPause: null,
    onPlay: null,
    onPlaying: null,
    onPopState: null,
    onProgress: null,
    onRateChange: null,
    onRejectionHandled: null,
    onReset: null,
    onResize: null,
    onScroll: null,
    onScrollEnd: null,
    onSecurityPolicyViolation: null,
    onSeeked: null,
    onSeeking: null,
    onSelect: null,
    onSlotChange: null,
    onStalled: null,
    onStorage: null,
    onSubmit: null,
    onSuspend: null,
    onTimeUpdate: null,
    onToggle: null,
    onUnhandledRejection: null,
    onUnload: null,
    onVolumeChange: null,
    onWaiting: null,
    onWheel: null,
    open: boolean,
    optimum: number,
    pattern: null,
    ping: spaceSeparated,
    placeholder: null,
    playsInline: boolean,
    popover: null,
    popoverTarget: null,
    popoverTargetAction: null,
    poster: null,
    preload: null,
    readOnly: boolean,
    referrerPolicy: null,
    rel: spaceSeparated,
    required: boolean,
    reversed: boolean,
    rows: number,
    rowSpan: number,
    sandbox: spaceSeparated,
    scope: null,
    scoped: boolean,
    seamless: boolean,
    selected: boolean,
    shadowRootClonable: boolean,
    shadowRootDelegatesFocus: boolean,
    shadowRootMode: null,
    shape: null,
    size: number,
    sizes: null,
    slot: null,
    span: number,
    spellCheck: booleanish,
    src: null,
    srcDoc: null,
    srcLang: null,
    srcSet: null,
    start: number,
    step: null,
    style: null,
    tabIndex: number,
    target: null,
    title: null,
    translate: null,
    type: null,
    typeMustMatch: boolean,
    useMap: null,
    value: booleanish,
    width: number,
    wrap: null,
    writingSuggestions: null,
    // Legacy.
    // See: https://html.spec.whatwg.org/#other-elements,-attributes-and-apis
    align: null,
    // Several. Use CSS `text-align` instead,
    aLink: null,
    // `<body>`. Use CSS `a:active {color}` instead
    archive: spaceSeparated,
    // `<object>`. List of URIs to archives
    axis: null,
    // `<td>` and `<th>`. Use `scope` on `<th>`
    background: null,
    // `<body>`. Use CSS `background-image` instead
    bgColor: null,
    // `<body>` and table elements. Use CSS `background-color` instead
    border: number,
    // `<table>`. Use CSS `border-width` instead,
    borderColor: null,
    // `<table>`. Use CSS `border-color` instead,
    bottomMargin: number,
    // `<body>`
    cellPadding: null,
    // `<table>`
    cellSpacing: null,
    // `<table>`
    char: null,
    // Several table elements. When `align=char`, sets the character to align on
    charOff: null,
    // Several table elements. When `char`, offsets the alignment
    classId: null,
    // `<object>`
    clear: null,
    // `<br>`. Use CSS `clear` instead
    code: null,
    // `<object>`
    codeBase: null,
    // `<object>`
    codeType: null,
    // `<object>`
    color: null,
    // `<font>` and `<hr>`. Use CSS instead
    compact: boolean,
    // Lists. Use CSS to reduce space between items instead
    declare: boolean,
    // `<object>`
    event: null,
    // `<script>`
    face: null,
    // `<font>`. Use CSS instead
    frame: null,
    // `<table>`
    frameBorder: null,
    // `<iframe>`. Use CSS `border` instead
    hSpace: number,
    // `<img>` and `<object>`
    leftMargin: number,
    // `<body>`
    link: null,
    // `<body>`. Use CSS `a:link {color: *}` instead
    longDesc: null,
    // `<frame>`, `<iframe>`, and `<img>`. Use an `<a>`
    lowSrc: null,
    // `<img>`. Use a `<picture>`
    marginHeight: number,
    // `<body>`
    marginWidth: number,
    // `<body>`
    noResize: boolean,
    // `<frame>`
    noHref: boolean,
    // `<area>`. Use no href instead of an explicit `nohref`
    noShade: boolean,
    // `<hr>`. Use background-color and height instead of borders
    noWrap: boolean,
    // `<td>` and `<th>`
    object: null,
    // `<applet>`
    profile: null,
    // `<head>`
    prompt: null,
    // `<isindex>`
    rev: null,
    // `<link>`
    rightMargin: number,
    // `<body>`
    rules: null,
    // `<table>`
    scheme: null,
    // `<meta>`
    scrolling: booleanish,
    // `<frame>`. Use overflow in the child context
    standby: null,
    // `<object>`
    summary: null,
    // `<table>`
    text: null,
    // `<body>`. Use CSS `color` instead
    topMargin: number,
    // `<body>`
    valueType: null,
    // `<param>`
    version: null,
    // `<html>`. Use a doctype.
    vAlign: null,
    // Several. Use CSS `vertical-align` instead
    vLink: null,
    // `<body>`. Use CSS `a:visited {color}` instead
    vSpace: number,
    // `<img>` and `<object>`
    // Non-standard Properties.
    allowTransparency: null,
    autoCorrect: null,
    autoSave: null,
    disablePictureInPicture: boolean,
    disableRemotePlayback: boolean,
    prefix: null,
    property: null,
    results: number,
    security: null,
    unselectable: null
  },
  space: "html",
  transform: caseInsensitiveTransform
});

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/svg.js
var svg = create7({
  attributes: {
    accentHeight: "accent-height",
    alignmentBaseline: "alignment-baseline",
    arabicForm: "arabic-form",
    baselineShift: "baseline-shift",
    capHeight: "cap-height",
    className: "class",
    clipPath: "clip-path",
    clipRule: "clip-rule",
    colorInterpolation: "color-interpolation",
    colorInterpolationFilters: "color-interpolation-filters",
    colorProfile: "color-profile",
    colorRendering: "color-rendering",
    crossOrigin: "crossorigin",
    dataType: "datatype",
    dominantBaseline: "dominant-baseline",
    enableBackground: "enable-background",
    fillOpacity: "fill-opacity",
    fillRule: "fill-rule",
    floodColor: "flood-color",
    floodOpacity: "flood-opacity",
    fontFamily: "font-family",
    fontSize: "font-size",
    fontSizeAdjust: "font-size-adjust",
    fontStretch: "font-stretch",
    fontStyle: "font-style",
    fontVariant: "font-variant",
    fontWeight: "font-weight",
    glyphName: "glyph-name",
    glyphOrientationHorizontal: "glyph-orientation-horizontal",
    glyphOrientationVertical: "glyph-orientation-vertical",
    hrefLang: "hreflang",
    horizAdvX: "horiz-adv-x",
    horizOriginX: "horiz-origin-x",
    horizOriginY: "horiz-origin-y",
    imageRendering: "image-rendering",
    letterSpacing: "letter-spacing",
    lightingColor: "lighting-color",
    markerEnd: "marker-end",
    markerMid: "marker-mid",
    markerStart: "marker-start",
    navDown: "nav-down",
    navDownLeft: "nav-down-left",
    navDownRight: "nav-down-right",
    navLeft: "nav-left",
    navNext: "nav-next",
    navPrev: "nav-prev",
    navRight: "nav-right",
    navUp: "nav-up",
    navUpLeft: "nav-up-left",
    navUpRight: "nav-up-right",
    onAbort: "onabort",
    onActivate: "onactivate",
    onAfterPrint: "onafterprint",
    onBeforePrint: "onbeforeprint",
    onBegin: "onbegin",
    onCancel: "oncancel",
    onCanPlay: "oncanplay",
    onCanPlayThrough: "oncanplaythrough",
    onChange: "onchange",
    onClick: "onclick",
    onClose: "onclose",
    onCopy: "oncopy",
    onCueChange: "oncuechange",
    onCut: "oncut",
    onDblClick: "ondblclick",
    onDrag: "ondrag",
    onDragEnd: "ondragend",
    onDragEnter: "ondragenter",
    onDragExit: "ondragexit",
    onDragLeave: "ondragleave",
    onDragOver: "ondragover",
    onDragStart: "ondragstart",
    onDrop: "ondrop",
    onDurationChange: "ondurationchange",
    onEmptied: "onemptied",
    onEnd: "onend",
    onEnded: "onended",
    onError: "onerror",
    onFocus: "onfocus",
    onFocusIn: "onfocusin",
    onFocusOut: "onfocusout",
    onHashChange: "onhashchange",
    onInput: "oninput",
    onInvalid: "oninvalid",
    onKeyDown: "onkeydown",
    onKeyPress: "onkeypress",
    onKeyUp: "onkeyup",
    onLoad: "onload",
    onLoadedData: "onloadeddata",
    onLoadedMetadata: "onloadedmetadata",
    onLoadStart: "onloadstart",
    onMessage: "onmessage",
    onMouseDown: "onmousedown",
    onMouseEnter: "onmouseenter",
    onMouseLeave: "onmouseleave",
    onMouseMove: "onmousemove",
    onMouseOut: "onmouseout",
    onMouseOver: "onmouseover",
    onMouseUp: "onmouseup",
    onMouseWheel: "onmousewheel",
    onOffline: "onoffline",
    onOnline: "ononline",
    onPageHide: "onpagehide",
    onPageShow: "onpageshow",
    onPaste: "onpaste",
    onPause: "onpause",
    onPlay: "onplay",
    onPlaying: "onplaying",
    onPopState: "onpopstate",
    onProgress: "onprogress",
    onRateChange: "onratechange",
    onRepeat: "onrepeat",
    onReset: "onreset",
    onResize: "onresize",
    onScroll: "onscroll",
    onSeeked: "onseeked",
    onSeeking: "onseeking",
    onSelect: "onselect",
    onShow: "onshow",
    onStalled: "onstalled",
    onStorage: "onstorage",
    onSubmit: "onsubmit",
    onSuspend: "onsuspend",
    onTimeUpdate: "ontimeupdate",
    onToggle: "ontoggle",
    onUnload: "onunload",
    onVolumeChange: "onvolumechange",
    onWaiting: "onwaiting",
    onZoom: "onzoom",
    overlinePosition: "overline-position",
    overlineThickness: "overline-thickness",
    paintOrder: "paint-order",
    panose1: "panose-1",
    pointerEvents: "pointer-events",
    referrerPolicy: "referrerpolicy",
    renderingIntent: "rendering-intent",
    shapeRendering: "shape-rendering",
    stopColor: "stop-color",
    stopOpacity: "stop-opacity",
    strikethroughPosition: "strikethrough-position",
    strikethroughThickness: "strikethrough-thickness",
    strokeDashArray: "stroke-dasharray",
    strokeDashOffset: "stroke-dashoffset",
    strokeLineCap: "stroke-linecap",
    strokeLineJoin: "stroke-linejoin",
    strokeMiterLimit: "stroke-miterlimit",
    strokeOpacity: "stroke-opacity",
    strokeWidth: "stroke-width",
    tabIndex: "tabindex",
    textAnchor: "text-anchor",
    textDecoration: "text-decoration",
    textRendering: "text-rendering",
    transformOrigin: "transform-origin",
    typeOf: "typeof",
    underlinePosition: "underline-position",
    underlineThickness: "underline-thickness",
    unicodeBidi: "unicode-bidi",
    unicodeRange: "unicode-range",
    unitsPerEm: "units-per-em",
    vAlphabetic: "v-alphabetic",
    vHanging: "v-hanging",
    vIdeographic: "v-ideographic",
    vMathematical: "v-mathematical",
    vectorEffect: "vector-effect",
    vertAdvY: "vert-adv-y",
    vertOriginX: "vert-origin-x",
    vertOriginY: "vert-origin-y",
    wordSpacing: "word-spacing",
    writingMode: "writing-mode",
    xHeight: "x-height",
    // These were camelcased in Tiny. Now lowercased in SVG 2
    playbackOrder: "playbackorder",
    timelineBegin: "timelinebegin"
  },
  properties: {
    about: commaOrSpaceSeparated,
    accentHeight: number,
    accumulate: null,
    additive: null,
    alignmentBaseline: null,
    alphabetic: number,
    amplitude: number,
    arabicForm: null,
    ascent: number,
    attributeName: null,
    attributeType: null,
    azimuth: number,
    bandwidth: null,
    baselineShift: null,
    baseFrequency: null,
    baseProfile: null,
    bbox: null,
    begin: null,
    bias: number,
    by: null,
    calcMode: null,
    capHeight: number,
    className: spaceSeparated,
    clip: null,
    clipPath: null,
    clipPathUnits: null,
    clipRule: null,
    color: null,
    colorInterpolation: null,
    colorInterpolationFilters: null,
    colorProfile: null,
    colorRendering: null,
    content: null,
    contentScriptType: null,
    contentStyleType: null,
    crossOrigin: null,
    cursor: null,
    cx: null,
    cy: null,
    d: null,
    dataType: null,
    defaultAction: null,
    descent: number,
    diffuseConstant: number,
    direction: null,
    display: null,
    dur: null,
    divisor: number,
    dominantBaseline: null,
    download: boolean,
    dx: null,
    dy: null,
    edgeMode: null,
    editable: null,
    elevation: number,
    enableBackground: null,
    end: null,
    event: null,
    exponent: number,
    externalResourcesRequired: null,
    fill: null,
    fillOpacity: number,
    fillRule: null,
    filter: null,
    filterRes: null,
    filterUnits: null,
    floodColor: null,
    floodOpacity: null,
    focusable: null,
    focusHighlight: null,
    fontFamily: null,
    fontSize: null,
    fontSizeAdjust: null,
    fontStretch: null,
    fontStyle: null,
    fontVariant: null,
    fontWeight: null,
    format: null,
    fr: null,
    from: null,
    fx: null,
    fy: null,
    g1: commaSeparated,
    g2: commaSeparated,
    glyphName: commaSeparated,
    glyphOrientationHorizontal: null,
    glyphOrientationVertical: null,
    glyphRef: null,
    gradientTransform: null,
    gradientUnits: null,
    handler: null,
    hanging: number,
    hatchContentUnits: null,
    hatchUnits: null,
    height: null,
    href: null,
    hrefLang: null,
    horizAdvX: number,
    horizOriginX: number,
    horizOriginY: number,
    id: null,
    ideographic: number,
    imageRendering: null,
    initialVisibility: null,
    in: null,
    in2: null,
    intercept: number,
    k: number,
    k1: number,
    k2: number,
    k3: number,
    k4: number,
    kernelMatrix: commaOrSpaceSeparated,
    kernelUnitLength: null,
    keyPoints: null,
    // SEMI_COLON_SEPARATED
    keySplines: null,
    // SEMI_COLON_SEPARATED
    keyTimes: null,
    // SEMI_COLON_SEPARATED
    kerning: null,
    lang: null,
    lengthAdjust: null,
    letterSpacing: null,
    lightingColor: null,
    limitingConeAngle: number,
    local: null,
    markerEnd: null,
    markerMid: null,
    markerStart: null,
    markerHeight: null,
    markerUnits: null,
    markerWidth: null,
    mask: null,
    maskContentUnits: null,
    maskUnits: null,
    mathematical: null,
    max: null,
    media: null,
    mediaCharacterEncoding: null,
    mediaContentEncodings: null,
    mediaSize: number,
    mediaTime: null,
    method: null,
    min: null,
    mode: null,
    name: null,
    navDown: null,
    navDownLeft: null,
    navDownRight: null,
    navLeft: null,
    navNext: null,
    navPrev: null,
    navRight: null,
    navUp: null,
    navUpLeft: null,
    navUpRight: null,
    numOctaves: null,
    observer: null,
    offset: null,
    onAbort: null,
    onActivate: null,
    onAfterPrint: null,
    onBeforePrint: null,
    onBegin: null,
    onCancel: null,
    onCanPlay: null,
    onCanPlayThrough: null,
    onChange: null,
    onClick: null,
    onClose: null,
    onCopy: null,
    onCueChange: null,
    onCut: null,
    onDblClick: null,
    onDrag: null,
    onDragEnd: null,
    onDragEnter: null,
    onDragExit: null,
    onDragLeave: null,
    onDragOver: null,
    onDragStart: null,
    onDrop: null,
    onDurationChange: null,
    onEmptied: null,
    onEnd: null,
    onEnded: null,
    onError: null,
    onFocus: null,
    onFocusIn: null,
    onFocusOut: null,
    onHashChange: null,
    onInput: null,
    onInvalid: null,
    onKeyDown: null,
    onKeyPress: null,
    onKeyUp: null,
    onLoad: null,
    onLoadedData: null,
    onLoadedMetadata: null,
    onLoadStart: null,
    onMessage: null,
    onMouseDown: null,
    onMouseEnter: null,
    onMouseLeave: null,
    onMouseMove: null,
    onMouseOut: null,
    onMouseOver: null,
    onMouseUp: null,
    onMouseWheel: null,
    onOffline: null,
    onOnline: null,
    onPageHide: null,
    onPageShow: null,
    onPaste: null,
    onPause: null,
    onPlay: null,
    onPlaying: null,
    onPopState: null,
    onProgress: null,
    onRateChange: null,
    onRepeat: null,
    onReset: null,
    onResize: null,
    onScroll: null,
    onSeeked: null,
    onSeeking: null,
    onSelect: null,
    onShow: null,
    onStalled: null,
    onStorage: null,
    onSubmit: null,
    onSuspend: null,
    onTimeUpdate: null,
    onToggle: null,
    onUnload: null,
    onVolumeChange: null,
    onWaiting: null,
    onZoom: null,
    opacity: null,
    operator: null,
    order: null,
    orient: null,
    orientation: null,
    origin: null,
    overflow: null,
    overlay: null,
    overlinePosition: number,
    overlineThickness: number,
    paintOrder: null,
    panose1: null,
    path: null,
    pathLength: number,
    patternContentUnits: null,
    patternTransform: null,
    patternUnits: null,
    phase: null,
    ping: spaceSeparated,
    pitch: null,
    playbackOrder: null,
    pointerEvents: null,
    points: null,
    pointsAtX: number,
    pointsAtY: number,
    pointsAtZ: number,
    preserveAlpha: null,
    preserveAspectRatio: null,
    primitiveUnits: null,
    propagate: null,
    property: commaOrSpaceSeparated,
    r: null,
    radius: null,
    referrerPolicy: null,
    refX: null,
    refY: null,
    rel: commaOrSpaceSeparated,
    rev: commaOrSpaceSeparated,
    renderingIntent: null,
    repeatCount: null,
    repeatDur: null,
    requiredExtensions: commaOrSpaceSeparated,
    requiredFeatures: commaOrSpaceSeparated,
    requiredFonts: commaOrSpaceSeparated,
    requiredFormats: commaOrSpaceSeparated,
    resource: null,
    restart: null,
    result: null,
    rotate: null,
    rx: null,
    ry: null,
    scale: null,
    seed: null,
    shapeRendering: null,
    side: null,
    slope: null,
    snapshotTime: null,
    specularConstant: number,
    specularExponent: number,
    spreadMethod: null,
    spacing: null,
    startOffset: null,
    stdDeviation: null,
    stemh: null,
    stemv: null,
    stitchTiles: null,
    stopColor: null,
    stopOpacity: null,
    strikethroughPosition: number,
    strikethroughThickness: number,
    string: null,
    stroke: null,
    strokeDashArray: commaOrSpaceSeparated,
    strokeDashOffset: null,
    strokeLineCap: null,
    strokeLineJoin: null,
    strokeMiterLimit: number,
    strokeOpacity: number,
    strokeWidth: null,
    style: null,
    surfaceScale: number,
    syncBehavior: null,
    syncBehaviorDefault: null,
    syncMaster: null,
    syncTolerance: null,
    syncToleranceDefault: null,
    systemLanguage: commaOrSpaceSeparated,
    tabIndex: number,
    tableValues: null,
    target: null,
    targetX: number,
    targetY: number,
    textAnchor: null,
    textDecoration: null,
    textRendering: null,
    textLength: null,
    timelineBegin: null,
    title: null,
    transformBehavior: null,
    type: null,
    typeOf: commaOrSpaceSeparated,
    to: null,
    transform: null,
    transformOrigin: null,
    u1: null,
    u2: null,
    underlinePosition: number,
    underlineThickness: number,
    unicode: null,
    unicodeBidi: null,
    unicodeRange: null,
    unitsPerEm: number,
    values: null,
    vAlphabetic: number,
    vMathematical: number,
    vectorEffect: null,
    vHanging: number,
    vIdeographic: number,
    version: null,
    vertAdvY: number,
    vertOriginX: number,
    vertOriginY: number,
    viewBox: null,
    viewTarget: null,
    visibility: null,
    width: null,
    widths: null,
    wordSpacing: null,
    writingMode: null,
    x: null,
    x1: null,
    x2: null,
    xChannelSelector: null,
    xHeight: number,
    y: null,
    y1: null,
    y2: null,
    yChannelSelector: null,
    z: null,
    zoomAndPan: null
  },
  space: "svg",
  transform: caseSensitiveTransform
});

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/xlink.js
var xlink = create7({
  properties: {
    xLinkActuate: null,
    xLinkArcRole: null,
    xLinkHref: null,
    xLinkRole: null,
    xLinkShow: null,
    xLinkTitle: null,
    xLinkType: null
  },
  space: "xlink",
  transform(_2, property) {
    return "xlink:" + property.slice(5).toLowerCase();
  }
});

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/xmlns.js
var xmlns = create7({
  attributes: { xmlnsxlink: "xmlns:xlink" },
  properties: { xmlnsXLink: null, xmlns: null },
  space: "xmlns",
  transform: caseInsensitiveTransform
});

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/xml.js
var xml = create7({
  properties: { xmlBase: null, xmlLang: null, xmlSpace: null },
  space: "xml",
  transform(_2, property) {
    return "xml:" + property.slice(3).toLowerCase();
  }
});

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/lib/find.js
var cap = /[A-Z]/g;
var dash = /-[a-z]/g;
var valid = /^data[-\w.:]+$/i;
function find2(schema, value) {
  const normal = normalize2(value);
  let property = value;
  let Type = Info;
  if (normal in schema.normal) {
    return schema.property[schema.normal[normal]];
  }
  if (normal.length > 4 && normal.slice(0, 4) === "data" && valid.test(value)) {
    if (value.charAt(4) === "-") {
      const rest = value.slice(5).replace(dash, camelcase);
      property = "data" + rest.charAt(0).toUpperCase() + rest.slice(1);
    } else {
      const rest = value.slice(4);
      if (!dash.test(rest)) {
        let dashes = rest.replace(cap, kebab);
        if (dashes.charAt(0) !== "-") {
          dashes = "-" + dashes;
        }
        value = "data" + dashes;
      }
    }
    Type = DefinedInfo;
  }
  return new Type(property, value);
}
function kebab($0) {
  return "-" + $0.toLowerCase();
}
function camelcase($0) {
  return $0.charAt(1).toUpperCase();
}

// ../../node_modules/.pnpm/property-information@7.1.0/node_modules/property-information/index.js
var html2 = merge([aria, html, xlink, xmlns, xml], "html");
var svg2 = merge([aria, svg, xlink, xmlns, xml], "svg");

// ../../node_modules/.pnpm/comma-separated-tokens@2.0.3/node_modules/comma-separated-tokens/index.js
function parse2(value) {
  const tokens = [];
  const input2 = String(value || "");
  let index4 = input2.indexOf(",");
  let start = 0;
  let end = false;
  while (!end) {
    if (index4 === -1) {
      index4 = input2.length;
      end = true;
    }
    const token = input2.slice(start, index4).trim();
    if (token || !end) {
      tokens.push(token);
    }
    start = index4 + 1;
    index4 = input2.indexOf(",", start);
  }
  return tokens;
}
function stringify3(values2, options2) {
  const settings = options2 || {};
  const input2 = values2[values2.length - 1] === "" ? [...values2, ""] : values2;
  return input2.join(
    (settings.padRight ? " " : "") + "," + (settings.padLeft === false ? "" : " ")
  ).trim();
}

// ../../node_modules/.pnpm/hast-util-parse-selector@4.0.0/node_modules/hast-util-parse-selector/lib/index.js
var search = /[#.]/g;
function parseSelector(selector, defaultTagName) {
  const value = selector || "";
  const props = {};
  let start = 0;
  let previous3;
  let tagName;
  while (start < value.length) {
    search.lastIndex = start;
    const match2 = search.exec(value);
    const subvalue = value.slice(start, match2 ? match2.index : value.length);
    if (subvalue) {
      if (!previous3) {
        tagName = subvalue;
      } else if (previous3 === "#") {
        props.id = subvalue;
      } else if (Array.isArray(props.className)) {
        props.className.push(subvalue);
      } else {
        props.className = [subvalue];
      }
      start += subvalue.length;
    }
    if (match2) {
      previous3 = match2[0];
      start++;
    }
  }
  return {
    type: "element",
    // @ts-expect-error: tag name is parsed.
    tagName: tagName || defaultTagName || "div",
    properties: props,
    children: []
  };
}

// ../../node_modules/.pnpm/space-separated-tokens@2.0.2/node_modules/space-separated-tokens/index.js
function parse3(value) {
  const input2 = String(value || "").trim();
  return input2 ? input2.split(/[ \t\n\r\f]+/g) : [];
}
function stringify4(values2) {
  return values2.join(" ").trim();
}

// ../../node_modules/.pnpm/hastscript@9.0.1/node_modules/hastscript/lib/create-h.js
function createH(schema, defaultTagName, caseSensitive) {
  const adjust = caseSensitive ? createAdjustMap(caseSensitive) : void 0;
  function h7(selector, properties, ...children) {
    let node2;
    if (selector === null || selector === void 0) {
      node2 = { type: "root", children: [] };
      const child = (
        /** @type {Child} */
        properties
      );
      children.unshift(child);
    } else {
      node2 = parseSelector(selector, defaultTagName);
      const lower = node2.tagName.toLowerCase();
      const adjusted = adjust ? adjust.get(lower) : void 0;
      node2.tagName = adjusted || lower;
      if (isChild(properties)) {
        children.unshift(properties);
      } else {
        for (const [key2, value] of Object.entries(properties)) {
          addProperty(schema, node2.properties, key2, value);
        }
      }
    }
    for (const child of children) {
      addChild(node2.children, child);
    }
    if (node2.type === "element" && node2.tagName === "template") {
      node2.content = { type: "root", children: node2.children };
      node2.children = [];
    }
    return node2;
  }
  return h7;
}
function isChild(value) {
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
    return true;
  }
  if (typeof value.type !== "string") return false;
  const record = (
    /** @type {Record<string, unknown>} */
    value
  );
  const keys5 = Object.keys(value);
  for (const key2 of keys5) {
    const value2 = record[key2];
    if (value2 && typeof value2 === "object") {
      if (!Array.isArray(value2)) return true;
      const list7 = (
        /** @type {ReadonlyArray<unknown>} */
        value2
      );
      for (const item of list7) {
        if (typeof item !== "number" && typeof item !== "string") {
          return true;
        }
      }
    }
  }
  if ("children" in value && Array.isArray(value.children)) {
    return true;
  }
  return false;
}
function addProperty(schema, properties, key2, value) {
  const info = find2(schema, key2);
  let result;
  if (value === null || value === void 0) return;
  if (typeof value === "number") {
    if (Number.isNaN(value)) return;
    result = value;
  } else if (typeof value === "boolean") {
    result = value;
  } else if (typeof value === "string") {
    if (info.spaceSeparated) {
      result = parse3(value);
    } else if (info.commaSeparated) {
      result = parse2(value);
    } else if (info.commaOrSpaceSeparated) {
      result = parse3(parse2(value).join(" "));
    } else {
      result = parsePrimitive(info, info.property, value);
    }
  } else if (Array.isArray(value)) {
    result = [...value];
  } else {
    result = info.property === "style" ? style2(value) : String(value);
  }
  if (Array.isArray(result)) {
    const finalResult = [];
    for (const item of result) {
      finalResult.push(
        /** @type {number | string} */
        parsePrimitive(info, info.property, item)
      );
    }
    result = finalResult;
  }
  if (info.property === "className" && Array.isArray(properties.className)) {
    result = properties.className.concat(
      /** @type {Array<number | string> | number | string} */
      result
    );
  }
  properties[info.property] = result;
}
function addChild(nodes, value) {
  if (value === null || value === void 0) {
  } else if (typeof value === "number" || typeof value === "string") {
    nodes.push({ type: "text", value: String(value) });
  } else if (Array.isArray(value)) {
    for (const child of value) {
      addChild(nodes, child);
    }
  } else if (typeof value === "object" && "type" in value) {
    if (value.type === "root") {
      addChild(nodes, value.children);
    } else {
      nodes.push(value);
    }
  } else {
    throw new Error("Expected node, nodes, or string, got `" + value + "`");
  }
}
function parsePrimitive(info, name, value) {
  if (typeof value === "string") {
    if (info.number && value && !Number.isNaN(Number(value))) {
      return Number(value);
    }
    if ((info.boolean || info.overloadedBoolean) && (value === "" || normalize2(value) === normalize2(name))) {
      return true;
    }
  }
  return value;
}
function style2(styles) {
  const result = [];
  for (const [key2, value] of Object.entries(styles)) {
    result.push([key2, value].join(": "));
  }
  return result.join("; ");
}
function createAdjustMap(values2) {
  const result = /* @__PURE__ */ new Map();
  for (const value of values2) {
    result.set(value.toLowerCase(), value);
  }
  return result;
}

// ../../node_modules/.pnpm/hastscript@9.0.1/node_modules/hastscript/lib/svg-case-sensitive-tag-names.js
var svgCaseSensitiveTagNames = [
  "altGlyph",
  "altGlyphDef",
  "altGlyphItem",
  "animateColor",
  "animateMotion",
  "animateTransform",
  "clipPath",
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feDistantLight",
  "feDropShadow",
  "feFlood",
  "feFuncA",
  "feFuncB",
  "feFuncG",
  "feFuncR",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMergeNode",
  "feMorphology",
  "feOffset",
  "fePointLight",
  "feSpecularLighting",
  "feSpotLight",
  "feTile",
  "feTurbulence",
  "foreignObject",
  "glyphRef",
  "linearGradient",
  "radialGradient",
  "solidColor",
  "textArea",
  "textPath"
];

// ../../node_modules/.pnpm/hastscript@9.0.1/node_modules/hastscript/lib/index.js
var h4 = createH(html2, "div");
var s = createH(svg2, "g", svgCaseSensitiveTagNames);

// ../../node_modules/.pnpm/vfile-location@5.0.3/node_modules/vfile-location/lib/index.js
function location2(file) {
  const value = String(file);
  const indices = [];
  return { toOffset, toPoint };
  function toPoint(offset4) {
    if (typeof offset4 === "number" && offset4 > -1 && offset4 <= value.length) {
      let index4 = 0;
      while (true) {
        let end = indices[index4];
        if (end === void 0) {
          const eol2 = next(value, indices[index4 - 1]);
          end = eol2 === -1 ? value.length + 1 : eol2 + 1;
          indices[index4] = end;
        }
        if (end > offset4) {
          return {
            line: index4 + 1,
            column: offset4 - (index4 > 0 ? indices[index4 - 1] : 0) + 1,
            offset: offset4
          };
        }
        index4++;
      }
    }
  }
  function toOffset(point5) {
    if (point5 && typeof point5.line === "number" && typeof point5.column === "number" && !Number.isNaN(point5.line) && !Number.isNaN(point5.column)) {
      while (indices.length < point5.line) {
        const from4 = indices[indices.length - 1];
        const eol2 = next(value, from4);
        const end = eol2 === -1 ? value.length + 1 : eol2 + 1;
        if (from4 === end) break;
        indices.push(end);
      }
      const offset4 = (point5.line > 1 ? indices[point5.line - 2] : 0) + point5.column - 1;
      if (offset4 < indices[point5.line - 1]) return offset4;
    }
  }
}
function next(value, from4) {
  const cr2 = value.indexOf("\r", from4);
  const lf = value.indexOf("\n", from4);
  if (lf === -1) return cr2;
  if (cr2 === -1 || cr2 + 1 === lf) return lf;
  return cr2 < lf ? cr2 : lf;
}

// ../../node_modules/.pnpm/web-namespaces@2.0.1/node_modules/web-namespaces/index.js
var webNamespaces = {
  html: "http://www.w3.org/1999/xhtml",
  mathml: "http://www.w3.org/1998/Math/MathML",
  svg: "http://www.w3.org/2000/svg",
  xlink: "http://www.w3.org/1999/xlink",
  xml: "http://www.w3.org/XML/1998/namespace",
  xmlns: "http://www.w3.org/2000/xmlns/"
};

// ../../node_modules/.pnpm/hast-util-from-parse5@8.0.3/node_modules/hast-util-from-parse5/lib/index.js
var own = {}.hasOwnProperty;
var proto = Object.prototype;
function fromParse5(tree, options2) {
  const settings = options2 || {};
  return one(
    {
      file: settings.file || void 0,
      location: false,
      schema: settings.space === "svg" ? svg2 : html2,
      verbose: settings.verbose || false
    },
    tree
  );
}
function one(state, node2) {
  let result;
  switch (node2.nodeName) {
    case "#comment": {
      const reference = (
        /** @type {DefaultTreeAdapterMap['commentNode']} */
        node2
      );
      result = { type: "comment", value: reference.data };
      patch(state, reference, result);
      return result;
    }
    case "#document":
    case "#document-fragment": {
      const reference = (
        /** @type {DefaultTreeAdapterMap['document'] | DefaultTreeAdapterMap['documentFragment']} */
        node2
      );
      const quirksMode = "mode" in reference ? reference.mode === "quirks" || reference.mode === "limited-quirks" : false;
      result = {
        type: "root",
        children: all2(state, node2.childNodes),
        data: { quirksMode }
      };
      if (state.file && state.location) {
        const document4 = String(state.file);
        const loc = location2(document4);
        const start = loc.toPoint(0);
        const end = loc.toPoint(document4.length);
        ok(start, "expected `start`");
        ok(end, "expected `end`");
        result.position = { start, end };
      }
      return result;
    }
    case "#documentType": {
      const reference = (
        /** @type {DefaultTreeAdapterMap['documentType']} */
        node2
      );
      result = { type: "doctype" };
      patch(state, reference, result);
      return result;
    }
    case "#text": {
      const reference = (
        /** @type {DefaultTreeAdapterMap['textNode']} */
        node2
      );
      result = { type: "text", value: reference.value };
      patch(state, reference, result);
      return result;
    }
    // Element.
    default: {
      const reference = (
        /** @type {DefaultTreeAdapterMap['element']} */
        node2
      );
      result = element2(state, reference);
      return result;
    }
  }
}
function all2(state, nodes) {
  let index4 = -1;
  const results = [];
  while (++index4 < nodes.length) {
    const result = (
      /** @type {RootContent} */
      one(state, nodes[index4])
    );
    results.push(result);
  }
  return results;
}
function element2(state, node2) {
  const schema = state.schema;
  state.schema = node2.namespaceURI === webNamespaces.svg ? svg2 : html2;
  let index4 = -1;
  const properties = {};
  while (++index4 < node2.attrs.length) {
    const attribute = node2.attrs[index4];
    const name = (attribute.prefix ? attribute.prefix + ":" : "") + attribute.name;
    if (!own.call(proto, name)) {
      properties[name] = attribute.value;
    }
  }
  const x5 = state.schema.space === "svg" ? s : h4;
  const result = x5(node2.tagName, properties, all2(state, node2.childNodes));
  patch(state, node2, result);
  if (result.tagName === "template") {
    const reference = (
      /** @type {DefaultTreeAdapterMap['template']} */
      node2
    );
    const pos = reference.sourceCodeLocation;
    const startTag = pos && pos.startTag && position(pos.startTag);
    const endTag = pos && pos.endTag && position(pos.endTag);
    const content5 = (
      /** @type {Root} */
      one(state, reference.content)
    );
    if (startTag && endTag && state.file) {
      content5.position = { start: startTag.end, end: endTag.start };
    }
    result.content = content5;
  }
  state.schema = schema;
  return result;
}
function patch(state, from4, to2) {
  if ("sourceCodeLocation" in from4 && from4.sourceCodeLocation && state.file) {
    const position4 = createLocation(state, to2, from4.sourceCodeLocation);
    if (position4) {
      state.location = true;
      to2.position = position4;
    }
  }
}
function createLocation(state, node2, location3) {
  const result = position(location3);
  if (node2.type === "element") {
    const tail = node2.children[node2.children.length - 1];
    if (result && !location3.endTag && tail && tail.position && tail.position.end) {
      result.end = Object.assign({}, tail.position.end);
    }
    if (state.verbose) {
      const properties = {};
      let key2;
      if (location3.attrs) {
        for (key2 in location3.attrs) {
          if (own.call(location3.attrs, key2)) {
            properties[find2(state.schema, key2).property] = position(
              location3.attrs[key2]
            );
          }
        }
      }
      ok(location3.startTag, "a start tag should exist");
      const opening2 = position(location3.startTag);
      const closing2 = location3.endTag ? position(location3.endTag) : void 0;
      const data = { opening: opening2 };
      if (closing2) data.closing = closing2;
      data.properties = properties;
      node2.data = { position: data };
    }
  }
  return result;
}
function position(loc) {
  const start = point({
    line: loc.startLine,
    column: loc.startCol,
    offset: loc.startOffset
  });
  const end = point({
    line: loc.endLine,
    column: loc.endCol,
    offset: loc.endOffset
  });
  return start || end ? { start, end } : void 0;
}
function point(point5) {
  return point5.line && point5.column ? point5 : void 0;
}

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/common/unicode.js
var UNDEFINED_CODE_POINTS = /* @__PURE__ */ new Set([
  65534,
  65535,
  131070,
  131071,
  196606,
  196607,
  262142,
  262143,
  327678,
  327679,
  393214,
  393215,
  458750,
  458751,
  524286,
  524287,
  589822,
  589823,
  655358,
  655359,
  720894,
  720895,
  786430,
  786431,
  851966,
  851967,
  917502,
  917503,
  983038,
  983039,
  1048574,
  1048575,
  1114110,
  1114111
]);
var REPLACEMENT_CHARACTER = "�";
var CODE_POINTS;
(function(CODE_POINTS2) {
  CODE_POINTS2[CODE_POINTS2["EOF"] = -1] = "EOF";
  CODE_POINTS2[CODE_POINTS2["NULL"] = 0] = "NULL";
  CODE_POINTS2[CODE_POINTS2["TABULATION"] = 9] = "TABULATION";
  CODE_POINTS2[CODE_POINTS2["CARRIAGE_RETURN"] = 13] = "CARRIAGE_RETURN";
  CODE_POINTS2[CODE_POINTS2["LINE_FEED"] = 10] = "LINE_FEED";
  CODE_POINTS2[CODE_POINTS2["FORM_FEED"] = 12] = "FORM_FEED";
  CODE_POINTS2[CODE_POINTS2["SPACE"] = 32] = "SPACE";
  CODE_POINTS2[CODE_POINTS2["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK";
  CODE_POINTS2[CODE_POINTS2["QUOTATION_MARK"] = 34] = "QUOTATION_MARK";
  CODE_POINTS2[CODE_POINTS2["AMPERSAND"] = 38] = "AMPERSAND";
  CODE_POINTS2[CODE_POINTS2["APOSTROPHE"] = 39] = "APOSTROPHE";
  CODE_POINTS2[CODE_POINTS2["HYPHEN_MINUS"] = 45] = "HYPHEN_MINUS";
  CODE_POINTS2[CODE_POINTS2["SOLIDUS"] = 47] = "SOLIDUS";
  CODE_POINTS2[CODE_POINTS2["DIGIT_0"] = 48] = "DIGIT_0";
  CODE_POINTS2[CODE_POINTS2["DIGIT_9"] = 57] = "DIGIT_9";
  CODE_POINTS2[CODE_POINTS2["SEMICOLON"] = 59] = "SEMICOLON";
  CODE_POINTS2[CODE_POINTS2["LESS_THAN_SIGN"] = 60] = "LESS_THAN_SIGN";
  CODE_POINTS2[CODE_POINTS2["EQUALS_SIGN"] = 61] = "EQUALS_SIGN";
  CODE_POINTS2[CODE_POINTS2["GREATER_THAN_SIGN"] = 62] = "GREATER_THAN_SIGN";
  CODE_POINTS2[CODE_POINTS2["QUESTION_MARK"] = 63] = "QUESTION_MARK";
  CODE_POINTS2[CODE_POINTS2["LATIN_CAPITAL_A"] = 65] = "LATIN_CAPITAL_A";
  CODE_POINTS2[CODE_POINTS2["LATIN_CAPITAL_Z"] = 90] = "LATIN_CAPITAL_Z";
  CODE_POINTS2[CODE_POINTS2["RIGHT_SQUARE_BRACKET"] = 93] = "RIGHT_SQUARE_BRACKET";
  CODE_POINTS2[CODE_POINTS2["GRAVE_ACCENT"] = 96] = "GRAVE_ACCENT";
  CODE_POINTS2[CODE_POINTS2["LATIN_SMALL_A"] = 97] = "LATIN_SMALL_A";
  CODE_POINTS2[CODE_POINTS2["LATIN_SMALL_Z"] = 122] = "LATIN_SMALL_Z";
})(CODE_POINTS || (CODE_POINTS = {}));
var SEQUENCES = {
  DASH_DASH: "--",
  CDATA_START: "[CDATA[",
  DOCTYPE: "doctype",
  SCRIPT: "script",
  PUBLIC: "public",
  SYSTEM: "system"
};
function isSurrogate(cp) {
  return cp >= 55296 && cp <= 57343;
}
function isSurrogatePair2(cp) {
  return cp >= 56320 && cp <= 57343;
}
function getSurrogatePairCodePoint(cp1, cp2) {
  return (cp1 - 55296) * 1024 + 9216 + cp2;
}
function isControlCodePoint(cp) {
  return cp !== 32 && cp !== 10 && cp !== 13 && cp !== 9 && cp !== 12 && cp >= 1 && cp <= 31 || cp >= 127 && cp <= 159;
}
function isUndefinedCodePoint(cp) {
  return cp >= 64976 && cp <= 65007 || UNDEFINED_CODE_POINTS.has(cp);
}

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/common/error-codes.js
var ERR;
(function(ERR2) {
  ERR2["controlCharacterInInputStream"] = "control-character-in-input-stream";
  ERR2["noncharacterInInputStream"] = "noncharacter-in-input-stream";
  ERR2["surrogateInInputStream"] = "surrogate-in-input-stream";
  ERR2["nonVoidHtmlElementStartTagWithTrailingSolidus"] = "non-void-html-element-start-tag-with-trailing-solidus";
  ERR2["endTagWithAttributes"] = "end-tag-with-attributes";
  ERR2["endTagWithTrailingSolidus"] = "end-tag-with-trailing-solidus";
  ERR2["unexpectedSolidusInTag"] = "unexpected-solidus-in-tag";
  ERR2["unexpectedNullCharacter"] = "unexpected-null-character";
  ERR2["unexpectedQuestionMarkInsteadOfTagName"] = "unexpected-question-mark-instead-of-tag-name";
  ERR2["invalidFirstCharacterOfTagName"] = "invalid-first-character-of-tag-name";
  ERR2["unexpectedEqualsSignBeforeAttributeName"] = "unexpected-equals-sign-before-attribute-name";
  ERR2["missingEndTagName"] = "missing-end-tag-name";
  ERR2["unexpectedCharacterInAttributeName"] = "unexpected-character-in-attribute-name";
  ERR2["unknownNamedCharacterReference"] = "unknown-named-character-reference";
  ERR2["missingSemicolonAfterCharacterReference"] = "missing-semicolon-after-character-reference";
  ERR2["unexpectedCharacterAfterDoctypeSystemIdentifier"] = "unexpected-character-after-doctype-system-identifier";
  ERR2["unexpectedCharacterInUnquotedAttributeValue"] = "unexpected-character-in-unquoted-attribute-value";
  ERR2["eofBeforeTagName"] = "eof-before-tag-name";
  ERR2["eofInTag"] = "eof-in-tag";
  ERR2["missingAttributeValue"] = "missing-attribute-value";
  ERR2["missingWhitespaceBetweenAttributes"] = "missing-whitespace-between-attributes";
  ERR2["missingWhitespaceAfterDoctypePublicKeyword"] = "missing-whitespace-after-doctype-public-keyword";
  ERR2["missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers"] = "missing-whitespace-between-doctype-public-and-system-identifiers";
  ERR2["missingWhitespaceAfterDoctypeSystemKeyword"] = "missing-whitespace-after-doctype-system-keyword";
  ERR2["missingQuoteBeforeDoctypePublicIdentifier"] = "missing-quote-before-doctype-public-identifier";
  ERR2["missingQuoteBeforeDoctypeSystemIdentifier"] = "missing-quote-before-doctype-system-identifier";
  ERR2["missingDoctypePublicIdentifier"] = "missing-doctype-public-identifier";
  ERR2["missingDoctypeSystemIdentifier"] = "missing-doctype-system-identifier";
  ERR2["abruptDoctypePublicIdentifier"] = "abrupt-doctype-public-identifier";
  ERR2["abruptDoctypeSystemIdentifier"] = "abrupt-doctype-system-identifier";
  ERR2["cdataInHtmlContent"] = "cdata-in-html-content";
  ERR2["incorrectlyOpenedComment"] = "incorrectly-opened-comment";
  ERR2["eofInScriptHtmlCommentLikeText"] = "eof-in-script-html-comment-like-text";
  ERR2["eofInDoctype"] = "eof-in-doctype";
  ERR2["nestedComment"] = "nested-comment";
  ERR2["abruptClosingOfEmptyComment"] = "abrupt-closing-of-empty-comment";
  ERR2["eofInComment"] = "eof-in-comment";
  ERR2["incorrectlyClosedComment"] = "incorrectly-closed-comment";
  ERR2["eofInCdata"] = "eof-in-cdata";
  ERR2["absenceOfDigitsInNumericCharacterReference"] = "absence-of-digits-in-numeric-character-reference";
  ERR2["nullCharacterReference"] = "null-character-reference";
  ERR2["surrogateCharacterReference"] = "surrogate-character-reference";
  ERR2["characterReferenceOutsideUnicodeRange"] = "character-reference-outside-unicode-range";
  ERR2["controlCharacterReference"] = "control-character-reference";
  ERR2["noncharacterCharacterReference"] = "noncharacter-character-reference";
  ERR2["missingWhitespaceBeforeDoctypeName"] = "missing-whitespace-before-doctype-name";
  ERR2["missingDoctypeName"] = "missing-doctype-name";
  ERR2["invalidCharacterSequenceAfterDoctypeName"] = "invalid-character-sequence-after-doctype-name";
  ERR2["duplicateAttribute"] = "duplicate-attribute";
  ERR2["nonConformingDoctype"] = "non-conforming-doctype";
  ERR2["missingDoctype"] = "missing-doctype";
  ERR2["misplacedDoctype"] = "misplaced-doctype";
  ERR2["endTagWithoutMatchingOpenElement"] = "end-tag-without-matching-open-element";
  ERR2["closingOfElementWithOpenChildElements"] = "closing-of-element-with-open-child-elements";
  ERR2["disallowedContentInNoscriptInHead"] = "disallowed-content-in-noscript-in-head";
  ERR2["openElementsLeftAfterEof"] = "open-elements-left-after-eof";
  ERR2["abandonedHeadElementChild"] = "abandoned-head-element-child";
  ERR2["misplacedStartTagForHeadElement"] = "misplaced-start-tag-for-head-element";
  ERR2["nestedNoscriptInHead"] = "nested-noscript-in-head";
  ERR2["eofInElementThatCanContainOnlyText"] = "eof-in-element-that-can-contain-only-text";
})(ERR || (ERR = {}));

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/tokenizer/preprocessor.js
var DEFAULT_BUFFER_WATERLINE = 1 << 16;
var Preprocessor = class {
  constructor(handler) {
    this.handler = handler;
    this.html = "";
    this.pos = -1;
    this.lastGapPos = -2;
    this.gapStack = [];
    this.skipNextNewLine = false;
    this.lastChunkWritten = false;
    this.endOfChunkHit = false;
    this.bufferWaterline = DEFAULT_BUFFER_WATERLINE;
    this.isEol = false;
    this.lineStartPos = 0;
    this.droppedBufferSize = 0;
    this.line = 1;
    this.lastErrOffset = -1;
  }
  /** The column on the current line. If we just saw a gap (eg. a surrogate pair), return the index before. */
  get col() {
    return this.pos - this.lineStartPos + Number(this.lastGapPos !== this.pos);
  }
  get offset() {
    return this.droppedBufferSize + this.pos;
  }
  getError(code5, cpOffset) {
    const { line, col, offset: offset4 } = this;
    const startCol = col + cpOffset;
    const startOffset = offset4 + cpOffset;
    return {
      code: code5,
      startLine: line,
      endLine: line,
      startCol,
      endCol: startCol,
      startOffset,
      endOffset: startOffset
    };
  }
  _err(code5) {
    if (this.handler.onParseError && this.lastErrOffset !== this.offset) {
      this.lastErrOffset = this.offset;
      this.handler.onParseError(this.getError(code5, 0));
    }
  }
  _addGap() {
    this.gapStack.push(this.lastGapPos);
    this.lastGapPos = this.pos;
  }
  _processSurrogate(cp) {
    if (this.pos !== this.html.length - 1) {
      const nextCp = this.html.charCodeAt(this.pos + 1);
      if (isSurrogatePair2(nextCp)) {
        this.pos++;
        this._addGap();
        return getSurrogatePairCodePoint(cp, nextCp);
      }
    } else if (!this.lastChunkWritten) {
      this.endOfChunkHit = true;
      return CODE_POINTS.EOF;
    }
    this._err(ERR.surrogateInInputStream);
    return cp;
  }
  willDropParsedChunk() {
    return this.pos > this.bufferWaterline;
  }
  dropParsedChunk() {
    if (this.willDropParsedChunk()) {
      this.html = this.html.substring(this.pos);
      this.lineStartPos -= this.pos;
      this.droppedBufferSize += this.pos;
      this.pos = 0;
      this.lastGapPos = -2;
      this.gapStack.length = 0;
    }
  }
  write(chunk, isLastChunk) {
    if (this.html.length > 0) {
      this.html += chunk;
    } else {
      this.html = chunk;
    }
    this.endOfChunkHit = false;
    this.lastChunkWritten = isLastChunk;
  }
  insertHtmlAtCurrentPos(chunk) {
    this.html = this.html.substring(0, this.pos + 1) + chunk + this.html.substring(this.pos + 1);
    this.endOfChunkHit = false;
  }
  startsWith(pattern, caseSensitive) {
    if (this.pos + pattern.length > this.html.length) {
      this.endOfChunkHit = !this.lastChunkWritten;
      return false;
    }
    if (caseSensitive) {
      return this.html.startsWith(pattern, this.pos);
    }
    for (let i3 = 0; i3 < pattern.length; i3++) {
      const cp = this.html.charCodeAt(this.pos + i3) | 32;
      if (cp !== pattern.charCodeAt(i3)) {
        return false;
      }
    }
    return true;
  }
  peek(offset4) {
    const pos = this.pos + offset4;
    if (pos >= this.html.length) {
      this.endOfChunkHit = !this.lastChunkWritten;
      return CODE_POINTS.EOF;
    }
    const code5 = this.html.charCodeAt(pos);
    return code5 === CODE_POINTS.CARRIAGE_RETURN ? CODE_POINTS.LINE_FEED : code5;
  }
  advance() {
    this.pos++;
    if (this.isEol) {
      this.isEol = false;
      this.line++;
      this.lineStartPos = this.pos;
    }
    if (this.pos >= this.html.length) {
      this.endOfChunkHit = !this.lastChunkWritten;
      return CODE_POINTS.EOF;
    }
    let cp = this.html.charCodeAt(this.pos);
    if (cp === CODE_POINTS.CARRIAGE_RETURN) {
      this.isEol = true;
      this.skipNextNewLine = true;
      return CODE_POINTS.LINE_FEED;
    }
    if (cp === CODE_POINTS.LINE_FEED) {
      this.isEol = true;
      if (this.skipNextNewLine) {
        this.line--;
        this.skipNextNewLine = false;
        this._addGap();
        return this.advance();
      }
    }
    this.skipNextNewLine = false;
    if (isSurrogate(cp)) {
      cp = this._processSurrogate(cp);
    }
    const isCommonValidRange = this.handler.onParseError === null || cp > 31 && cp < 127 || cp === CODE_POINTS.LINE_FEED || cp === CODE_POINTS.CARRIAGE_RETURN || cp > 159 && cp < 64976;
    if (!isCommonValidRange) {
      this._checkForProblematicCharacters(cp);
    }
    return cp;
  }
  _checkForProblematicCharacters(cp) {
    if (isControlCodePoint(cp)) {
      this._err(ERR.controlCharacterInInputStream);
    } else if (isUndefinedCodePoint(cp)) {
      this._err(ERR.noncharacterInInputStream);
    }
  }
  retreat(count2) {
    this.pos -= count2;
    while (this.pos < this.lastGapPos) {
      this.lastGapPos = this.gapStack.pop();
      this.pos--;
    }
    this.isEol = false;
  }
};

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/common/token.js
var token_exports = {};
__export(token_exports, {
  TokenType: () => TokenType,
  getTokenAttr: () => getTokenAttr
});
var TokenType;
(function(TokenType2) {
  TokenType2[TokenType2["CHARACTER"] = 0] = "CHARACTER";
  TokenType2[TokenType2["NULL_CHARACTER"] = 1] = "NULL_CHARACTER";
  TokenType2[TokenType2["WHITESPACE_CHARACTER"] = 2] = "WHITESPACE_CHARACTER";
  TokenType2[TokenType2["START_TAG"] = 3] = "START_TAG";
  TokenType2[TokenType2["END_TAG"] = 4] = "END_TAG";
  TokenType2[TokenType2["COMMENT"] = 5] = "COMMENT";
  TokenType2[TokenType2["DOCTYPE"] = 6] = "DOCTYPE";
  TokenType2[TokenType2["EOF"] = 7] = "EOF";
  TokenType2[TokenType2["HIBERNATION"] = 8] = "HIBERNATION";
})(TokenType || (TokenType = {}));
function getTokenAttr(token, attrName) {
  for (let i3 = token.attrs.length - 1; i3 >= 0; i3--) {
    if (token.attrs[i3].name === attrName) {
      return token.attrs[i3].value;
    }
  }
  return null;
}

// ../../node_modules/.pnpm/entities@6.0.1/node_modules/entities/dist/esm/generated/decode-data-html.js
var htmlDecodeTree = new Uint16Array(
  // prettier-ignore
  'ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTǇǋǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉ǲኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻ǲᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤĳạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ﬃɩᾹ\0\0᾽g;耀ﬀig;耀ﬄ;쀀𝔣lig;耀ﬁlig;쀀fjƀaltῙ῜ῡt;晭ig;耀ﬂns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒α‚‰‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସǳ⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗǈⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼ǲ㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map((c3) => c3.charCodeAt(0))
);

// ../../node_modules/.pnpm/entities@6.0.1/node_modules/entities/dist/esm/generated/decode-data-xml.js
var xmlDecodeTree = new Uint16Array(
  // prettier-ignore
  "Ȁaglq	\x1Bɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map((c3) => c3.charCodeAt(0))
);

// ../../node_modules/.pnpm/entities@6.0.1/node_modules/entities/dist/esm/decode-codepoint.js
var _a;
var decodeMap = /* @__PURE__ */ new Map([
  [0, 65533],
  // C1 Unicode control character reference replacements
  [128, 8364],
  [130, 8218],
  [131, 402],
  [132, 8222],
  [133, 8230],
  [134, 8224],
  [135, 8225],
  [136, 710],
  [137, 8240],
  [138, 352],
  [139, 8249],
  [140, 338],
  [142, 381],
  [145, 8216],
  [146, 8217],
  [147, 8220],
  [148, 8221],
  [149, 8226],
  [150, 8211],
  [151, 8212],
  [152, 732],
  [153, 8482],
  [154, 353],
  [155, 8250],
  [156, 339],
  [158, 382],
  [159, 376]
]);
var fromCodePoint2 = (
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, n/no-unsupported-features/es-builtins
  (_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function(codePoint) {
    let output = "";
    if (codePoint > 65535) {
      codePoint -= 65536;
      output += String.fromCharCode(codePoint >>> 10 & 1023 | 55296);
      codePoint = 56320 | codePoint & 1023;
    }
    output += String.fromCharCode(codePoint);
    return output;
  }
);
function replaceCodePoint(codePoint) {
  var _a2;
  if (codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111) {
    return 65533;
  }
  return (_a2 = decodeMap.get(codePoint)) !== null && _a2 !== void 0 ? _a2 : codePoint;
}

// ../../node_modules/.pnpm/entities@6.0.1/node_modules/entities/dist/esm/decode.js
var CharCodes;
(function(CharCodes2) {
  CharCodes2[CharCodes2["NUM"] = 35] = "NUM";
  CharCodes2[CharCodes2["SEMI"] = 59] = "SEMI";
  CharCodes2[CharCodes2["EQUALS"] = 61] = "EQUALS";
  CharCodes2[CharCodes2["ZERO"] = 48] = "ZERO";
  CharCodes2[CharCodes2["NINE"] = 57] = "NINE";
  CharCodes2[CharCodes2["LOWER_A"] = 97] = "LOWER_A";
  CharCodes2[CharCodes2["LOWER_F"] = 102] = "LOWER_F";
  CharCodes2[CharCodes2["LOWER_X"] = 120] = "LOWER_X";
  CharCodes2[CharCodes2["LOWER_Z"] = 122] = "LOWER_Z";
  CharCodes2[CharCodes2["UPPER_A"] = 65] = "UPPER_A";
  CharCodes2[CharCodes2["UPPER_F"] = 70] = "UPPER_F";
  CharCodes2[CharCodes2["UPPER_Z"] = 90] = "UPPER_Z";
})(CharCodes || (CharCodes = {}));
var TO_LOWER_BIT = 32;
var BinTrieFlags;
(function(BinTrieFlags2) {
  BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
  BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH";
  BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE";
})(BinTrieFlags || (BinTrieFlags = {}));
function isNumber2(code5) {
  return code5 >= CharCodes.ZERO && code5 <= CharCodes.NINE;
}
function isHexadecimalCharacter(code5) {
  return code5 >= CharCodes.UPPER_A && code5 <= CharCodes.UPPER_F || code5 >= CharCodes.LOWER_A && code5 <= CharCodes.LOWER_F;
}
function isAsciiAlphaNumeric(code5) {
  return code5 >= CharCodes.UPPER_A && code5 <= CharCodes.UPPER_Z || code5 >= CharCodes.LOWER_A && code5 <= CharCodes.LOWER_Z || isNumber2(code5);
}
function isEntityInAttributeInvalidEnd(code5) {
  return code5 === CharCodes.EQUALS || isAsciiAlphaNumeric(code5);
}
var EntityDecoderState;
(function(EntityDecoderState2) {
  EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart";
  EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart";
  EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal";
  EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex";
  EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity";
})(EntityDecoderState || (EntityDecoderState = {}));
var DecodingMode;
(function(DecodingMode2) {
  DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy";
  DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict";
  DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute";
})(DecodingMode || (DecodingMode = {}));
var EntityDecoder = class {
  constructor(decodeTree, emitCodePoint, errors2) {
    this.decodeTree = decodeTree;
    this.emitCodePoint = emitCodePoint;
    this.errors = errors2;
    this.state = EntityDecoderState.EntityStart;
    this.consumed = 1;
    this.result = 0;
    this.treeIndex = 0;
    this.excess = 1;
    this.decodeMode = DecodingMode.Strict;
  }
  /** Resets the instance to make it reusable. */
  startEntity(decodeMode) {
    this.decodeMode = decodeMode;
    this.state = EntityDecoderState.EntityStart;
    this.result = 0;
    this.treeIndex = 0;
    this.excess = 1;
    this.consumed = 1;
  }
  /**
   * Write an entity to the decoder. This can be called multiple times with partial entities.
   * If the entity is incomplete, the decoder will return -1.
   *
   * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the
   * entity is incomplete, and resume when the next string is written.
   *
   * @param input The string containing the entity (or a continuation of the entity).
   * @param offset The offset at which the entity begins. Should be 0 if this is not the first call.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  write(input2, offset4) {
    switch (this.state) {
      case EntityDecoderState.EntityStart: {
        if (input2.charCodeAt(offset4) === CharCodes.NUM) {
          this.state = EntityDecoderState.NumericStart;
          this.consumed += 1;
          return this.stateNumericStart(input2, offset4 + 1);
        }
        this.state = EntityDecoderState.NamedEntity;
        return this.stateNamedEntity(input2, offset4);
      }
      case EntityDecoderState.NumericStart: {
        return this.stateNumericStart(input2, offset4);
      }
      case EntityDecoderState.NumericDecimal: {
        return this.stateNumericDecimal(input2, offset4);
      }
      case EntityDecoderState.NumericHex: {
        return this.stateNumericHex(input2, offset4);
      }
      case EntityDecoderState.NamedEntity: {
        return this.stateNamedEntity(input2, offset4);
      }
    }
  }
  /**
   * Switches between the numeric decimal and hexadecimal states.
   *
   * Equivalent to the `Numeric character reference state` in the HTML spec.
   *
   * @param input The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericStart(input2, offset4) {
    if (offset4 >= input2.length) {
      return -1;
    }
    if ((input2.charCodeAt(offset4) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
      this.state = EntityDecoderState.NumericHex;
      this.consumed += 1;
      return this.stateNumericHex(input2, offset4 + 1);
    }
    this.state = EntityDecoderState.NumericDecimal;
    return this.stateNumericDecimal(input2, offset4);
  }
  addToNumericResult(input2, start, end, base4) {
    if (start !== end) {
      const digitCount = end - start;
      this.result = this.result * Math.pow(base4, digitCount) + Number.parseInt(input2.substr(start, digitCount), base4);
      this.consumed += digitCount;
    }
  }
  /**
   * Parses a hexadecimal numeric entity.
   *
   * Equivalent to the `Hexademical character reference state` in the HTML spec.
   *
   * @param input The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericHex(input2, offset4) {
    const startIndex = offset4;
    while (offset4 < input2.length) {
      const char = input2.charCodeAt(offset4);
      if (isNumber2(char) || isHexadecimalCharacter(char)) {
        offset4 += 1;
      } else {
        this.addToNumericResult(input2, startIndex, offset4, 16);
        return this.emitNumericEntity(char, 3);
      }
    }
    this.addToNumericResult(input2, startIndex, offset4, 16);
    return -1;
  }
  /**
   * Parses a decimal numeric entity.
   *
   * Equivalent to the `Decimal character reference state` in the HTML spec.
   *
   * @param input The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNumericDecimal(input2, offset4) {
    const startIndex = offset4;
    while (offset4 < input2.length) {
      const char = input2.charCodeAt(offset4);
      if (isNumber2(char)) {
        offset4 += 1;
      } else {
        this.addToNumericResult(input2, startIndex, offset4, 10);
        return this.emitNumericEntity(char, 2);
      }
    }
    this.addToNumericResult(input2, startIndex, offset4, 10);
    return -1;
  }
  /**
   * Validate and emit a numeric entity.
   *
   * Implements the logic from the `Hexademical character reference start
   * state` and `Numeric character reference end state` in the HTML spec.
   *
   * @param lastCp The last code point of the entity. Used to see if the
   *               entity was terminated with a semicolon.
   * @param expectedLength The minimum number of characters that should be
   *                       consumed. Used to validate that at least one digit
   *                       was consumed.
   * @returns The number of characters that were consumed.
   */
  emitNumericEntity(lastCp, expectedLength) {
    var _a2;
    if (this.consumed <= expectedLength) {
      (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
      return 0;
    }
    if (lastCp === CharCodes.SEMI) {
      this.consumed += 1;
    } else if (this.decodeMode === DecodingMode.Strict) {
      return 0;
    }
    this.emitCodePoint(replaceCodePoint(this.result), this.consumed);
    if (this.errors) {
      if (lastCp !== CharCodes.SEMI) {
        this.errors.missingSemicolonAfterCharacterReference();
      }
      this.errors.validateNumericCharacterReference(this.result);
    }
    return this.consumed;
  }
  /**
   * Parses a named entity.
   *
   * Equivalent to the `Named character reference state` in the HTML spec.
   *
   * @param input The string containing the entity (or a continuation of the entity).
   * @param offset The current offset.
   * @returns The number of characters that were consumed, or -1 if the entity is incomplete.
   */
  stateNamedEntity(input2, offset4) {
    const { decodeTree } = this;
    let current = decodeTree[this.treeIndex];
    let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
    for (; offset4 < input2.length; offset4++, this.excess++) {
      const char = input2.charCodeAt(offset4);
      this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char);
      if (this.treeIndex < 0) {
        return this.result === 0 || // If we are parsing an attribute
        this.decodeMode === DecodingMode.Attribute && // We shouldn't have consumed any characters after the entity,
        (valueLength === 0 || // And there should be no invalid characters.
        isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
      }
      current = decodeTree[this.treeIndex];
      valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14;
      if (valueLength !== 0) {
        if (char === CharCodes.SEMI) {
          return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess);
        }
        if (this.decodeMode !== DecodingMode.Strict) {
          this.result = this.treeIndex;
          this.consumed += this.excess;
          this.excess = 0;
        }
      }
    }
    return -1;
  }
  /**
   * Emit a named entity that was not terminated with a semicolon.
   *
   * @returns The number of characters consumed.
   */
  emitNotTerminatedNamedEntity() {
    var _a2;
    const { result, decodeTree } = this;
    const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14;
    this.emitNamedEntityData(result, valueLength, this.consumed);
    (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.missingSemicolonAfterCharacterReference();
    return this.consumed;
  }
  /**
   * Emit a named entity.
   *
   * @param result The index of the entity in the decode tree.
   * @param valueLength The number of bytes in the entity.
   * @param consumed The number of characters consumed.
   *
   * @returns The number of characters consumed.
   */
  emitNamedEntityData(result, valueLength, consumed) {
    const { decodeTree } = this;
    this.emitCodePoint(valueLength === 1 ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH : decodeTree[result + 1], consumed);
    if (valueLength === 3) {
      this.emitCodePoint(decodeTree[result + 2], consumed);
    }
    return consumed;
  }
  /**
   * Signal to the parser that the end of the input was reached.
   *
   * Remaining data will be emitted and relevant errors will be produced.
   *
   * @returns The number of characters consumed.
   */
  end() {
    var _a2;
    switch (this.state) {
      case EntityDecoderState.NamedEntity: {
        return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
      }
      // Otherwise, emit a numeric entity if we have one.
      case EntityDecoderState.NumericDecimal: {
        return this.emitNumericEntity(0, 2);
      }
      case EntityDecoderState.NumericHex: {
        return this.emitNumericEntity(0, 3);
      }
      case EntityDecoderState.NumericStart: {
        (_a2 = this.errors) === null || _a2 === void 0 ? void 0 : _a2.absenceOfDigitsInNumericCharacterReference(this.consumed);
        return 0;
      }
      case EntityDecoderState.EntityStart: {
        return 0;
      }
    }
  }
};
function getDecoder(decodeTree) {
  let returnValue = "";
  const decoder = new EntityDecoder(decodeTree, (data) => returnValue += fromCodePoint2(data));
  return function decodeWithTrie(input2, decodeMode) {
    let lastIndex = 0;
    let offset4 = 0;
    while ((offset4 = input2.indexOf("&", offset4)) >= 0) {
      returnValue += input2.slice(lastIndex, offset4);
      decoder.startEntity(decodeMode);
      const length2 = decoder.write(
        input2,
        // Skip the "&"
        offset4 + 1
      );
      if (length2 < 0) {
        lastIndex = offset4 + decoder.end();
        break;
      }
      lastIndex = offset4 + length2;
      offset4 = length2 === 0 ? lastIndex + 1 : lastIndex;
    }
    const result = returnValue + input2.slice(lastIndex);
    returnValue = "";
    return result;
  };
}
function determineBranch(decodeTree, current, nodeIndex, char) {
  const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
  const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
  if (branchCount === 0) {
    return jumpOffset !== 0 && char === jumpOffset ? nodeIndex : -1;
  }
  if (jumpOffset) {
    const value = char - jumpOffset;
    return value < 0 || value >= branchCount ? -1 : decodeTree[nodeIndex + value] - 1;
  }
  let lo3 = nodeIndex;
  let hi2 = lo3 + branchCount - 1;
  while (lo3 <= hi2) {
    const mid = lo3 + hi2 >>> 1;
    const midValue = decodeTree[mid];
    if (midValue < char) {
      lo3 = mid + 1;
    } else if (midValue > char) {
      hi2 = mid - 1;
    } else {
      return decodeTree[mid + branchCount];
    }
  }
  return -1;
}
var htmlDecoder = getDecoder(htmlDecodeTree);
var xmlDecoder = getDecoder(xmlDecodeTree);

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/common/html.js
var html_exports = {};
__export(html_exports, {
  ATTRS: () => ATTRS,
  DOCUMENT_MODE: () => DOCUMENT_MODE,
  NS: () => NS,
  NUMBERED_HEADERS: () => NUMBERED_HEADERS,
  SPECIAL_ELEMENTS: () => SPECIAL_ELEMENTS,
  TAG_ID: () => TAG_ID,
  TAG_NAMES: () => TAG_NAMES,
  getTagID: () => getTagID,
  hasUnescapedText: () => hasUnescapedText
});
var NS;
(function(NS2) {
  NS2["HTML"] = "http://www.w3.org/1999/xhtml";
  NS2["MATHML"] = "http://www.w3.org/1998/Math/MathML";
  NS2["SVG"] = "http://www.w3.org/2000/svg";
  NS2["XLINK"] = "http://www.w3.org/1999/xlink";
  NS2["XML"] = "http://www.w3.org/XML/1998/namespace";
  NS2["XMLNS"] = "http://www.w3.org/2000/xmlns/";
})(NS || (NS = {}));
var ATTRS;
(function(ATTRS2) {
  ATTRS2["TYPE"] = "type";
  ATTRS2["ACTION"] = "action";
  ATTRS2["ENCODING"] = "encoding";
  ATTRS2["PROMPT"] = "prompt";
  ATTRS2["NAME"] = "name";
  ATTRS2["COLOR"] = "color";
  ATTRS2["FACE"] = "face";
  ATTRS2["SIZE"] = "size";
})(ATTRS || (ATTRS = {}));
var DOCUMENT_MODE;
(function(DOCUMENT_MODE2) {
  DOCUMENT_MODE2["NO_QUIRKS"] = "no-quirks";
  DOCUMENT_MODE2["QUIRKS"] = "quirks";
  DOCUMENT_MODE2["LIMITED_QUIRKS"] = "limited-quirks";
})(DOCUMENT_MODE || (DOCUMENT_MODE = {}));
var TAG_NAMES;
(function(TAG_NAMES2) {
  TAG_NAMES2["A"] = "a";
  TAG_NAMES2["ADDRESS"] = "address";
  TAG_NAMES2["ANNOTATION_XML"] = "annotation-xml";
  TAG_NAMES2["APPLET"] = "applet";
  TAG_NAMES2["AREA"] = "area";
  TAG_NAMES2["ARTICLE"] = "article";
  TAG_NAMES2["ASIDE"] = "aside";
  TAG_NAMES2["B"] = "b";
  TAG_NAMES2["BASE"] = "base";
  TAG_NAMES2["BASEFONT"] = "basefont";
  TAG_NAMES2["BGSOUND"] = "bgsound";
  TAG_NAMES2["BIG"] = "big";
  TAG_NAMES2["BLOCKQUOTE"] = "blockquote";
  TAG_NAMES2["BODY"] = "body";
  TAG_NAMES2["BR"] = "br";
  TAG_NAMES2["BUTTON"] = "button";
  TAG_NAMES2["CAPTION"] = "caption";
  TAG_NAMES2["CENTER"] = "center";
  TAG_NAMES2["CODE"] = "code";
  TAG_NAMES2["COL"] = "col";
  TAG_NAMES2["COLGROUP"] = "colgroup";
  TAG_NAMES2["DD"] = "dd";
  TAG_NAMES2["DESC"] = "desc";
  TAG_NAMES2["DETAILS"] = "details";
  TAG_NAMES2["DIALOG"] = "dialog";
  TAG_NAMES2["DIR"] = "dir";
  TAG_NAMES2["DIV"] = "div";
  TAG_NAMES2["DL"] = "dl";
  TAG_NAMES2["DT"] = "dt";
  TAG_NAMES2["EM"] = "em";
  TAG_NAMES2["EMBED"] = "embed";
  TAG_NAMES2["FIELDSET"] = "fieldset";
  TAG_NAMES2["FIGCAPTION"] = "figcaption";
  TAG_NAMES2["FIGURE"] = "figure";
  TAG_NAMES2["FONT"] = "font";
  TAG_NAMES2["FOOTER"] = "footer";
  TAG_NAMES2["FOREIGN_OBJECT"] = "foreignObject";
  TAG_NAMES2["FORM"] = "form";
  TAG_NAMES2["FRAME"] = "frame";
  TAG_NAMES2["FRAMESET"] = "frameset";
  TAG_NAMES2["H1"] = "h1";
  TAG_NAMES2["H2"] = "h2";
  TAG_NAMES2["H3"] = "h3";
  TAG_NAMES2["H4"] = "h4";
  TAG_NAMES2["H5"] = "h5";
  TAG_NAMES2["H6"] = "h6";
  TAG_NAMES2["HEAD"] = "head";
  TAG_NAMES2["HEADER"] = "header";
  TAG_NAMES2["HGROUP"] = "hgroup";
  TAG_NAMES2["HR"] = "hr";
  TAG_NAMES2["HTML"] = "html";
  TAG_NAMES2["I"] = "i";
  TAG_NAMES2["IMG"] = "img";
  TAG_NAMES2["IMAGE"] = "image";
  TAG_NAMES2["INPUT"] = "input";
  TAG_NAMES2["IFRAME"] = "iframe";
  TAG_NAMES2["KEYGEN"] = "keygen";
  TAG_NAMES2["LABEL"] = "label";
  TAG_NAMES2["LI"] = "li";
  TAG_NAMES2["LINK"] = "link";
  TAG_NAMES2["LISTING"] = "listing";
  TAG_NAMES2["MAIN"] = "main";
  TAG_NAMES2["MALIGNMARK"] = "malignmark";
  TAG_NAMES2["MARQUEE"] = "marquee";
  TAG_NAMES2["MATH"] = "math";
  TAG_NAMES2["MENU"] = "menu";
  TAG_NAMES2["META"] = "meta";
  TAG_NAMES2["MGLYPH"] = "mglyph";
  TAG_NAMES2["MI"] = "mi";
  TAG_NAMES2["MO"] = "mo";
  TAG_NAMES2["MN"] = "mn";
  TAG_NAMES2["MS"] = "ms";
  TAG_NAMES2["MTEXT"] = "mtext";
  TAG_NAMES2["NAV"] = "nav";
  TAG_NAMES2["NOBR"] = "nobr";
  TAG_NAMES2["NOFRAMES"] = "noframes";
  TAG_NAMES2["NOEMBED"] = "noembed";
  TAG_NAMES2["NOSCRIPT"] = "noscript";
  TAG_NAMES2["OBJECT"] = "object";
  TAG_NAMES2["OL"] = "ol";
  TAG_NAMES2["OPTGROUP"] = "optgroup";
  TAG_NAMES2["OPTION"] = "option";
  TAG_NAMES2["P"] = "p";
  TAG_NAMES2["PARAM"] = "param";
  TAG_NAMES2["PLAINTEXT"] = "plaintext";
  TAG_NAMES2["PRE"] = "pre";
  TAG_NAMES2["RB"] = "rb";
  TAG_NAMES2["RP"] = "rp";
  TAG_NAMES2["RT"] = "rt";
  TAG_NAMES2["RTC"] = "rtc";
  TAG_NAMES2["RUBY"] = "ruby";
  TAG_NAMES2["S"] = "s";
  TAG_NAMES2["SCRIPT"] = "script";
  TAG_NAMES2["SEARCH"] = "search";
  TAG_NAMES2["SECTION"] = "section";
  TAG_NAMES2["SELECT"] = "select";
  TAG_NAMES2["SOURCE"] = "source";
  TAG_NAMES2["SMALL"] = "small";
  TAG_NAMES2["SPAN"] = "span";
  TAG_NAMES2["STRIKE"] = "strike";
  TAG_NAMES2["STRONG"] = "strong";
  TAG_NAMES2["STYLE"] = "style";
  TAG_NAMES2["SUB"] = "sub";
  TAG_NAMES2["SUMMARY"] = "summary";
  TAG_NAMES2["SUP"] = "sup";
  TAG_NAMES2["TABLE"] = "table";
  TAG_NAMES2["TBODY"] = "tbody";
  TAG_NAMES2["TEMPLATE"] = "template";
  TAG_NAMES2["TEXTAREA"] = "textarea";
  TAG_NAMES2["TFOOT"] = "tfoot";
  TAG_NAMES2["TD"] = "td";
  TAG_NAMES2["TH"] = "th";
  TAG_NAMES2["THEAD"] = "thead";
  TAG_NAMES2["TITLE"] = "title";
  TAG_NAMES2["TR"] = "tr";
  TAG_NAMES2["TRACK"] = "track";
  TAG_NAMES2["TT"] = "tt";
  TAG_NAMES2["U"] = "u";
  TAG_NAMES2["UL"] = "ul";
  TAG_NAMES2["SVG"] = "svg";
  TAG_NAMES2["VAR"] = "var";
  TAG_NAMES2["WBR"] = "wbr";
  TAG_NAMES2["XMP"] = "xmp";
})(TAG_NAMES || (TAG_NAMES = {}));
var TAG_ID;
(function(TAG_ID2) {
  TAG_ID2[TAG_ID2["UNKNOWN"] = 0] = "UNKNOWN";
  TAG_ID2[TAG_ID2["A"] = 1] = "A";
  TAG_ID2[TAG_ID2["ADDRESS"] = 2] = "ADDRESS";
  TAG_ID2[TAG_ID2["ANNOTATION_XML"] = 3] = "ANNOTATION_XML";
  TAG_ID2[TAG_ID2["APPLET"] = 4] = "APPLET";
  TAG_ID2[TAG_ID2["AREA"] = 5] = "AREA";
  TAG_ID2[TAG_ID2["ARTICLE"] = 6] = "ARTICLE";
  TAG_ID2[TAG_ID2["ASIDE"] = 7] = "ASIDE";
  TAG_ID2[TAG_ID2["B"] = 8] = "B";
  TAG_ID2[TAG_ID2["BASE"] = 9] = "BASE";
  TAG_ID2[TAG_ID2["BASEFONT"] = 10] = "BASEFONT";
  TAG_ID2[TAG_ID2["BGSOUND"] = 11] = "BGSOUND";
  TAG_ID2[TAG_ID2["BIG"] = 12] = "BIG";
  TAG_ID2[TAG_ID2["BLOCKQUOTE"] = 13] = "BLOCKQUOTE";
  TAG_ID2[TAG_ID2["BODY"] = 14] = "BODY";
  TAG_ID2[TAG_ID2["BR"] = 15] = "BR";
  TAG_ID2[TAG_ID2["BUTTON"] = 16] = "BUTTON";
  TAG_ID2[TAG_ID2["CAPTION"] = 17] = "CAPTION";
  TAG_ID2[TAG_ID2["CENTER"] = 18] = "CENTER";
  TAG_ID2[TAG_ID2["CODE"] = 19] = "CODE";
  TAG_ID2[TAG_ID2["COL"] = 20] = "COL";
  TAG_ID2[TAG_ID2["COLGROUP"] = 21] = "COLGROUP";
  TAG_ID2[TAG_ID2["DD"] = 22] = "DD";
  TAG_ID2[TAG_ID2["DESC"] = 23] = "DESC";
  TAG_ID2[TAG_ID2["DETAILS"] = 24] = "DETAILS";
  TAG_ID2[TAG_ID2["DIALOG"] = 25] = "DIALOG";
  TAG_ID2[TAG_ID2["DIR"] = 26] = "DIR";
  TAG_ID2[TAG_ID2["DIV"] = 27] = "DIV";
  TAG_ID2[TAG_ID2["DL"] = 28] = "DL";
  TAG_ID2[TAG_ID2["DT"] = 29] = "DT";
  TAG_ID2[TAG_ID2["EM"] = 30] = "EM";
  TAG_ID2[TAG_ID2["EMBED"] = 31] = "EMBED";
  TAG_ID2[TAG_ID2["FIELDSET"] = 32] = "FIELDSET";
  TAG_ID2[TAG_ID2["FIGCAPTION"] = 33] = "FIGCAPTION";
  TAG_ID2[TAG_ID2["FIGURE"] = 34] = "FIGURE";
  TAG_ID2[TAG_ID2["FONT"] = 35] = "FONT";
  TAG_ID2[TAG_ID2["FOOTER"] = 36] = "FOOTER";
  TAG_ID2[TAG_ID2["FOREIGN_OBJECT"] = 37] = "FOREIGN_OBJECT";
  TAG_ID2[TAG_ID2["FORM"] = 38] = "FORM";
  TAG_ID2[TAG_ID2["FRAME"] = 39] = "FRAME";
  TAG_ID2[TAG_ID2["FRAMESET"] = 40] = "FRAMESET";
  TAG_ID2[TAG_ID2["H1"] = 41] = "H1";
  TAG_ID2[TAG_ID2["H2"] = 42] = "H2";
  TAG_ID2[TAG_ID2["H3"] = 43] = "H3";
  TAG_ID2[TAG_ID2["H4"] = 44] = "H4";
  TAG_ID2[TAG_ID2["H5"] = 45] = "H5";
  TAG_ID2[TAG_ID2["H6"] = 46] = "H6";
  TAG_ID2[TAG_ID2["HEAD"] = 47] = "HEAD";
  TAG_ID2[TAG_ID2["HEADER"] = 48] = "HEADER";
  TAG_ID2[TAG_ID2["HGROUP"] = 49] = "HGROUP";
  TAG_ID2[TAG_ID2["HR"] = 50] = "HR";
  TAG_ID2[TAG_ID2["HTML"] = 51] = "HTML";
  TAG_ID2[TAG_ID2["I"] = 52] = "I";
  TAG_ID2[TAG_ID2["IMG"] = 53] = "IMG";
  TAG_ID2[TAG_ID2["IMAGE"] = 54] = "IMAGE";
  TAG_ID2[TAG_ID2["INPUT"] = 55] = "INPUT";
  TAG_ID2[TAG_ID2["IFRAME"] = 56] = "IFRAME";
  TAG_ID2[TAG_ID2["KEYGEN"] = 57] = "KEYGEN";
  TAG_ID2[TAG_ID2["LABEL"] = 58] = "LABEL";
  TAG_ID2[TAG_ID2["LI"] = 59] = "LI";
  TAG_ID2[TAG_ID2["LINK"] = 60] = "LINK";
  TAG_ID2[TAG_ID2["LISTING"] = 61] = "LISTING";
  TAG_ID2[TAG_ID2["MAIN"] = 62] = "MAIN";
  TAG_ID2[TAG_ID2["MALIGNMARK"] = 63] = "MALIGNMARK";
  TAG_ID2[TAG_ID2["MARQUEE"] = 64] = "MARQUEE";
  TAG_ID2[TAG_ID2["MATH"] = 65] = "MATH";
  TAG_ID2[TAG_ID2["MENU"] = 66] = "MENU";
  TAG_ID2[TAG_ID2["META"] = 67] = "META";
  TAG_ID2[TAG_ID2["MGLYPH"] = 68] = "MGLYPH";
  TAG_ID2[TAG_ID2["MI"] = 69] = "MI";
  TAG_ID2[TAG_ID2["MO"] = 70] = "MO";
  TAG_ID2[TAG_ID2["MN"] = 71] = "MN";
  TAG_ID2[TAG_ID2["MS"] = 72] = "MS";
  TAG_ID2[TAG_ID2["MTEXT"] = 73] = "MTEXT";
  TAG_ID2[TAG_ID2["NAV"] = 74] = "NAV";
  TAG_ID2[TAG_ID2["NOBR"] = 75] = "NOBR";
  TAG_ID2[TAG_ID2["NOFRAMES"] = 76] = "NOFRAMES";
  TAG_ID2[TAG_ID2["NOEMBED"] = 77] = "NOEMBED";
  TAG_ID2[TAG_ID2["NOSCRIPT"] = 78] = "NOSCRIPT";
  TAG_ID2[TAG_ID2["OBJECT"] = 79] = "OBJECT";
  TAG_ID2[TAG_ID2["OL"] = 80] = "OL";
  TAG_ID2[TAG_ID2["OPTGROUP"] = 81] = "OPTGROUP";
  TAG_ID2[TAG_ID2["OPTION"] = 82] = "OPTION";
  TAG_ID2[TAG_ID2["P"] = 83] = "P";
  TAG_ID2[TAG_ID2["PARAM"] = 84] = "PARAM";
  TAG_ID2[TAG_ID2["PLAINTEXT"] = 85] = "PLAINTEXT";
  TAG_ID2[TAG_ID2["PRE"] = 86] = "PRE";
  TAG_ID2[TAG_ID2["RB"] = 87] = "RB";
  TAG_ID2[TAG_ID2["RP"] = 88] = "RP";
  TAG_ID2[TAG_ID2["RT"] = 89] = "RT";
  TAG_ID2[TAG_ID2["RTC"] = 90] = "RTC";
  TAG_ID2[TAG_ID2["RUBY"] = 91] = "RUBY";
  TAG_ID2[TAG_ID2["S"] = 92] = "S";
  TAG_ID2[TAG_ID2["SCRIPT"] = 93] = "SCRIPT";
  TAG_ID2[TAG_ID2["SEARCH"] = 94] = "SEARCH";
  TAG_ID2[TAG_ID2["SECTION"] = 95] = "SECTION";
  TAG_ID2[TAG_ID2["SELECT"] = 96] = "SELECT";
  TAG_ID2[TAG_ID2["SOURCE"] = 97] = "SOURCE";
  TAG_ID2[TAG_ID2["SMALL"] = 98] = "SMALL";
  TAG_ID2[TAG_ID2["SPAN"] = 99] = "SPAN";
  TAG_ID2[TAG_ID2["STRIKE"] = 100] = "STRIKE";
  TAG_ID2[TAG_ID2["STRONG"] = 101] = "STRONG";
  TAG_ID2[TAG_ID2["STYLE"] = 102] = "STYLE";
  TAG_ID2[TAG_ID2["SUB"] = 103] = "SUB";
  TAG_ID2[TAG_ID2["SUMMARY"] = 104] = "SUMMARY";
  TAG_ID2[TAG_ID2["SUP"] = 105] = "SUP";
  TAG_ID2[TAG_ID2["TABLE"] = 106] = "TABLE";
  TAG_ID2[TAG_ID2["TBODY"] = 107] = "TBODY";
  TAG_ID2[TAG_ID2["TEMPLATE"] = 108] = "TEMPLATE";
  TAG_ID2[TAG_ID2["TEXTAREA"] = 109] = "TEXTAREA";
  TAG_ID2[TAG_ID2["TFOOT"] = 110] = "TFOOT";
  TAG_ID2[TAG_ID2["TD"] = 111] = "TD";
  TAG_ID2[TAG_ID2["TH"] = 112] = "TH";
  TAG_ID2[TAG_ID2["THEAD"] = 113] = "THEAD";
  TAG_ID2[TAG_ID2["TITLE"] = 114] = "TITLE";
  TAG_ID2[TAG_ID2["TR"] = 115] = "TR";
  TAG_ID2[TAG_ID2["TRACK"] = 116] = "TRACK";
  TAG_ID2[TAG_ID2["TT"] = 117] = "TT";
  TAG_ID2[TAG_ID2["U"] = 118] = "U";
  TAG_ID2[TAG_ID2["UL"] = 119] = "UL";
  TAG_ID2[TAG_ID2["SVG"] = 120] = "SVG";
  TAG_ID2[TAG_ID2["VAR"] = 121] = "VAR";
  TAG_ID2[TAG_ID2["WBR"] = 122] = "WBR";
  TAG_ID2[TAG_ID2["XMP"] = 123] = "XMP";
})(TAG_ID || (TAG_ID = {}));
var TAG_NAME_TO_ID = /* @__PURE__ */ new Map([
  [TAG_NAMES.A, TAG_ID.A],
  [TAG_NAMES.ADDRESS, TAG_ID.ADDRESS],
  [TAG_NAMES.ANNOTATION_XML, TAG_ID.ANNOTATION_XML],
  [TAG_NAMES.APPLET, TAG_ID.APPLET],
  [TAG_NAMES.AREA, TAG_ID.AREA],
  [TAG_NAMES.ARTICLE, TAG_ID.ARTICLE],
  [TAG_NAMES.ASIDE, TAG_ID.ASIDE],
  [TAG_NAMES.B, TAG_ID.B],
  [TAG_NAMES.BASE, TAG_ID.BASE],
  [TAG_NAMES.BASEFONT, TAG_ID.BASEFONT],
  [TAG_NAMES.BGSOUND, TAG_ID.BGSOUND],
  [TAG_NAMES.BIG, TAG_ID.BIG],
  [TAG_NAMES.BLOCKQUOTE, TAG_ID.BLOCKQUOTE],
  [TAG_NAMES.BODY, TAG_ID.BODY],
  [TAG_NAMES.BR, TAG_ID.BR],
  [TAG_NAMES.BUTTON, TAG_ID.BUTTON],
  [TAG_NAMES.CAPTION, TAG_ID.CAPTION],
  [TAG_NAMES.CENTER, TAG_ID.CENTER],
  [TAG_NAMES.CODE, TAG_ID.CODE],
  [TAG_NAMES.COL, TAG_ID.COL],
  [TAG_NAMES.COLGROUP, TAG_ID.COLGROUP],
  [TAG_NAMES.DD, TAG_ID.DD],
  [TAG_NAMES.DESC, TAG_ID.DESC],
  [TAG_NAMES.DETAILS, TAG_ID.DETAILS],
  [TAG_NAMES.DIALOG, TAG_ID.DIALOG],
  [TAG_NAMES.DIR, TAG_ID.DIR],
  [TAG_NAMES.DIV, TAG_ID.DIV],
  [TAG_NAMES.DL, TAG_ID.DL],
  [TAG_NAMES.DT, TAG_ID.DT],
  [TAG_NAMES.EM, TAG_ID.EM],
  [TAG_NAMES.EMBED, TAG_ID.EMBED],
  [TAG_NAMES.FIELDSET, TAG_ID.FIELDSET],
  [TAG_NAMES.FIGCAPTION, TAG_ID.FIGCAPTION],
  [TAG_NAMES.FIGURE, TAG_ID.FIGURE],
  [TAG_NAMES.FONT, TAG_ID.FONT],
  [TAG_NAMES.FOOTER, TAG_ID.FOOTER],
  [TAG_NAMES.FOREIGN_OBJECT, TAG_ID.FOREIGN_OBJECT],
  [TAG_NAMES.FORM, TAG_ID.FORM],
  [TAG_NAMES.FRAME, TAG_ID.FRAME],
  [TAG_NAMES.FRAMESET, TAG_ID.FRAMESET],
  [TAG_NAMES.H1, TAG_ID.H1],
  [TAG_NAMES.H2, TAG_ID.H2],
  [TAG_NAMES.H3, TAG_ID.H3],
  [TAG_NAMES.H4, TAG_ID.H4],
  [TAG_NAMES.H5, TAG_ID.H5],
  [TAG_NAMES.H6, TAG_ID.H6],
  [TAG_NAMES.HEAD, TAG_ID.HEAD],
  [TAG_NAMES.HEADER, TAG_ID.HEADER],
  [TAG_NAMES.HGROUP, TAG_ID.HGROUP],
  [TAG_NAMES.HR, TAG_ID.HR],
  [TAG_NAMES.HTML, TAG_ID.HTML],
  [TAG_NAMES.I, TAG_ID.I],
  [TAG_NAMES.IMG, TAG_ID.IMG],
  [TAG_NAMES.IMAGE, TAG_ID.IMAGE],
  [TAG_NAMES.INPUT, TAG_ID.INPUT],
  [TAG_NAMES.IFRAME, TAG_ID.IFRAME],
  [TAG_NAMES.KEYGEN, TAG_ID.KEYGEN],
  [TAG_NAMES.LABEL, TAG_ID.LABEL],
  [TAG_NAMES.LI, TAG_ID.LI],
  [TAG_NAMES.LINK, TAG_ID.LINK],
  [TAG_NAMES.LISTING, TAG_ID.LISTING],
  [TAG_NAMES.MAIN, TAG_ID.MAIN],
  [TAG_NAMES.MALIGNMARK, TAG_ID.MALIGNMARK],
  [TAG_NAMES.MARQUEE, TAG_ID.MARQUEE],
  [TAG_NAMES.MATH, TAG_ID.MATH],
  [TAG_NAMES.MENU, TAG_ID.MENU],
  [TAG_NAMES.META, TAG_ID.META],
  [TAG_NAMES.MGLYPH, TAG_ID.MGLYPH],
  [TAG_NAMES.MI, TAG_ID.MI],
  [TAG_NAMES.MO, TAG_ID.MO],
  [TAG_NAMES.MN, TAG_ID.MN],
  [TAG_NAMES.MS, TAG_ID.MS],
  [TAG_NAMES.MTEXT, TAG_ID.MTEXT],
  [TAG_NAMES.NAV, TAG_ID.NAV],
  [TAG_NAMES.NOBR, TAG_ID.NOBR],
  [TAG_NAMES.NOFRAMES, TAG_ID.NOFRAMES],
  [TAG_NAMES.NOEMBED, TAG_ID.NOEMBED],
  [TAG_NAMES.NOSCRIPT, TAG_ID.NOSCRIPT],
  [TAG_NAMES.OBJECT, TAG_ID.OBJECT],
  [TAG_NAMES.OL, TAG_ID.OL],
  [TAG_NAMES.OPTGROUP, TAG_ID.OPTGROUP],
  [TAG_NAMES.OPTION, TAG_ID.OPTION],
  [TAG_NAMES.P, TAG_ID.P],
  [TAG_NAMES.PARAM, TAG_ID.PARAM],
  [TAG_NAMES.PLAINTEXT, TAG_ID.PLAINTEXT],
  [TAG_NAMES.PRE, TAG_ID.PRE],
  [TAG_NAMES.RB, TAG_ID.RB],
  [TAG_NAMES.RP, TAG_ID.RP],
  [TAG_NAMES.RT, TAG_ID.RT],
  [TAG_NAMES.RTC, TAG_ID.RTC],
  [TAG_NAMES.RUBY, TAG_ID.RUBY],
  [TAG_NAMES.S, TAG_ID.S],
  [TAG_NAMES.SCRIPT, TAG_ID.SCRIPT],
  [TAG_NAMES.SEARCH, TAG_ID.SEARCH],
  [TAG_NAMES.SECTION, TAG_ID.SECTION],
  [TAG_NAMES.SELECT, TAG_ID.SELECT],
  [TAG_NAMES.SOURCE, TAG_ID.SOURCE],
  [TAG_NAMES.SMALL, TAG_ID.SMALL],
  [TAG_NAMES.SPAN, TAG_ID.SPAN],
  [TAG_NAMES.STRIKE, TAG_ID.STRIKE],
  [TAG_NAMES.STRONG, TAG_ID.STRONG],
  [TAG_NAMES.STYLE, TAG_ID.STYLE],
  [TAG_NAMES.SUB, TAG_ID.SUB],
  [TAG_NAMES.SUMMARY, TAG_ID.SUMMARY],
  [TAG_NAMES.SUP, TAG_ID.SUP],
  [TAG_NAMES.TABLE, TAG_ID.TABLE],
  [TAG_NAMES.TBODY, TAG_ID.TBODY],
  [TAG_NAMES.TEMPLATE, TAG_ID.TEMPLATE],
  [TAG_NAMES.TEXTAREA, TAG_ID.TEXTAREA],
  [TAG_NAMES.TFOOT, TAG_ID.TFOOT],
  [TAG_NAMES.TD, TAG_ID.TD],
  [TAG_NAMES.TH, TAG_ID.TH],
  [TAG_NAMES.THEAD, TAG_ID.THEAD],
  [TAG_NAMES.TITLE, TAG_ID.TITLE],
  [TAG_NAMES.TR, TAG_ID.TR],
  [TAG_NAMES.TRACK, TAG_ID.TRACK],
  [TAG_NAMES.TT, TAG_ID.TT],
  [TAG_NAMES.U, TAG_ID.U],
  [TAG_NAMES.UL, TAG_ID.UL],
  [TAG_NAMES.SVG, TAG_ID.SVG],
  [TAG_NAMES.VAR, TAG_ID.VAR],
  [TAG_NAMES.WBR, TAG_ID.WBR],
  [TAG_NAMES.XMP, TAG_ID.XMP]
]);
function getTagID(tagName) {
  var _a2;
  return (_a2 = TAG_NAME_TO_ID.get(tagName)) !== null && _a2 !== void 0 ? _a2 : TAG_ID.UNKNOWN;
}
var $4 = TAG_ID;
var SPECIAL_ELEMENTS = {
  [NS.HTML]: /* @__PURE__ */ new Set([
    $4.ADDRESS,
    $4.APPLET,
    $4.AREA,
    $4.ARTICLE,
    $4.ASIDE,
    $4.BASE,
    $4.BASEFONT,
    $4.BGSOUND,
    $4.BLOCKQUOTE,
    $4.BODY,
    $4.BR,
    $4.BUTTON,
    $4.CAPTION,
    $4.CENTER,
    $4.COL,
    $4.COLGROUP,
    $4.DD,
    $4.DETAILS,
    $4.DIR,
    $4.DIV,
    $4.DL,
    $4.DT,
    $4.EMBED,
    $4.FIELDSET,
    $4.FIGCAPTION,
    $4.FIGURE,
    $4.FOOTER,
    $4.FORM,
    $4.FRAME,
    $4.FRAMESET,
    $4.H1,
    $4.H2,
    $4.H3,
    $4.H4,
    $4.H5,
    $4.H6,
    $4.HEAD,
    $4.HEADER,
    $4.HGROUP,
    $4.HR,
    $4.HTML,
    $4.IFRAME,
    $4.IMG,
    $4.INPUT,
    $4.LI,
    $4.LINK,
    $4.LISTING,
    $4.MAIN,
    $4.MARQUEE,
    $4.MENU,
    $4.META,
    $4.NAV,
    $4.NOEMBED,
    $4.NOFRAMES,
    $4.NOSCRIPT,
    $4.OBJECT,
    $4.OL,
    $4.P,
    $4.PARAM,
    $4.PLAINTEXT,
    $4.PRE,
    $4.SCRIPT,
    $4.SECTION,
    $4.SELECT,
    $4.SOURCE,
    $4.STYLE,
    $4.SUMMARY,
    $4.TABLE,
    $4.TBODY,
    $4.TD,
    $4.TEMPLATE,
    $4.TEXTAREA,
    $4.TFOOT,
    $4.TH,
    $4.THEAD,
    $4.TITLE,
    $4.TR,
    $4.TRACK,
    $4.UL,
    $4.WBR,
    $4.XMP
  ]),
  [NS.MATHML]: /* @__PURE__ */ new Set([$4.MI, $4.MO, $4.MN, $4.MS, $4.MTEXT, $4.ANNOTATION_XML]),
  [NS.SVG]: /* @__PURE__ */ new Set([$4.TITLE, $4.FOREIGN_OBJECT, $4.DESC]),
  [NS.XLINK]: /* @__PURE__ */ new Set(),
  [NS.XML]: /* @__PURE__ */ new Set(),
  [NS.XMLNS]: /* @__PURE__ */ new Set()
};
var NUMBERED_HEADERS = /* @__PURE__ */ new Set([$4.H1, $4.H2, $4.H3, $4.H4, $4.H5, $4.H6]);
var UNESCAPED_TEXT = /* @__PURE__ */ new Set([
  TAG_NAMES.STYLE,
  TAG_NAMES.SCRIPT,
  TAG_NAMES.XMP,
  TAG_NAMES.IFRAME,
  TAG_NAMES.NOEMBED,
  TAG_NAMES.NOFRAMES,
  TAG_NAMES.PLAINTEXT
]);
function hasUnescapedText(tn4, scriptingEnabled) {
  return UNESCAPED_TEXT.has(tn4) || scriptingEnabled && tn4 === TAG_NAMES.NOSCRIPT;
}

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/tokenizer/index.js
var State;
(function(State3) {
  State3[State3["DATA"] = 0] = "DATA";
  State3[State3["RCDATA"] = 1] = "RCDATA";
  State3[State3["RAWTEXT"] = 2] = "RAWTEXT";
  State3[State3["SCRIPT_DATA"] = 3] = "SCRIPT_DATA";
  State3[State3["PLAINTEXT"] = 4] = "PLAINTEXT";
  State3[State3["TAG_OPEN"] = 5] = "TAG_OPEN";
  State3[State3["END_TAG_OPEN"] = 6] = "END_TAG_OPEN";
  State3[State3["TAG_NAME"] = 7] = "TAG_NAME";
  State3[State3["RCDATA_LESS_THAN_SIGN"] = 8] = "RCDATA_LESS_THAN_SIGN";
  State3[State3["RCDATA_END_TAG_OPEN"] = 9] = "RCDATA_END_TAG_OPEN";
  State3[State3["RCDATA_END_TAG_NAME"] = 10] = "RCDATA_END_TAG_NAME";
  State3[State3["RAWTEXT_LESS_THAN_SIGN"] = 11] = "RAWTEXT_LESS_THAN_SIGN";
  State3[State3["RAWTEXT_END_TAG_OPEN"] = 12] = "RAWTEXT_END_TAG_OPEN";
  State3[State3["RAWTEXT_END_TAG_NAME"] = 13] = "RAWTEXT_END_TAG_NAME";
  State3[State3["SCRIPT_DATA_LESS_THAN_SIGN"] = 14] = "SCRIPT_DATA_LESS_THAN_SIGN";
  State3[State3["SCRIPT_DATA_END_TAG_OPEN"] = 15] = "SCRIPT_DATA_END_TAG_OPEN";
  State3[State3["SCRIPT_DATA_END_TAG_NAME"] = 16] = "SCRIPT_DATA_END_TAG_NAME";
  State3[State3["SCRIPT_DATA_ESCAPE_START"] = 17] = "SCRIPT_DATA_ESCAPE_START";
  State3[State3["SCRIPT_DATA_ESCAPE_START_DASH"] = 18] = "SCRIPT_DATA_ESCAPE_START_DASH";
  State3[State3["SCRIPT_DATA_ESCAPED"] = 19] = "SCRIPT_DATA_ESCAPED";
  State3[State3["SCRIPT_DATA_ESCAPED_DASH"] = 20] = "SCRIPT_DATA_ESCAPED_DASH";
  State3[State3["SCRIPT_DATA_ESCAPED_DASH_DASH"] = 21] = "SCRIPT_DATA_ESCAPED_DASH_DASH";
  State3[State3["SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN"] = 22] = "SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN";
  State3[State3["SCRIPT_DATA_ESCAPED_END_TAG_OPEN"] = 23] = "SCRIPT_DATA_ESCAPED_END_TAG_OPEN";
  State3[State3["SCRIPT_DATA_ESCAPED_END_TAG_NAME"] = 24] = "SCRIPT_DATA_ESCAPED_END_TAG_NAME";
  State3[State3["SCRIPT_DATA_DOUBLE_ESCAPE_START"] = 25] = "SCRIPT_DATA_DOUBLE_ESCAPE_START";
  State3[State3["SCRIPT_DATA_DOUBLE_ESCAPED"] = 26] = "SCRIPT_DATA_DOUBLE_ESCAPED";
  State3[State3["SCRIPT_DATA_DOUBLE_ESCAPED_DASH"] = 27] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH";
  State3[State3["SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH"] = 28] = "SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH";
  State3[State3["SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN"] = 29] = "SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN";
  State3[State3["SCRIPT_DATA_DOUBLE_ESCAPE_END"] = 30] = "SCRIPT_DATA_DOUBLE_ESCAPE_END";
  State3[State3["BEFORE_ATTRIBUTE_NAME"] = 31] = "BEFORE_ATTRIBUTE_NAME";
  State3[State3["ATTRIBUTE_NAME"] = 32] = "ATTRIBUTE_NAME";
  State3[State3["AFTER_ATTRIBUTE_NAME"] = 33] = "AFTER_ATTRIBUTE_NAME";
  State3[State3["BEFORE_ATTRIBUTE_VALUE"] = 34] = "BEFORE_ATTRIBUTE_VALUE";
  State3[State3["ATTRIBUTE_VALUE_DOUBLE_QUOTED"] = 35] = "ATTRIBUTE_VALUE_DOUBLE_QUOTED";
  State3[State3["ATTRIBUTE_VALUE_SINGLE_QUOTED"] = 36] = "ATTRIBUTE_VALUE_SINGLE_QUOTED";
  State3[State3["ATTRIBUTE_VALUE_UNQUOTED"] = 37] = "ATTRIBUTE_VALUE_UNQUOTED";
  State3[State3["AFTER_ATTRIBUTE_VALUE_QUOTED"] = 38] = "AFTER_ATTRIBUTE_VALUE_QUOTED";
  State3[State3["SELF_CLOSING_START_TAG"] = 39] = "SELF_CLOSING_START_TAG";
  State3[State3["BOGUS_COMMENT"] = 40] = "BOGUS_COMMENT";
  State3[State3["MARKUP_DECLARATION_OPEN"] = 41] = "MARKUP_DECLARATION_OPEN";
  State3[State3["COMMENT_START"] = 42] = "COMMENT_START";
  State3[State3["COMMENT_START_DASH"] = 43] = "COMMENT_START_DASH";
  State3[State3["COMMENT"] = 44] = "COMMENT";
  State3[State3["COMMENT_LESS_THAN_SIGN"] = 45] = "COMMENT_LESS_THAN_SIGN";
  State3[State3["COMMENT_LESS_THAN_SIGN_BANG"] = 46] = "COMMENT_LESS_THAN_SIGN_BANG";
  State3[State3["COMMENT_LESS_THAN_SIGN_BANG_DASH"] = 47] = "COMMENT_LESS_THAN_SIGN_BANG_DASH";
  State3[State3["COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH"] = 48] = "COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH";
  State3[State3["COMMENT_END_DASH"] = 49] = "COMMENT_END_DASH";
  State3[State3["COMMENT_END"] = 50] = "COMMENT_END";
  State3[State3["COMMENT_END_BANG"] = 51] = "COMMENT_END_BANG";
  State3[State3["DOCTYPE"] = 52] = "DOCTYPE";
  State3[State3["BEFORE_DOCTYPE_NAME"] = 53] = "BEFORE_DOCTYPE_NAME";
  State3[State3["DOCTYPE_NAME"] = 54] = "DOCTYPE_NAME";
  State3[State3["AFTER_DOCTYPE_NAME"] = 55] = "AFTER_DOCTYPE_NAME";
  State3[State3["AFTER_DOCTYPE_PUBLIC_KEYWORD"] = 56] = "AFTER_DOCTYPE_PUBLIC_KEYWORD";
  State3[State3["BEFORE_DOCTYPE_PUBLIC_IDENTIFIER"] = 57] = "BEFORE_DOCTYPE_PUBLIC_IDENTIFIER";
  State3[State3["DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED"] = 58] = "DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED";
  State3[State3["DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED"] = 59] = "DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED";
  State3[State3["AFTER_DOCTYPE_PUBLIC_IDENTIFIER"] = 60] = "AFTER_DOCTYPE_PUBLIC_IDENTIFIER";
  State3[State3["BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS"] = 61] = "BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS";
  State3[State3["AFTER_DOCTYPE_SYSTEM_KEYWORD"] = 62] = "AFTER_DOCTYPE_SYSTEM_KEYWORD";
  State3[State3["BEFORE_DOCTYPE_SYSTEM_IDENTIFIER"] = 63] = "BEFORE_DOCTYPE_SYSTEM_IDENTIFIER";
  State3[State3["DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED"] = 64] = "DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED";
  State3[State3["DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED"] = 65] = "DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED";
  State3[State3["AFTER_DOCTYPE_SYSTEM_IDENTIFIER"] = 66] = "AFTER_DOCTYPE_SYSTEM_IDENTIFIER";
  State3[State3["BOGUS_DOCTYPE"] = 67] = "BOGUS_DOCTYPE";
  State3[State3["CDATA_SECTION"] = 68] = "CDATA_SECTION";
  State3[State3["CDATA_SECTION_BRACKET"] = 69] = "CDATA_SECTION_BRACKET";
  State3[State3["CDATA_SECTION_END"] = 70] = "CDATA_SECTION_END";
  State3[State3["CHARACTER_REFERENCE"] = 71] = "CHARACTER_REFERENCE";
  State3[State3["AMBIGUOUS_AMPERSAND"] = 72] = "AMBIGUOUS_AMPERSAND";
})(State || (State = {}));
var TokenizerMode = {
  DATA: State.DATA,
  RCDATA: State.RCDATA,
  RAWTEXT: State.RAWTEXT,
  SCRIPT_DATA: State.SCRIPT_DATA,
  PLAINTEXT: State.PLAINTEXT,
  CDATA_SECTION: State.CDATA_SECTION
};
function isAsciiDigit(cp) {
  return cp >= CODE_POINTS.DIGIT_0 && cp <= CODE_POINTS.DIGIT_9;
}
function isAsciiUpper(cp) {
  return cp >= CODE_POINTS.LATIN_CAPITAL_A && cp <= CODE_POINTS.LATIN_CAPITAL_Z;
}
function isAsciiLower(cp) {
  return cp >= CODE_POINTS.LATIN_SMALL_A && cp <= CODE_POINTS.LATIN_SMALL_Z;
}
function isAsciiLetter(cp) {
  return isAsciiLower(cp) || isAsciiUpper(cp);
}
function isAsciiAlphaNumeric2(cp) {
  return isAsciiLetter(cp) || isAsciiDigit(cp);
}
function toAsciiLower(cp) {
  return cp + 32;
}
function isWhitespace(cp) {
  return cp === CODE_POINTS.SPACE || cp === CODE_POINTS.LINE_FEED || cp === CODE_POINTS.TABULATION || cp === CODE_POINTS.FORM_FEED;
}
function isScriptDataDoubleEscapeSequenceEnd(cp) {
  return isWhitespace(cp) || cp === CODE_POINTS.SOLIDUS || cp === CODE_POINTS.GREATER_THAN_SIGN;
}
function getErrorForNumericCharacterReference(code5) {
  if (code5 === CODE_POINTS.NULL) {
    return ERR.nullCharacterReference;
  } else if (code5 > 1114111) {
    return ERR.characterReferenceOutsideUnicodeRange;
  } else if (isSurrogate(code5)) {
    return ERR.surrogateCharacterReference;
  } else if (isUndefinedCodePoint(code5)) {
    return ERR.noncharacterCharacterReference;
  } else if (isControlCodePoint(code5) || code5 === CODE_POINTS.CARRIAGE_RETURN) {
    return ERR.controlCharacterReference;
  }
  return null;
}
var Tokenizer = class {
  constructor(options2, handler) {
    this.options = options2;
    this.handler = handler;
    this.paused = false;
    this.inLoop = false;
    this.inForeignNode = false;
    this.lastStartTagName = "";
    this.active = false;
    this.state = State.DATA;
    this.returnState = State.DATA;
    this.entityStartPos = 0;
    this.consumedAfterSnapshot = -1;
    this.currentCharacterToken = null;
    this.currentToken = null;
    this.currentAttr = { name: "", value: "" };
    this.preprocessor = new Preprocessor(handler);
    this.currentLocation = this.getCurrentLocation(-1);
    this.entityDecoder = new EntityDecoder(htmlDecodeTree, (cp, consumed) => {
      this.preprocessor.pos = this.entityStartPos + consumed - 1;
      this._flushCodePointConsumedAsCharacterReference(cp);
    }, handler.onParseError ? {
      missingSemicolonAfterCharacterReference: () => {
        this._err(ERR.missingSemicolonAfterCharacterReference, 1);
      },
      absenceOfDigitsInNumericCharacterReference: (consumed) => {
        this._err(ERR.absenceOfDigitsInNumericCharacterReference, this.entityStartPos - this.preprocessor.pos + consumed);
      },
      validateNumericCharacterReference: (code5) => {
        const error2 = getErrorForNumericCharacterReference(code5);
        if (error2)
          this._err(error2, 1);
      }
    } : void 0);
  }
  //Errors
  _err(code5, cpOffset = 0) {
    var _a2, _b;
    (_b = (_a2 = this.handler).onParseError) === null || _b === void 0 ? void 0 : _b.call(_a2, this.preprocessor.getError(code5, cpOffset));
  }
  // NOTE: `offset` may never run across line boundaries.
  getCurrentLocation(offset4) {
    if (!this.options.sourceCodeLocationInfo) {
      return null;
    }
    return {
      startLine: this.preprocessor.line,
      startCol: this.preprocessor.col - offset4,
      startOffset: this.preprocessor.offset - offset4,
      endLine: -1,
      endCol: -1,
      endOffset: -1
    };
  }
  _runParsingLoop() {
    if (this.inLoop)
      return;
    this.inLoop = true;
    while (this.active && !this.paused) {
      this.consumedAfterSnapshot = 0;
      const cp = this._consume();
      if (!this._ensureHibernation()) {
        this._callState(cp);
      }
    }
    this.inLoop = false;
  }
  //API
  pause() {
    this.paused = true;
  }
  resume(writeCallback) {
    if (!this.paused) {
      throw new Error("Parser was already resumed");
    }
    this.paused = false;
    if (this.inLoop)
      return;
    this._runParsingLoop();
    if (!this.paused) {
      writeCallback === null || writeCallback === void 0 ? void 0 : writeCallback();
    }
  }
  write(chunk, isLastChunk, writeCallback) {
    this.active = true;
    this.preprocessor.write(chunk, isLastChunk);
    this._runParsingLoop();
    if (!this.paused) {
      writeCallback === null || writeCallback === void 0 ? void 0 : writeCallback();
    }
  }
  insertHtmlAtCurrentPos(chunk) {
    this.active = true;
    this.preprocessor.insertHtmlAtCurrentPos(chunk);
    this._runParsingLoop();
  }
  //Hibernation
  _ensureHibernation() {
    if (this.preprocessor.endOfChunkHit) {
      this.preprocessor.retreat(this.consumedAfterSnapshot);
      this.consumedAfterSnapshot = 0;
      this.active = false;
      return true;
    }
    return false;
  }
  //Consumption
  _consume() {
    this.consumedAfterSnapshot++;
    return this.preprocessor.advance();
  }
  _advanceBy(count2) {
    this.consumedAfterSnapshot += count2;
    for (let i3 = 0; i3 < count2; i3++) {
      this.preprocessor.advance();
    }
  }
  _consumeSequenceIfMatch(pattern, caseSensitive) {
    if (this.preprocessor.startsWith(pattern, caseSensitive)) {
      this._advanceBy(pattern.length - 1);
      return true;
    }
    return false;
  }
  //Token creation
  _createStartTagToken() {
    this.currentToken = {
      type: TokenType.START_TAG,
      tagName: "",
      tagID: TAG_ID.UNKNOWN,
      selfClosing: false,
      ackSelfClosing: false,
      attrs: [],
      location: this.getCurrentLocation(1)
    };
  }
  _createEndTagToken() {
    this.currentToken = {
      type: TokenType.END_TAG,
      tagName: "",
      tagID: TAG_ID.UNKNOWN,
      selfClosing: false,
      ackSelfClosing: false,
      attrs: [],
      location: this.getCurrentLocation(2)
    };
  }
  _createCommentToken(offset4) {
    this.currentToken = {
      type: TokenType.COMMENT,
      data: "",
      location: this.getCurrentLocation(offset4)
    };
  }
  _createDoctypeToken(initialName) {
    this.currentToken = {
      type: TokenType.DOCTYPE,
      name: initialName,
      forceQuirks: false,
      publicId: null,
      systemId: null,
      location: this.currentLocation
    };
  }
  _createCharacterToken(type, chars) {
    this.currentCharacterToken = {
      type,
      chars,
      location: this.currentLocation
    };
  }
  //Tag attributes
  _createAttr(attrNameFirstCh) {
    this.currentAttr = {
      name: attrNameFirstCh,
      value: ""
    };
    this.currentLocation = this.getCurrentLocation(0);
  }
  _leaveAttrName() {
    var _a2;
    var _b;
    const token = this.currentToken;
    if (getTokenAttr(token, this.currentAttr.name) === null) {
      token.attrs.push(this.currentAttr);
      if (token.location && this.currentLocation) {
        const attrLocations = (_a2 = (_b = token.location).attrs) !== null && _a2 !== void 0 ? _a2 : _b.attrs = /* @__PURE__ */ Object.create(null);
        attrLocations[this.currentAttr.name] = this.currentLocation;
        this._leaveAttrValue();
      }
    } else {
      this._err(ERR.duplicateAttribute);
    }
  }
  _leaveAttrValue() {
    if (this.currentLocation) {
      this.currentLocation.endLine = this.preprocessor.line;
      this.currentLocation.endCol = this.preprocessor.col;
      this.currentLocation.endOffset = this.preprocessor.offset;
    }
  }
  //Token emission
  prepareToken(ct2) {
    this._emitCurrentCharacterToken(ct2.location);
    this.currentToken = null;
    if (ct2.location) {
      ct2.location.endLine = this.preprocessor.line;
      ct2.location.endCol = this.preprocessor.col + 1;
      ct2.location.endOffset = this.preprocessor.offset + 1;
    }
    this.currentLocation = this.getCurrentLocation(-1);
  }
  emitCurrentTagToken() {
    const ct2 = this.currentToken;
    this.prepareToken(ct2);
    ct2.tagID = getTagID(ct2.tagName);
    if (ct2.type === TokenType.START_TAG) {
      this.lastStartTagName = ct2.tagName;
      this.handler.onStartTag(ct2);
    } else {
      if (ct2.attrs.length > 0) {
        this._err(ERR.endTagWithAttributes);
      }
      if (ct2.selfClosing) {
        this._err(ERR.endTagWithTrailingSolidus);
      }
      this.handler.onEndTag(ct2);
    }
    this.preprocessor.dropParsedChunk();
  }
  emitCurrentComment(ct2) {
    this.prepareToken(ct2);
    this.handler.onComment(ct2);
    this.preprocessor.dropParsedChunk();
  }
  emitCurrentDoctype(ct2) {
    this.prepareToken(ct2);
    this.handler.onDoctype(ct2);
    this.preprocessor.dropParsedChunk();
  }
  _emitCurrentCharacterToken(nextLocation) {
    if (this.currentCharacterToken) {
      if (nextLocation && this.currentCharacterToken.location) {
        this.currentCharacterToken.location.endLine = nextLocation.startLine;
        this.currentCharacterToken.location.endCol = nextLocation.startCol;
        this.currentCharacterToken.location.endOffset = nextLocation.startOffset;
      }
      switch (this.currentCharacterToken.type) {
        case TokenType.CHARACTER: {
          this.handler.onCharacter(this.currentCharacterToken);
          break;
        }
        case TokenType.NULL_CHARACTER: {
          this.handler.onNullCharacter(this.currentCharacterToken);
          break;
        }
        case TokenType.WHITESPACE_CHARACTER: {
          this.handler.onWhitespaceCharacter(this.currentCharacterToken);
          break;
        }
      }
      this.currentCharacterToken = null;
    }
  }
  _emitEOFToken() {
    const location3 = this.getCurrentLocation(0);
    if (location3) {
      location3.endLine = location3.startLine;
      location3.endCol = location3.startCol;
      location3.endOffset = location3.startOffset;
    }
    this._emitCurrentCharacterToken(location3);
    this.handler.onEof({ type: TokenType.EOF, location: location3 });
    this.active = false;
  }
  //Characters emission
  //OPTIMIZATION: The specification uses only one type of character token (one token per character).
  //This causes a huge memory overhead and a lot of unnecessary parser loops. parse5 uses 3 groups of characters.
  //If we have a sequence of characters that belong to the same group, the parser can process it
  //as a single solid character token.
  //So, there are 3 types of character tokens in parse5:
  //1)TokenType.NULL_CHARACTER - \u0000-character sequences (e.g. '\u0000\u0000\u0000')
  //2)TokenType.WHITESPACE_CHARACTER - any whitespace/new-line character sequences (e.g. '\n  \r\t   \f')
  //3)TokenType.CHARACTER - any character sequence which don't belong to groups 1 and 2 (e.g. 'abcdef1234@@#$%^')
  _appendCharToCurrentCharacterToken(type, ch) {
    if (this.currentCharacterToken) {
      if (this.currentCharacterToken.type === type) {
        this.currentCharacterToken.chars += ch;
        return;
      } else {
        this.currentLocation = this.getCurrentLocation(0);
        this._emitCurrentCharacterToken(this.currentLocation);
        this.preprocessor.dropParsedChunk();
      }
    }
    this._createCharacterToken(type, ch);
  }
  _emitCodePoint(cp) {
    const type = isWhitespace(cp) ? TokenType.WHITESPACE_CHARACTER : cp === CODE_POINTS.NULL ? TokenType.NULL_CHARACTER : TokenType.CHARACTER;
    this._appendCharToCurrentCharacterToken(type, String.fromCodePoint(cp));
  }
  //NOTE: used when we emit characters explicitly.
  //This is always for non-whitespace and non-null characters, which allows us to avoid additional checks.
  _emitChars(ch) {
    this._appendCharToCurrentCharacterToken(TokenType.CHARACTER, ch);
  }
  // Character reference helpers
  _startCharacterReference() {
    this.returnState = this.state;
    this.state = State.CHARACTER_REFERENCE;
    this.entityStartPos = this.preprocessor.pos;
    this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute() ? DecodingMode.Attribute : DecodingMode.Legacy);
  }
  _isCharacterReferenceInAttribute() {
    return this.returnState === State.ATTRIBUTE_VALUE_DOUBLE_QUOTED || this.returnState === State.ATTRIBUTE_VALUE_SINGLE_QUOTED || this.returnState === State.ATTRIBUTE_VALUE_UNQUOTED;
  }
  _flushCodePointConsumedAsCharacterReference(cp) {
    if (this._isCharacterReferenceInAttribute()) {
      this.currentAttr.value += String.fromCodePoint(cp);
    } else {
      this._emitCodePoint(cp);
    }
  }
  // Calling states this way turns out to be much faster than any other approach.
  _callState(cp) {
    switch (this.state) {
      case State.DATA: {
        this._stateData(cp);
        break;
      }
      case State.RCDATA: {
        this._stateRcdata(cp);
        break;
      }
      case State.RAWTEXT: {
        this._stateRawtext(cp);
        break;
      }
      case State.SCRIPT_DATA: {
        this._stateScriptData(cp);
        break;
      }
      case State.PLAINTEXT: {
        this._statePlaintext(cp);
        break;
      }
      case State.TAG_OPEN: {
        this._stateTagOpen(cp);
        break;
      }
      case State.END_TAG_OPEN: {
        this._stateEndTagOpen(cp);
        break;
      }
      case State.TAG_NAME: {
        this._stateTagName(cp);
        break;
      }
      case State.RCDATA_LESS_THAN_SIGN: {
        this._stateRcdataLessThanSign(cp);
        break;
      }
      case State.RCDATA_END_TAG_OPEN: {
        this._stateRcdataEndTagOpen(cp);
        break;
      }
      case State.RCDATA_END_TAG_NAME: {
        this._stateRcdataEndTagName(cp);
        break;
      }
      case State.RAWTEXT_LESS_THAN_SIGN: {
        this._stateRawtextLessThanSign(cp);
        break;
      }
      case State.RAWTEXT_END_TAG_OPEN: {
        this._stateRawtextEndTagOpen(cp);
        break;
      }
      case State.RAWTEXT_END_TAG_NAME: {
        this._stateRawtextEndTagName(cp);
        break;
      }
      case State.SCRIPT_DATA_LESS_THAN_SIGN: {
        this._stateScriptDataLessThanSign(cp);
        break;
      }
      case State.SCRIPT_DATA_END_TAG_OPEN: {
        this._stateScriptDataEndTagOpen(cp);
        break;
      }
      case State.SCRIPT_DATA_END_TAG_NAME: {
        this._stateScriptDataEndTagName(cp);
        break;
      }
      case State.SCRIPT_DATA_ESCAPE_START: {
        this._stateScriptDataEscapeStart(cp);
        break;
      }
      case State.SCRIPT_DATA_ESCAPE_START_DASH: {
        this._stateScriptDataEscapeStartDash(cp);
        break;
      }
      case State.SCRIPT_DATA_ESCAPED: {
        this._stateScriptDataEscaped(cp);
        break;
      }
      case State.SCRIPT_DATA_ESCAPED_DASH: {
        this._stateScriptDataEscapedDash(cp);
        break;
      }
      case State.SCRIPT_DATA_ESCAPED_DASH_DASH: {
        this._stateScriptDataEscapedDashDash(cp);
        break;
      }
      case State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN: {
        this._stateScriptDataEscapedLessThanSign(cp);
        break;
      }
      case State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN: {
        this._stateScriptDataEscapedEndTagOpen(cp);
        break;
      }
      case State.SCRIPT_DATA_ESCAPED_END_TAG_NAME: {
        this._stateScriptDataEscapedEndTagName(cp);
        break;
      }
      case State.SCRIPT_DATA_DOUBLE_ESCAPE_START: {
        this._stateScriptDataDoubleEscapeStart(cp);
        break;
      }
      case State.SCRIPT_DATA_DOUBLE_ESCAPED: {
        this._stateScriptDataDoubleEscaped(cp);
        break;
      }
      case State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH: {
        this._stateScriptDataDoubleEscapedDash(cp);
        break;
      }
      case State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH: {
        this._stateScriptDataDoubleEscapedDashDash(cp);
        break;
      }
      case State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN: {
        this._stateScriptDataDoubleEscapedLessThanSign(cp);
        break;
      }
      case State.SCRIPT_DATA_DOUBLE_ESCAPE_END: {
        this._stateScriptDataDoubleEscapeEnd(cp);
        break;
      }
      case State.BEFORE_ATTRIBUTE_NAME: {
        this._stateBeforeAttributeName(cp);
        break;
      }
      case State.ATTRIBUTE_NAME: {
        this._stateAttributeName(cp);
        break;
      }
      case State.AFTER_ATTRIBUTE_NAME: {
        this._stateAfterAttributeName(cp);
        break;
      }
      case State.BEFORE_ATTRIBUTE_VALUE: {
        this._stateBeforeAttributeValue(cp);
        break;
      }
      case State.ATTRIBUTE_VALUE_DOUBLE_QUOTED: {
        this._stateAttributeValueDoubleQuoted(cp);
        break;
      }
      case State.ATTRIBUTE_VALUE_SINGLE_QUOTED: {
        this._stateAttributeValueSingleQuoted(cp);
        break;
      }
      case State.ATTRIBUTE_VALUE_UNQUOTED: {
        this._stateAttributeValueUnquoted(cp);
        break;
      }
      case State.AFTER_ATTRIBUTE_VALUE_QUOTED: {
        this._stateAfterAttributeValueQuoted(cp);
        break;
      }
      case State.SELF_CLOSING_START_TAG: {
        this._stateSelfClosingStartTag(cp);
        break;
      }
      case State.BOGUS_COMMENT: {
        this._stateBogusComment(cp);
        break;
      }
      case State.MARKUP_DECLARATION_OPEN: {
        this._stateMarkupDeclarationOpen(cp);
        break;
      }
      case State.COMMENT_START: {
        this._stateCommentStart(cp);
        break;
      }
      case State.COMMENT_START_DASH: {
        this._stateCommentStartDash(cp);
        break;
      }
      case State.COMMENT: {
        this._stateComment(cp);
        break;
      }
      case State.COMMENT_LESS_THAN_SIGN: {
        this._stateCommentLessThanSign(cp);
        break;
      }
      case State.COMMENT_LESS_THAN_SIGN_BANG: {
        this._stateCommentLessThanSignBang(cp);
        break;
      }
      case State.COMMENT_LESS_THAN_SIGN_BANG_DASH: {
        this._stateCommentLessThanSignBangDash(cp);
        break;
      }
      case State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH: {
        this._stateCommentLessThanSignBangDashDash(cp);
        break;
      }
      case State.COMMENT_END_DASH: {
        this._stateCommentEndDash(cp);
        break;
      }
      case State.COMMENT_END: {
        this._stateCommentEnd(cp);
        break;
      }
      case State.COMMENT_END_BANG: {
        this._stateCommentEndBang(cp);
        break;
      }
      case State.DOCTYPE: {
        this._stateDoctype(cp);
        break;
      }
      case State.BEFORE_DOCTYPE_NAME: {
        this._stateBeforeDoctypeName(cp);
        break;
      }
      case State.DOCTYPE_NAME: {
        this._stateDoctypeName(cp);
        break;
      }
      case State.AFTER_DOCTYPE_NAME: {
        this._stateAfterDoctypeName(cp);
        break;
      }
      case State.AFTER_DOCTYPE_PUBLIC_KEYWORD: {
        this._stateAfterDoctypePublicKeyword(cp);
        break;
      }
      case State.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: {
        this._stateBeforeDoctypePublicIdentifier(cp);
        break;
      }
      case State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: {
        this._stateDoctypePublicIdentifierDoubleQuoted(cp);
        break;
      }
      case State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: {
        this._stateDoctypePublicIdentifierSingleQuoted(cp);
        break;
      }
      case State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER: {
        this._stateAfterDoctypePublicIdentifier(cp);
        break;
      }
      case State.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS: {
        this._stateBetweenDoctypePublicAndSystemIdentifiers(cp);
        break;
      }
      case State.AFTER_DOCTYPE_SYSTEM_KEYWORD: {
        this._stateAfterDoctypeSystemKeyword(cp);
        break;
      }
      case State.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: {
        this._stateBeforeDoctypeSystemIdentifier(cp);
        break;
      }
      case State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: {
        this._stateDoctypeSystemIdentifierDoubleQuoted(cp);
        break;
      }
      case State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: {
        this._stateDoctypeSystemIdentifierSingleQuoted(cp);
        break;
      }
      case State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER: {
        this._stateAfterDoctypeSystemIdentifier(cp);
        break;
      }
      case State.BOGUS_DOCTYPE: {
        this._stateBogusDoctype(cp);
        break;
      }
      case State.CDATA_SECTION: {
        this._stateCdataSection(cp);
        break;
      }
      case State.CDATA_SECTION_BRACKET: {
        this._stateCdataSectionBracket(cp);
        break;
      }
      case State.CDATA_SECTION_END: {
        this._stateCdataSectionEnd(cp);
        break;
      }
      case State.CHARACTER_REFERENCE: {
        this._stateCharacterReference();
        break;
      }
      case State.AMBIGUOUS_AMPERSAND: {
        this._stateAmbiguousAmpersand(cp);
        break;
      }
      default: {
        throw new Error("Unknown state");
      }
    }
  }
  // State machine
  // Data state
  //------------------------------------------------------------------
  _stateData(cp) {
    switch (cp) {
      case CODE_POINTS.LESS_THAN_SIGN: {
        this.state = State.TAG_OPEN;
        break;
      }
      case CODE_POINTS.AMPERSAND: {
        this._startCharacterReference();
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this._emitCodePoint(cp);
        break;
      }
      case CODE_POINTS.EOF: {
        this._emitEOFToken();
        break;
      }
      default: {
        this._emitCodePoint(cp);
      }
    }
  }
  //  RCDATA state
  //------------------------------------------------------------------
  _stateRcdata(cp) {
    switch (cp) {
      case CODE_POINTS.AMPERSAND: {
        this._startCharacterReference();
        break;
      }
      case CODE_POINTS.LESS_THAN_SIGN: {
        this.state = State.RCDATA_LESS_THAN_SIGN;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this._emitChars(REPLACEMENT_CHARACTER);
        break;
      }
      case CODE_POINTS.EOF: {
        this._emitEOFToken();
        break;
      }
      default: {
        this._emitCodePoint(cp);
      }
    }
  }
  // RAWTEXT state
  //------------------------------------------------------------------
  _stateRawtext(cp) {
    switch (cp) {
      case CODE_POINTS.LESS_THAN_SIGN: {
        this.state = State.RAWTEXT_LESS_THAN_SIGN;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this._emitChars(REPLACEMENT_CHARACTER);
        break;
      }
      case CODE_POINTS.EOF: {
        this._emitEOFToken();
        break;
      }
      default: {
        this._emitCodePoint(cp);
      }
    }
  }
  // Script data state
  //------------------------------------------------------------------
  _stateScriptData(cp) {
    switch (cp) {
      case CODE_POINTS.LESS_THAN_SIGN: {
        this.state = State.SCRIPT_DATA_LESS_THAN_SIGN;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this._emitChars(REPLACEMENT_CHARACTER);
        break;
      }
      case CODE_POINTS.EOF: {
        this._emitEOFToken();
        break;
      }
      default: {
        this._emitCodePoint(cp);
      }
    }
  }
  // PLAINTEXT state
  //------------------------------------------------------------------
  _statePlaintext(cp) {
    switch (cp) {
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this._emitChars(REPLACEMENT_CHARACTER);
        break;
      }
      case CODE_POINTS.EOF: {
        this._emitEOFToken();
        break;
      }
      default: {
        this._emitCodePoint(cp);
      }
    }
  }
  // Tag open state
  //------------------------------------------------------------------
  _stateTagOpen(cp) {
    if (isAsciiLetter(cp)) {
      this._createStartTagToken();
      this.state = State.TAG_NAME;
      this._stateTagName(cp);
    } else
      switch (cp) {
        case CODE_POINTS.EXCLAMATION_MARK: {
          this.state = State.MARKUP_DECLARATION_OPEN;
          break;
        }
        case CODE_POINTS.SOLIDUS: {
          this.state = State.END_TAG_OPEN;
          break;
        }
        case CODE_POINTS.QUESTION_MARK: {
          this._err(ERR.unexpectedQuestionMarkInsteadOfTagName);
          this._createCommentToken(1);
          this.state = State.BOGUS_COMMENT;
          this._stateBogusComment(cp);
          break;
        }
        case CODE_POINTS.EOF: {
          this._err(ERR.eofBeforeTagName);
          this._emitChars("<");
          this._emitEOFToken();
          break;
        }
        default: {
          this._err(ERR.invalidFirstCharacterOfTagName);
          this._emitChars("<");
          this.state = State.DATA;
          this._stateData(cp);
        }
      }
  }
  // End tag open state
  //------------------------------------------------------------------
  _stateEndTagOpen(cp) {
    if (isAsciiLetter(cp)) {
      this._createEndTagToken();
      this.state = State.TAG_NAME;
      this._stateTagName(cp);
    } else
      switch (cp) {
        case CODE_POINTS.GREATER_THAN_SIGN: {
          this._err(ERR.missingEndTagName);
          this.state = State.DATA;
          break;
        }
        case CODE_POINTS.EOF: {
          this._err(ERR.eofBeforeTagName);
          this._emitChars("</");
          this._emitEOFToken();
          break;
        }
        default: {
          this._err(ERR.invalidFirstCharacterOfTagName);
          this._createCommentToken(2);
          this.state = State.BOGUS_COMMENT;
          this._stateBogusComment(cp);
        }
      }
  }
  // Tag name state
  //------------------------------------------------------------------
  _stateTagName(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        this.state = State.BEFORE_ATTRIBUTE_NAME;
        break;
      }
      case CODE_POINTS.SOLIDUS: {
        this.state = State.SELF_CLOSING_START_TAG;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.DATA;
        this.emitCurrentTagToken();
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        token.tagName += REPLACEMENT_CHARACTER;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInTag);
        this._emitEOFToken();
        break;
      }
      default: {
        token.tagName += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
      }
    }
  }
  // RCDATA less-than sign state
  //------------------------------------------------------------------
  _stateRcdataLessThanSign(cp) {
    if (cp === CODE_POINTS.SOLIDUS) {
      this.state = State.RCDATA_END_TAG_OPEN;
    } else {
      this._emitChars("<");
      this.state = State.RCDATA;
      this._stateRcdata(cp);
    }
  }
  // RCDATA end tag open state
  //------------------------------------------------------------------
  _stateRcdataEndTagOpen(cp) {
    if (isAsciiLetter(cp)) {
      this.state = State.RCDATA_END_TAG_NAME;
      this._stateRcdataEndTagName(cp);
    } else {
      this._emitChars("</");
      this.state = State.RCDATA;
      this._stateRcdata(cp);
    }
  }
  handleSpecialEndTag(_cp) {
    if (!this.preprocessor.startsWith(this.lastStartTagName, false)) {
      return !this._ensureHibernation();
    }
    this._createEndTagToken();
    const token = this.currentToken;
    token.tagName = this.lastStartTagName;
    const cp = this.preprocessor.peek(this.lastStartTagName.length);
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        this._advanceBy(this.lastStartTagName.length);
        this.state = State.BEFORE_ATTRIBUTE_NAME;
        return false;
      }
      case CODE_POINTS.SOLIDUS: {
        this._advanceBy(this.lastStartTagName.length);
        this.state = State.SELF_CLOSING_START_TAG;
        return false;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._advanceBy(this.lastStartTagName.length);
        this.emitCurrentTagToken();
        this.state = State.DATA;
        return false;
      }
      default: {
        return !this._ensureHibernation();
      }
    }
  }
  // RCDATA end tag name state
  //------------------------------------------------------------------
  _stateRcdataEndTagName(cp) {
    if (this.handleSpecialEndTag(cp)) {
      this._emitChars("</");
      this.state = State.RCDATA;
      this._stateRcdata(cp);
    }
  }
  // RAWTEXT less-than sign state
  //------------------------------------------------------------------
  _stateRawtextLessThanSign(cp) {
    if (cp === CODE_POINTS.SOLIDUS) {
      this.state = State.RAWTEXT_END_TAG_OPEN;
    } else {
      this._emitChars("<");
      this.state = State.RAWTEXT;
      this._stateRawtext(cp);
    }
  }
  // RAWTEXT end tag open state
  //------------------------------------------------------------------
  _stateRawtextEndTagOpen(cp) {
    if (isAsciiLetter(cp)) {
      this.state = State.RAWTEXT_END_TAG_NAME;
      this._stateRawtextEndTagName(cp);
    } else {
      this._emitChars("</");
      this.state = State.RAWTEXT;
      this._stateRawtext(cp);
    }
  }
  // RAWTEXT end tag name state
  //------------------------------------------------------------------
  _stateRawtextEndTagName(cp) {
    if (this.handleSpecialEndTag(cp)) {
      this._emitChars("</");
      this.state = State.RAWTEXT;
      this._stateRawtext(cp);
    }
  }
  // Script data less-than sign state
  //------------------------------------------------------------------
  _stateScriptDataLessThanSign(cp) {
    switch (cp) {
      case CODE_POINTS.SOLIDUS: {
        this.state = State.SCRIPT_DATA_END_TAG_OPEN;
        break;
      }
      case CODE_POINTS.EXCLAMATION_MARK: {
        this.state = State.SCRIPT_DATA_ESCAPE_START;
        this._emitChars("<!");
        break;
      }
      default: {
        this._emitChars("<");
        this.state = State.SCRIPT_DATA;
        this._stateScriptData(cp);
      }
    }
  }
  // Script data end tag open state
  //------------------------------------------------------------------
  _stateScriptDataEndTagOpen(cp) {
    if (isAsciiLetter(cp)) {
      this.state = State.SCRIPT_DATA_END_TAG_NAME;
      this._stateScriptDataEndTagName(cp);
    } else {
      this._emitChars("</");
      this.state = State.SCRIPT_DATA;
      this._stateScriptData(cp);
    }
  }
  // Script data end tag name state
  //------------------------------------------------------------------
  _stateScriptDataEndTagName(cp) {
    if (this.handleSpecialEndTag(cp)) {
      this._emitChars("</");
      this.state = State.SCRIPT_DATA;
      this._stateScriptData(cp);
    }
  }
  // Script data escape start state
  //------------------------------------------------------------------
  _stateScriptDataEscapeStart(cp) {
    if (cp === CODE_POINTS.HYPHEN_MINUS) {
      this.state = State.SCRIPT_DATA_ESCAPE_START_DASH;
      this._emitChars("-");
    } else {
      this.state = State.SCRIPT_DATA;
      this._stateScriptData(cp);
    }
  }
  // Script data escape start dash state
  //------------------------------------------------------------------
  _stateScriptDataEscapeStartDash(cp) {
    if (cp === CODE_POINTS.HYPHEN_MINUS) {
      this.state = State.SCRIPT_DATA_ESCAPED_DASH_DASH;
      this._emitChars("-");
    } else {
      this.state = State.SCRIPT_DATA;
      this._stateScriptData(cp);
    }
  }
  // Script data escaped state
  //------------------------------------------------------------------
  _stateScriptDataEscaped(cp) {
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        this.state = State.SCRIPT_DATA_ESCAPED_DASH;
        this._emitChars("-");
        break;
      }
      case CODE_POINTS.LESS_THAN_SIGN: {
        this.state = State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this._emitChars(REPLACEMENT_CHARACTER);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInScriptHtmlCommentLikeText);
        this._emitEOFToken();
        break;
      }
      default: {
        this._emitCodePoint(cp);
      }
    }
  }
  // Script data escaped dash state
  //------------------------------------------------------------------
  _stateScriptDataEscapedDash(cp) {
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        this.state = State.SCRIPT_DATA_ESCAPED_DASH_DASH;
        this._emitChars("-");
        break;
      }
      case CODE_POINTS.LESS_THAN_SIGN: {
        this.state = State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this.state = State.SCRIPT_DATA_ESCAPED;
        this._emitChars(REPLACEMENT_CHARACTER);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInScriptHtmlCommentLikeText);
        this._emitEOFToken();
        break;
      }
      default: {
        this.state = State.SCRIPT_DATA_ESCAPED;
        this._emitCodePoint(cp);
      }
    }
  }
  // Script data escaped dash dash state
  //------------------------------------------------------------------
  _stateScriptDataEscapedDashDash(cp) {
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        this._emitChars("-");
        break;
      }
      case CODE_POINTS.LESS_THAN_SIGN: {
        this.state = State.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.SCRIPT_DATA;
        this._emitChars(">");
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this.state = State.SCRIPT_DATA_ESCAPED;
        this._emitChars(REPLACEMENT_CHARACTER);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInScriptHtmlCommentLikeText);
        this._emitEOFToken();
        break;
      }
      default: {
        this.state = State.SCRIPT_DATA_ESCAPED;
        this._emitCodePoint(cp);
      }
    }
  }
  // Script data escaped less-than sign state
  //------------------------------------------------------------------
  _stateScriptDataEscapedLessThanSign(cp) {
    if (cp === CODE_POINTS.SOLIDUS) {
      this.state = State.SCRIPT_DATA_ESCAPED_END_TAG_OPEN;
    } else if (isAsciiLetter(cp)) {
      this._emitChars("<");
      this.state = State.SCRIPT_DATA_DOUBLE_ESCAPE_START;
      this._stateScriptDataDoubleEscapeStart(cp);
    } else {
      this._emitChars("<");
      this.state = State.SCRIPT_DATA_ESCAPED;
      this._stateScriptDataEscaped(cp);
    }
  }
  // Script data escaped end tag open state
  //------------------------------------------------------------------
  _stateScriptDataEscapedEndTagOpen(cp) {
    if (isAsciiLetter(cp)) {
      this.state = State.SCRIPT_DATA_ESCAPED_END_TAG_NAME;
      this._stateScriptDataEscapedEndTagName(cp);
    } else {
      this._emitChars("</");
      this.state = State.SCRIPT_DATA_ESCAPED;
      this._stateScriptDataEscaped(cp);
    }
  }
  // Script data escaped end tag name state
  //------------------------------------------------------------------
  _stateScriptDataEscapedEndTagName(cp) {
    if (this.handleSpecialEndTag(cp)) {
      this._emitChars("</");
      this.state = State.SCRIPT_DATA_ESCAPED;
      this._stateScriptDataEscaped(cp);
    }
  }
  // Script data double escape start state
  //------------------------------------------------------------------
  _stateScriptDataDoubleEscapeStart(cp) {
    if (this.preprocessor.startsWith(SEQUENCES.SCRIPT, false) && isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(SEQUENCES.SCRIPT.length))) {
      this._emitCodePoint(cp);
      for (let i3 = 0; i3 < SEQUENCES.SCRIPT.length; i3++) {
        this._emitCodePoint(this._consume());
      }
      this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
    } else if (!this._ensureHibernation()) {
      this.state = State.SCRIPT_DATA_ESCAPED;
      this._stateScriptDataEscaped(cp);
    }
  }
  // Script data double escaped state
  //------------------------------------------------------------------
  _stateScriptDataDoubleEscaped(cp) {
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH;
        this._emitChars("-");
        break;
      }
      case CODE_POINTS.LESS_THAN_SIGN: {
        this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
        this._emitChars("<");
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this._emitChars(REPLACEMENT_CHARACTER);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInScriptHtmlCommentLikeText);
        this._emitEOFToken();
        break;
      }
      default: {
        this._emitCodePoint(cp);
      }
    }
  }
  // Script data double escaped dash state
  //------------------------------------------------------------------
  _stateScriptDataDoubleEscapedDash(cp) {
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH;
        this._emitChars("-");
        break;
      }
      case CODE_POINTS.LESS_THAN_SIGN: {
        this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
        this._emitChars("<");
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
        this._emitChars(REPLACEMENT_CHARACTER);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInScriptHtmlCommentLikeText);
        this._emitEOFToken();
        break;
      }
      default: {
        this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
        this._emitCodePoint(cp);
      }
    }
  }
  // Script data double escaped dash dash state
  //------------------------------------------------------------------
  _stateScriptDataDoubleEscapedDashDash(cp) {
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        this._emitChars("-");
        break;
      }
      case CODE_POINTS.LESS_THAN_SIGN: {
        this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN;
        this._emitChars("<");
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.SCRIPT_DATA;
        this._emitChars(">");
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
        this._emitChars(REPLACEMENT_CHARACTER);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInScriptHtmlCommentLikeText);
        this._emitEOFToken();
        break;
      }
      default: {
        this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
        this._emitCodePoint(cp);
      }
    }
  }
  // Script data double escaped less-than sign state
  //------------------------------------------------------------------
  _stateScriptDataDoubleEscapedLessThanSign(cp) {
    if (cp === CODE_POINTS.SOLIDUS) {
      this.state = State.SCRIPT_DATA_DOUBLE_ESCAPE_END;
      this._emitChars("/");
    } else {
      this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
      this._stateScriptDataDoubleEscaped(cp);
    }
  }
  // Script data double escape end state
  //------------------------------------------------------------------
  _stateScriptDataDoubleEscapeEnd(cp) {
    if (this.preprocessor.startsWith(SEQUENCES.SCRIPT, false) && isScriptDataDoubleEscapeSequenceEnd(this.preprocessor.peek(SEQUENCES.SCRIPT.length))) {
      this._emitCodePoint(cp);
      for (let i3 = 0; i3 < SEQUENCES.SCRIPT.length; i3++) {
        this._emitCodePoint(this._consume());
      }
      this.state = State.SCRIPT_DATA_ESCAPED;
    } else if (!this._ensureHibernation()) {
      this.state = State.SCRIPT_DATA_DOUBLE_ESCAPED;
      this._stateScriptDataDoubleEscaped(cp);
    }
  }
  // Before attribute name state
  //------------------------------------------------------------------
  _stateBeforeAttributeName(cp) {
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        break;
      }
      case CODE_POINTS.SOLIDUS:
      case CODE_POINTS.GREATER_THAN_SIGN:
      case CODE_POINTS.EOF: {
        this.state = State.AFTER_ATTRIBUTE_NAME;
        this._stateAfterAttributeName(cp);
        break;
      }
      case CODE_POINTS.EQUALS_SIGN: {
        this._err(ERR.unexpectedEqualsSignBeforeAttributeName);
        this._createAttr("=");
        this.state = State.ATTRIBUTE_NAME;
        break;
      }
      default: {
        this._createAttr("");
        this.state = State.ATTRIBUTE_NAME;
        this._stateAttributeName(cp);
      }
    }
  }
  // Attribute name state
  //------------------------------------------------------------------
  _stateAttributeName(cp) {
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED:
      case CODE_POINTS.SOLIDUS:
      case CODE_POINTS.GREATER_THAN_SIGN:
      case CODE_POINTS.EOF: {
        this._leaveAttrName();
        this.state = State.AFTER_ATTRIBUTE_NAME;
        this._stateAfterAttributeName(cp);
        break;
      }
      case CODE_POINTS.EQUALS_SIGN: {
        this._leaveAttrName();
        this.state = State.BEFORE_ATTRIBUTE_VALUE;
        break;
      }
      case CODE_POINTS.QUOTATION_MARK:
      case CODE_POINTS.APOSTROPHE:
      case CODE_POINTS.LESS_THAN_SIGN: {
        this._err(ERR.unexpectedCharacterInAttributeName);
        this.currentAttr.name += String.fromCodePoint(cp);
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this.currentAttr.name += REPLACEMENT_CHARACTER;
        break;
      }
      default: {
        this.currentAttr.name += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
      }
    }
  }
  // After attribute name state
  //------------------------------------------------------------------
  _stateAfterAttributeName(cp) {
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        break;
      }
      case CODE_POINTS.SOLIDUS: {
        this.state = State.SELF_CLOSING_START_TAG;
        break;
      }
      case CODE_POINTS.EQUALS_SIGN: {
        this.state = State.BEFORE_ATTRIBUTE_VALUE;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.DATA;
        this.emitCurrentTagToken();
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInTag);
        this._emitEOFToken();
        break;
      }
      default: {
        this._createAttr("");
        this.state = State.ATTRIBUTE_NAME;
        this._stateAttributeName(cp);
      }
    }
  }
  // Before attribute value state
  //------------------------------------------------------------------
  _stateBeforeAttributeValue(cp) {
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        break;
      }
      case CODE_POINTS.QUOTATION_MARK: {
        this.state = State.ATTRIBUTE_VALUE_DOUBLE_QUOTED;
        break;
      }
      case CODE_POINTS.APOSTROPHE: {
        this.state = State.ATTRIBUTE_VALUE_SINGLE_QUOTED;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.missingAttributeValue);
        this.state = State.DATA;
        this.emitCurrentTagToken();
        break;
      }
      default: {
        this.state = State.ATTRIBUTE_VALUE_UNQUOTED;
        this._stateAttributeValueUnquoted(cp);
      }
    }
  }
  // Attribute value (double-quoted) state
  //------------------------------------------------------------------
  _stateAttributeValueDoubleQuoted(cp) {
    switch (cp) {
      case CODE_POINTS.QUOTATION_MARK: {
        this.state = State.AFTER_ATTRIBUTE_VALUE_QUOTED;
        break;
      }
      case CODE_POINTS.AMPERSAND: {
        this._startCharacterReference();
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this.currentAttr.value += REPLACEMENT_CHARACTER;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInTag);
        this._emitEOFToken();
        break;
      }
      default: {
        this.currentAttr.value += String.fromCodePoint(cp);
      }
    }
  }
  // Attribute value (single-quoted) state
  //------------------------------------------------------------------
  _stateAttributeValueSingleQuoted(cp) {
    switch (cp) {
      case CODE_POINTS.APOSTROPHE: {
        this.state = State.AFTER_ATTRIBUTE_VALUE_QUOTED;
        break;
      }
      case CODE_POINTS.AMPERSAND: {
        this._startCharacterReference();
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this.currentAttr.value += REPLACEMENT_CHARACTER;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInTag);
        this._emitEOFToken();
        break;
      }
      default: {
        this.currentAttr.value += String.fromCodePoint(cp);
      }
    }
  }
  // Attribute value (unquoted) state
  //------------------------------------------------------------------
  _stateAttributeValueUnquoted(cp) {
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        this._leaveAttrValue();
        this.state = State.BEFORE_ATTRIBUTE_NAME;
        break;
      }
      case CODE_POINTS.AMPERSAND: {
        this._startCharacterReference();
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._leaveAttrValue();
        this.state = State.DATA;
        this.emitCurrentTagToken();
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        this.currentAttr.value += REPLACEMENT_CHARACTER;
        break;
      }
      case CODE_POINTS.QUOTATION_MARK:
      case CODE_POINTS.APOSTROPHE:
      case CODE_POINTS.LESS_THAN_SIGN:
      case CODE_POINTS.EQUALS_SIGN:
      case CODE_POINTS.GRAVE_ACCENT: {
        this._err(ERR.unexpectedCharacterInUnquotedAttributeValue);
        this.currentAttr.value += String.fromCodePoint(cp);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInTag);
        this._emitEOFToken();
        break;
      }
      default: {
        this.currentAttr.value += String.fromCodePoint(cp);
      }
    }
  }
  // After attribute value (quoted) state
  //------------------------------------------------------------------
  _stateAfterAttributeValueQuoted(cp) {
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        this._leaveAttrValue();
        this.state = State.BEFORE_ATTRIBUTE_NAME;
        break;
      }
      case CODE_POINTS.SOLIDUS: {
        this._leaveAttrValue();
        this.state = State.SELF_CLOSING_START_TAG;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._leaveAttrValue();
        this.state = State.DATA;
        this.emitCurrentTagToken();
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInTag);
        this._emitEOFToken();
        break;
      }
      default: {
        this._err(ERR.missingWhitespaceBetweenAttributes);
        this.state = State.BEFORE_ATTRIBUTE_NAME;
        this._stateBeforeAttributeName(cp);
      }
    }
  }
  // Self-closing start tag state
  //------------------------------------------------------------------
  _stateSelfClosingStartTag(cp) {
    switch (cp) {
      case CODE_POINTS.GREATER_THAN_SIGN: {
        const token = this.currentToken;
        token.selfClosing = true;
        this.state = State.DATA;
        this.emitCurrentTagToken();
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInTag);
        this._emitEOFToken();
        break;
      }
      default: {
        this._err(ERR.unexpectedSolidusInTag);
        this.state = State.BEFORE_ATTRIBUTE_NAME;
        this._stateBeforeAttributeName(cp);
      }
    }
  }
  // Bogus comment state
  //------------------------------------------------------------------
  _stateBogusComment(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.DATA;
        this.emitCurrentComment(token);
        break;
      }
      case CODE_POINTS.EOF: {
        this.emitCurrentComment(token);
        this._emitEOFToken();
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        token.data += REPLACEMENT_CHARACTER;
        break;
      }
      default: {
        token.data += String.fromCodePoint(cp);
      }
    }
  }
  // Markup declaration open state
  //------------------------------------------------------------------
  _stateMarkupDeclarationOpen(cp) {
    if (this._consumeSequenceIfMatch(SEQUENCES.DASH_DASH, true)) {
      this._createCommentToken(SEQUENCES.DASH_DASH.length + 1);
      this.state = State.COMMENT_START;
    } else if (this._consumeSequenceIfMatch(SEQUENCES.DOCTYPE, false)) {
      this.currentLocation = this.getCurrentLocation(SEQUENCES.DOCTYPE.length + 1);
      this.state = State.DOCTYPE;
    } else if (this._consumeSequenceIfMatch(SEQUENCES.CDATA_START, true)) {
      if (this.inForeignNode) {
        this.state = State.CDATA_SECTION;
      } else {
        this._err(ERR.cdataInHtmlContent);
        this._createCommentToken(SEQUENCES.CDATA_START.length + 1);
        this.currentToken.data = "[CDATA[";
        this.state = State.BOGUS_COMMENT;
      }
    } else if (!this._ensureHibernation()) {
      this._err(ERR.incorrectlyOpenedComment);
      this._createCommentToken(2);
      this.state = State.BOGUS_COMMENT;
      this._stateBogusComment(cp);
    }
  }
  // Comment start state
  //------------------------------------------------------------------
  _stateCommentStart(cp) {
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        this.state = State.COMMENT_START_DASH;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.abruptClosingOfEmptyComment);
        this.state = State.DATA;
        const token = this.currentToken;
        this.emitCurrentComment(token);
        break;
      }
      default: {
        this.state = State.COMMENT;
        this._stateComment(cp);
      }
    }
  }
  // Comment start dash state
  //------------------------------------------------------------------
  _stateCommentStartDash(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        this.state = State.COMMENT_END;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.abruptClosingOfEmptyComment);
        this.state = State.DATA;
        this.emitCurrentComment(token);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInComment);
        this.emitCurrentComment(token);
        this._emitEOFToken();
        break;
      }
      default: {
        token.data += "-";
        this.state = State.COMMENT;
        this._stateComment(cp);
      }
    }
  }
  // Comment state
  //------------------------------------------------------------------
  _stateComment(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        this.state = State.COMMENT_END_DASH;
        break;
      }
      case CODE_POINTS.LESS_THAN_SIGN: {
        token.data += "<";
        this.state = State.COMMENT_LESS_THAN_SIGN;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        token.data += REPLACEMENT_CHARACTER;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInComment);
        this.emitCurrentComment(token);
        this._emitEOFToken();
        break;
      }
      default: {
        token.data += String.fromCodePoint(cp);
      }
    }
  }
  // Comment less-than sign state
  //------------------------------------------------------------------
  _stateCommentLessThanSign(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.EXCLAMATION_MARK: {
        token.data += "!";
        this.state = State.COMMENT_LESS_THAN_SIGN_BANG;
        break;
      }
      case CODE_POINTS.LESS_THAN_SIGN: {
        token.data += "<";
        break;
      }
      default: {
        this.state = State.COMMENT;
        this._stateComment(cp);
      }
    }
  }
  // Comment less-than sign bang state
  //------------------------------------------------------------------
  _stateCommentLessThanSignBang(cp) {
    if (cp === CODE_POINTS.HYPHEN_MINUS) {
      this.state = State.COMMENT_LESS_THAN_SIGN_BANG_DASH;
    } else {
      this.state = State.COMMENT;
      this._stateComment(cp);
    }
  }
  // Comment less-than sign bang dash state
  //------------------------------------------------------------------
  _stateCommentLessThanSignBangDash(cp) {
    if (cp === CODE_POINTS.HYPHEN_MINUS) {
      this.state = State.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH;
    } else {
      this.state = State.COMMENT_END_DASH;
      this._stateCommentEndDash(cp);
    }
  }
  // Comment less-than sign bang dash dash state
  //------------------------------------------------------------------
  _stateCommentLessThanSignBangDashDash(cp) {
    if (cp !== CODE_POINTS.GREATER_THAN_SIGN && cp !== CODE_POINTS.EOF) {
      this._err(ERR.nestedComment);
    }
    this.state = State.COMMENT_END;
    this._stateCommentEnd(cp);
  }
  // Comment end dash state
  //------------------------------------------------------------------
  _stateCommentEndDash(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        this.state = State.COMMENT_END;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInComment);
        this.emitCurrentComment(token);
        this._emitEOFToken();
        break;
      }
      default: {
        token.data += "-";
        this.state = State.COMMENT;
        this._stateComment(cp);
      }
    }
  }
  // Comment end state
  //------------------------------------------------------------------
  _stateCommentEnd(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.DATA;
        this.emitCurrentComment(token);
        break;
      }
      case CODE_POINTS.EXCLAMATION_MARK: {
        this.state = State.COMMENT_END_BANG;
        break;
      }
      case CODE_POINTS.HYPHEN_MINUS: {
        token.data += "-";
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInComment);
        this.emitCurrentComment(token);
        this._emitEOFToken();
        break;
      }
      default: {
        token.data += "--";
        this.state = State.COMMENT;
        this._stateComment(cp);
      }
    }
  }
  // Comment end bang state
  //------------------------------------------------------------------
  _stateCommentEndBang(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.HYPHEN_MINUS: {
        token.data += "--!";
        this.state = State.COMMENT_END_DASH;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.incorrectlyClosedComment);
        this.state = State.DATA;
        this.emitCurrentComment(token);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInComment);
        this.emitCurrentComment(token);
        this._emitEOFToken();
        break;
      }
      default: {
        token.data += "--!";
        this.state = State.COMMENT;
        this._stateComment(cp);
      }
    }
  }
  // DOCTYPE state
  //------------------------------------------------------------------
  _stateDoctype(cp) {
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        this.state = State.BEFORE_DOCTYPE_NAME;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.BEFORE_DOCTYPE_NAME;
        this._stateBeforeDoctypeName(cp);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        this._createDoctypeToken(null);
        const token = this.currentToken;
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        this._err(ERR.missingWhitespaceBeforeDoctypeName);
        this.state = State.BEFORE_DOCTYPE_NAME;
        this._stateBeforeDoctypeName(cp);
      }
    }
  }
  // Before DOCTYPE name state
  //------------------------------------------------------------------
  _stateBeforeDoctypeName(cp) {
    if (isAsciiUpper(cp)) {
      this._createDoctypeToken(String.fromCharCode(toAsciiLower(cp)));
      this.state = State.DOCTYPE_NAME;
    } else
      switch (cp) {
        case CODE_POINTS.SPACE:
        case CODE_POINTS.LINE_FEED:
        case CODE_POINTS.TABULATION:
        case CODE_POINTS.FORM_FEED: {
          break;
        }
        case CODE_POINTS.NULL: {
          this._err(ERR.unexpectedNullCharacter);
          this._createDoctypeToken(REPLACEMENT_CHARACTER);
          this.state = State.DOCTYPE_NAME;
          break;
        }
        case CODE_POINTS.GREATER_THAN_SIGN: {
          this._err(ERR.missingDoctypeName);
          this._createDoctypeToken(null);
          const token = this.currentToken;
          token.forceQuirks = true;
          this.emitCurrentDoctype(token);
          this.state = State.DATA;
          break;
        }
        case CODE_POINTS.EOF: {
          this._err(ERR.eofInDoctype);
          this._createDoctypeToken(null);
          const token = this.currentToken;
          token.forceQuirks = true;
          this.emitCurrentDoctype(token);
          this._emitEOFToken();
          break;
        }
        default: {
          this._createDoctypeToken(String.fromCodePoint(cp));
          this.state = State.DOCTYPE_NAME;
        }
      }
  }
  // DOCTYPE name state
  //------------------------------------------------------------------
  _stateDoctypeName(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        this.state = State.AFTER_DOCTYPE_NAME;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.DATA;
        this.emitCurrentDoctype(token);
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        token.name += REPLACEMENT_CHARACTER;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        token.name += String.fromCodePoint(isAsciiUpper(cp) ? toAsciiLower(cp) : cp);
      }
    }
  }
  // After DOCTYPE name state
  //------------------------------------------------------------------
  _stateAfterDoctypeName(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.DATA;
        this.emitCurrentDoctype(token);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        if (this._consumeSequenceIfMatch(SEQUENCES.PUBLIC, false)) {
          this.state = State.AFTER_DOCTYPE_PUBLIC_KEYWORD;
        } else if (this._consumeSequenceIfMatch(SEQUENCES.SYSTEM, false)) {
          this.state = State.AFTER_DOCTYPE_SYSTEM_KEYWORD;
        } else if (!this._ensureHibernation()) {
          this._err(ERR.invalidCharacterSequenceAfterDoctypeName);
          token.forceQuirks = true;
          this.state = State.BOGUS_DOCTYPE;
          this._stateBogusDoctype(cp);
        }
      }
    }
  }
  // After DOCTYPE public keyword state
  //------------------------------------------------------------------
  _stateAfterDoctypePublicKeyword(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        this.state = State.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;
        break;
      }
      case CODE_POINTS.QUOTATION_MARK: {
        this._err(ERR.missingWhitespaceAfterDoctypePublicKeyword);
        token.publicId = "";
        this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
        break;
      }
      case CODE_POINTS.APOSTROPHE: {
        this._err(ERR.missingWhitespaceAfterDoctypePublicKeyword);
        token.publicId = "";
        this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.missingDoctypePublicIdentifier);
        token.forceQuirks = true;
        this.state = State.DATA;
        this.emitCurrentDoctype(token);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier);
        token.forceQuirks = true;
        this.state = State.BOGUS_DOCTYPE;
        this._stateBogusDoctype(cp);
      }
    }
  }
  // Before DOCTYPE public identifier state
  //------------------------------------------------------------------
  _stateBeforeDoctypePublicIdentifier(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        break;
      }
      case CODE_POINTS.QUOTATION_MARK: {
        token.publicId = "";
        this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;
        break;
      }
      case CODE_POINTS.APOSTROPHE: {
        token.publicId = "";
        this.state = State.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.missingDoctypePublicIdentifier);
        token.forceQuirks = true;
        this.state = State.DATA;
        this.emitCurrentDoctype(token);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        this._err(ERR.missingQuoteBeforeDoctypePublicIdentifier);
        token.forceQuirks = true;
        this.state = State.BOGUS_DOCTYPE;
        this._stateBogusDoctype(cp);
      }
    }
  }
  // DOCTYPE public identifier (double-quoted) state
  //------------------------------------------------------------------
  _stateDoctypePublicIdentifierDoubleQuoted(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.QUOTATION_MARK: {
        this.state = State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        token.publicId += REPLACEMENT_CHARACTER;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.abruptDoctypePublicIdentifier);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this.state = State.DATA;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        token.publicId += String.fromCodePoint(cp);
      }
    }
  }
  // DOCTYPE public identifier (single-quoted) state
  //------------------------------------------------------------------
  _stateDoctypePublicIdentifierSingleQuoted(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.APOSTROPHE: {
        this.state = State.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        token.publicId += REPLACEMENT_CHARACTER;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.abruptDoctypePublicIdentifier);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this.state = State.DATA;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        token.publicId += String.fromCodePoint(cp);
      }
    }
  }
  // After DOCTYPE public identifier state
  //------------------------------------------------------------------
  _stateAfterDoctypePublicIdentifier(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        this.state = State.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.DATA;
        this.emitCurrentDoctype(token);
        break;
      }
      case CODE_POINTS.QUOTATION_MARK: {
        this._err(ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers);
        token.systemId = "";
        this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
        break;
      }
      case CODE_POINTS.APOSTROPHE: {
        this._err(ERR.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers);
        token.systemId = "";
        this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
        token.forceQuirks = true;
        this.state = State.BOGUS_DOCTYPE;
        this._stateBogusDoctype(cp);
      }
    }
  }
  // Between DOCTYPE public and system identifiers state
  //------------------------------------------------------------------
  _stateBetweenDoctypePublicAndSystemIdentifiers(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.emitCurrentDoctype(token);
        this.state = State.DATA;
        break;
      }
      case CODE_POINTS.QUOTATION_MARK: {
        token.systemId = "";
        this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
        break;
      }
      case CODE_POINTS.APOSTROPHE: {
        token.systemId = "";
        this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
        token.forceQuirks = true;
        this.state = State.BOGUS_DOCTYPE;
        this._stateBogusDoctype(cp);
      }
    }
  }
  // After DOCTYPE system keyword state
  //------------------------------------------------------------------
  _stateAfterDoctypeSystemKeyword(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        this.state = State.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;
        break;
      }
      case CODE_POINTS.QUOTATION_MARK: {
        this._err(ERR.missingWhitespaceAfterDoctypeSystemKeyword);
        token.systemId = "";
        this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
        break;
      }
      case CODE_POINTS.APOSTROPHE: {
        this._err(ERR.missingWhitespaceAfterDoctypeSystemKeyword);
        token.systemId = "";
        this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.missingDoctypeSystemIdentifier);
        token.forceQuirks = true;
        this.state = State.DATA;
        this.emitCurrentDoctype(token);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
        token.forceQuirks = true;
        this.state = State.BOGUS_DOCTYPE;
        this._stateBogusDoctype(cp);
      }
    }
  }
  // Before DOCTYPE system identifier state
  //------------------------------------------------------------------
  _stateBeforeDoctypeSystemIdentifier(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        break;
      }
      case CODE_POINTS.QUOTATION_MARK: {
        token.systemId = "";
        this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;
        break;
      }
      case CODE_POINTS.APOSTROPHE: {
        token.systemId = "";
        this.state = State.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.missingDoctypeSystemIdentifier);
        token.forceQuirks = true;
        this.state = State.DATA;
        this.emitCurrentDoctype(token);
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        this._err(ERR.missingQuoteBeforeDoctypeSystemIdentifier);
        token.forceQuirks = true;
        this.state = State.BOGUS_DOCTYPE;
        this._stateBogusDoctype(cp);
      }
    }
  }
  // DOCTYPE system identifier (double-quoted) state
  //------------------------------------------------------------------
  _stateDoctypeSystemIdentifierDoubleQuoted(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.QUOTATION_MARK: {
        this.state = State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        token.systemId += REPLACEMENT_CHARACTER;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.abruptDoctypeSystemIdentifier);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this.state = State.DATA;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        token.systemId += String.fromCodePoint(cp);
      }
    }
  }
  // DOCTYPE system identifier (single-quoted) state
  //------------------------------------------------------------------
  _stateDoctypeSystemIdentifierSingleQuoted(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.APOSTROPHE: {
        this.state = State.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        token.systemId += REPLACEMENT_CHARACTER;
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this._err(ERR.abruptDoctypeSystemIdentifier);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this.state = State.DATA;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        token.systemId += String.fromCodePoint(cp);
      }
    }
  }
  // After DOCTYPE system identifier state
  //------------------------------------------------------------------
  _stateAfterDoctypeSystemIdentifier(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.SPACE:
      case CODE_POINTS.LINE_FEED:
      case CODE_POINTS.TABULATION:
      case CODE_POINTS.FORM_FEED: {
        break;
      }
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.emitCurrentDoctype(token);
        this.state = State.DATA;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInDoctype);
        token.forceQuirks = true;
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default: {
        this._err(ERR.unexpectedCharacterAfterDoctypeSystemIdentifier);
        this.state = State.BOGUS_DOCTYPE;
        this._stateBogusDoctype(cp);
      }
    }
  }
  // Bogus DOCTYPE state
  //------------------------------------------------------------------
  _stateBogusDoctype(cp) {
    const token = this.currentToken;
    switch (cp) {
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.emitCurrentDoctype(token);
        this.state = State.DATA;
        break;
      }
      case CODE_POINTS.NULL: {
        this._err(ERR.unexpectedNullCharacter);
        break;
      }
      case CODE_POINTS.EOF: {
        this.emitCurrentDoctype(token);
        this._emitEOFToken();
        break;
      }
      default:
    }
  }
  // CDATA section state
  //------------------------------------------------------------------
  _stateCdataSection(cp) {
    switch (cp) {
      case CODE_POINTS.RIGHT_SQUARE_BRACKET: {
        this.state = State.CDATA_SECTION_BRACKET;
        break;
      }
      case CODE_POINTS.EOF: {
        this._err(ERR.eofInCdata);
        this._emitEOFToken();
        break;
      }
      default: {
        this._emitCodePoint(cp);
      }
    }
  }
  // CDATA section bracket state
  //------------------------------------------------------------------
  _stateCdataSectionBracket(cp) {
    if (cp === CODE_POINTS.RIGHT_SQUARE_BRACKET) {
      this.state = State.CDATA_SECTION_END;
    } else {
      this._emitChars("]");
      this.state = State.CDATA_SECTION;
      this._stateCdataSection(cp);
    }
  }
  // CDATA section end state
  //------------------------------------------------------------------
  _stateCdataSectionEnd(cp) {
    switch (cp) {
      case CODE_POINTS.GREATER_THAN_SIGN: {
        this.state = State.DATA;
        break;
      }
      case CODE_POINTS.RIGHT_SQUARE_BRACKET: {
        this._emitChars("]");
        break;
      }
      default: {
        this._emitChars("]]");
        this.state = State.CDATA_SECTION;
        this._stateCdataSection(cp);
      }
    }
  }
  // Character reference state
  //------------------------------------------------------------------
  _stateCharacterReference() {
    let length2 = this.entityDecoder.write(this.preprocessor.html, this.preprocessor.pos);
    if (length2 < 0) {
      if (this.preprocessor.lastChunkWritten) {
        length2 = this.entityDecoder.end();
      } else {
        this.active = false;
        this.preprocessor.pos = this.preprocessor.html.length - 1;
        this.consumedAfterSnapshot = 0;
        this.preprocessor.endOfChunkHit = true;
        return;
      }
    }
    if (length2 === 0) {
      this.preprocessor.pos = this.entityStartPos;
      this._flushCodePointConsumedAsCharacterReference(CODE_POINTS.AMPERSAND);
      this.state = !this._isCharacterReferenceInAttribute() && isAsciiAlphaNumeric2(this.preprocessor.peek(1)) ? State.AMBIGUOUS_AMPERSAND : this.returnState;
    } else {
      this.state = this.returnState;
    }
  }
  // Ambiguos ampersand state
  //------------------------------------------------------------------
  _stateAmbiguousAmpersand(cp) {
    if (isAsciiAlphaNumeric2(cp)) {
      this._flushCodePointConsumedAsCharacterReference(cp);
    } else {
      if (cp === CODE_POINTS.SEMICOLON) {
        this._err(ERR.unknownNamedCharacterReference);
      }
      this.state = this.returnState;
      this._callState(cp);
    }
  }
};

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/parser/open-element-stack.js
var IMPLICIT_END_TAG_REQUIRED = /* @__PURE__ */ new Set([TAG_ID.DD, TAG_ID.DT, TAG_ID.LI, TAG_ID.OPTGROUP, TAG_ID.OPTION, TAG_ID.P, TAG_ID.RB, TAG_ID.RP, TAG_ID.RT, TAG_ID.RTC]);
var IMPLICIT_END_TAG_REQUIRED_THOROUGHLY = /* @__PURE__ */ new Set([
  ...IMPLICIT_END_TAG_REQUIRED,
  TAG_ID.CAPTION,
  TAG_ID.COLGROUP,
  TAG_ID.TBODY,
  TAG_ID.TD,
  TAG_ID.TFOOT,
  TAG_ID.TH,
  TAG_ID.THEAD,
  TAG_ID.TR
]);
var SCOPING_ELEMENTS_HTML = /* @__PURE__ */ new Set([
  TAG_ID.APPLET,
  TAG_ID.CAPTION,
  TAG_ID.HTML,
  TAG_ID.MARQUEE,
  TAG_ID.OBJECT,
  TAG_ID.TABLE,
  TAG_ID.TD,
  TAG_ID.TEMPLATE,
  TAG_ID.TH
]);
var SCOPING_ELEMENTS_HTML_LIST = /* @__PURE__ */ new Set([...SCOPING_ELEMENTS_HTML, TAG_ID.OL, TAG_ID.UL]);
var SCOPING_ELEMENTS_HTML_BUTTON = /* @__PURE__ */ new Set([...SCOPING_ELEMENTS_HTML, TAG_ID.BUTTON]);
var SCOPING_ELEMENTS_MATHML = /* @__PURE__ */ new Set([TAG_ID.ANNOTATION_XML, TAG_ID.MI, TAG_ID.MN, TAG_ID.MO, TAG_ID.MS, TAG_ID.MTEXT]);
var SCOPING_ELEMENTS_SVG = /* @__PURE__ */ new Set([TAG_ID.DESC, TAG_ID.FOREIGN_OBJECT, TAG_ID.TITLE]);
var TABLE_ROW_CONTEXT = /* @__PURE__ */ new Set([TAG_ID.TR, TAG_ID.TEMPLATE, TAG_ID.HTML]);
var TABLE_BODY_CONTEXT = /* @__PURE__ */ new Set([TAG_ID.TBODY, TAG_ID.TFOOT, TAG_ID.THEAD, TAG_ID.TEMPLATE, TAG_ID.HTML]);
var TABLE_CONTEXT = /* @__PURE__ */ new Set([TAG_ID.TABLE, TAG_ID.TEMPLATE, TAG_ID.HTML]);
var TABLE_CELLS = /* @__PURE__ */ new Set([TAG_ID.TD, TAG_ID.TH]);
var OpenElementStack = class {
  get currentTmplContentOrNode() {
    return this._isInTemplate() ? this.treeAdapter.getTemplateContent(this.current) : this.current;
  }
  constructor(document4, treeAdapter, handler) {
    this.treeAdapter = treeAdapter;
    this.handler = handler;
    this.items = [];
    this.tagIDs = [];
    this.stackTop = -1;
    this.tmplCount = 0;
    this.currentTagId = TAG_ID.UNKNOWN;
    this.current = document4;
  }
  //Index of element
  _indexOf(element7) {
    return this.items.lastIndexOf(element7, this.stackTop);
  }
  //Update current element
  _isInTemplate() {
    return this.currentTagId === TAG_ID.TEMPLATE && this.treeAdapter.getNamespaceURI(this.current) === NS.HTML;
  }
  _updateCurrentElement() {
    this.current = this.items[this.stackTop];
    this.currentTagId = this.tagIDs[this.stackTop];
  }
  //Mutations
  push(element7, tagID) {
    this.stackTop++;
    this.items[this.stackTop] = element7;
    this.current = element7;
    this.tagIDs[this.stackTop] = tagID;
    this.currentTagId = tagID;
    if (this._isInTemplate()) {
      this.tmplCount++;
    }
    this.handler.onItemPush(element7, tagID, true);
  }
  pop() {
    const popped = this.current;
    if (this.tmplCount > 0 && this._isInTemplate()) {
      this.tmplCount--;
    }
    this.stackTop--;
    this._updateCurrentElement();
    this.handler.onItemPop(popped, true);
  }
  replace(oldElement, newElement) {
    const idx = this._indexOf(oldElement);
    this.items[idx] = newElement;
    if (idx === this.stackTop) {
      this.current = newElement;
    }
  }
  insertAfter(referenceElement, newElement, newElementID) {
    const insertionIdx = this._indexOf(referenceElement) + 1;
    this.items.splice(insertionIdx, 0, newElement);
    this.tagIDs.splice(insertionIdx, 0, newElementID);
    this.stackTop++;
    if (insertionIdx === this.stackTop) {
      this._updateCurrentElement();
    }
    if (this.current && this.currentTagId !== void 0) {
      this.handler.onItemPush(this.current, this.currentTagId, insertionIdx === this.stackTop);
    }
  }
  popUntilTagNamePopped(tagName) {
    let targetIdx = this.stackTop + 1;
    do {
      targetIdx = this.tagIDs.lastIndexOf(tagName, targetIdx - 1);
    } while (targetIdx > 0 && this.treeAdapter.getNamespaceURI(this.items[targetIdx]) !== NS.HTML);
    this.shortenToLength(Math.max(targetIdx, 0));
  }
  shortenToLength(idx) {
    while (this.stackTop >= idx) {
      const popped = this.current;
      if (this.tmplCount > 0 && this._isInTemplate()) {
        this.tmplCount -= 1;
      }
      this.stackTop--;
      this._updateCurrentElement();
      this.handler.onItemPop(popped, this.stackTop < idx);
    }
  }
  popUntilElementPopped(element7) {
    const idx = this._indexOf(element7);
    this.shortenToLength(Math.max(idx, 0));
  }
  popUntilPopped(tagNames, targetNS) {
    const idx = this._indexOfTagNames(tagNames, targetNS);
    this.shortenToLength(Math.max(idx, 0));
  }
  popUntilNumberedHeaderPopped() {
    this.popUntilPopped(NUMBERED_HEADERS, NS.HTML);
  }
  popUntilTableCellPopped() {
    this.popUntilPopped(TABLE_CELLS, NS.HTML);
  }
  popAllUpToHtmlElement() {
    this.tmplCount = 0;
    this.shortenToLength(1);
  }
  _indexOfTagNames(tagNames, namespace) {
    for (let i3 = this.stackTop; i3 >= 0; i3--) {
      if (tagNames.has(this.tagIDs[i3]) && this.treeAdapter.getNamespaceURI(this.items[i3]) === namespace) {
        return i3;
      }
    }
    return -1;
  }
  clearBackTo(tagNames, targetNS) {
    const idx = this._indexOfTagNames(tagNames, targetNS);
    this.shortenToLength(idx + 1);
  }
  clearBackToTableContext() {
    this.clearBackTo(TABLE_CONTEXT, NS.HTML);
  }
  clearBackToTableBodyContext() {
    this.clearBackTo(TABLE_BODY_CONTEXT, NS.HTML);
  }
  clearBackToTableRowContext() {
    this.clearBackTo(TABLE_ROW_CONTEXT, NS.HTML);
  }
  remove(element7) {
    const idx = this._indexOf(element7);
    if (idx >= 0) {
      if (idx === this.stackTop) {
        this.pop();
      } else {
        this.items.splice(idx, 1);
        this.tagIDs.splice(idx, 1);
        this.stackTop--;
        this._updateCurrentElement();
        this.handler.onItemPop(element7, false);
      }
    }
  }
  //Search
  tryPeekProperlyNestedBodyElement() {
    return this.stackTop >= 1 && this.tagIDs[1] === TAG_ID.BODY ? this.items[1] : null;
  }
  contains(element7) {
    return this._indexOf(element7) > -1;
  }
  getCommonAncestor(element7) {
    const elementIdx = this._indexOf(element7) - 1;
    return elementIdx >= 0 ? this.items[elementIdx] : null;
  }
  isRootHtmlElementCurrent() {
    return this.stackTop === 0 && this.tagIDs[0] === TAG_ID.HTML;
  }
  //Element in scope
  hasInDynamicScope(tagName, htmlScope) {
    for (let i3 = this.stackTop; i3 >= 0; i3--) {
      const tn4 = this.tagIDs[i3];
      switch (this.treeAdapter.getNamespaceURI(this.items[i3])) {
        case NS.HTML: {
          if (tn4 === tagName)
            return true;
          if (htmlScope.has(tn4))
            return false;
          break;
        }
        case NS.SVG: {
          if (SCOPING_ELEMENTS_SVG.has(tn4))
            return false;
          break;
        }
        case NS.MATHML: {
          if (SCOPING_ELEMENTS_MATHML.has(tn4))
            return false;
          break;
        }
      }
    }
    return true;
  }
  hasInScope(tagName) {
    return this.hasInDynamicScope(tagName, SCOPING_ELEMENTS_HTML);
  }
  hasInListItemScope(tagName) {
    return this.hasInDynamicScope(tagName, SCOPING_ELEMENTS_HTML_LIST);
  }
  hasInButtonScope(tagName) {
    return this.hasInDynamicScope(tagName, SCOPING_ELEMENTS_HTML_BUTTON);
  }
  hasNumberedHeaderInScope() {
    for (let i3 = this.stackTop; i3 >= 0; i3--) {
      const tn4 = this.tagIDs[i3];
      switch (this.treeAdapter.getNamespaceURI(this.items[i3])) {
        case NS.HTML: {
          if (NUMBERED_HEADERS.has(tn4))
            return true;
          if (SCOPING_ELEMENTS_HTML.has(tn4))
            return false;
          break;
        }
        case NS.SVG: {
          if (SCOPING_ELEMENTS_SVG.has(tn4))
            return false;
          break;
        }
        case NS.MATHML: {
          if (SCOPING_ELEMENTS_MATHML.has(tn4))
            return false;
          break;
        }
      }
    }
    return true;
  }
  hasInTableScope(tagName) {
    for (let i3 = this.stackTop; i3 >= 0; i3--) {
      if (this.treeAdapter.getNamespaceURI(this.items[i3]) !== NS.HTML) {
        continue;
      }
      switch (this.tagIDs[i3]) {
        case tagName: {
          return true;
        }
        case TAG_ID.TABLE:
        case TAG_ID.HTML: {
          return false;
        }
      }
    }
    return true;
  }
  hasTableBodyContextInTableScope() {
    for (let i3 = this.stackTop; i3 >= 0; i3--) {
      if (this.treeAdapter.getNamespaceURI(this.items[i3]) !== NS.HTML) {
        continue;
      }
      switch (this.tagIDs[i3]) {
        case TAG_ID.TBODY:
        case TAG_ID.THEAD:
        case TAG_ID.TFOOT: {
          return true;
        }
        case TAG_ID.TABLE:
        case TAG_ID.HTML: {
          return false;
        }
      }
    }
    return true;
  }
  hasInSelectScope(tagName) {
    for (let i3 = this.stackTop; i3 >= 0; i3--) {
      if (this.treeAdapter.getNamespaceURI(this.items[i3]) !== NS.HTML) {
        continue;
      }
      switch (this.tagIDs[i3]) {
        case tagName: {
          return true;
        }
        case TAG_ID.OPTION:
        case TAG_ID.OPTGROUP: {
          break;
        }
        default: {
          return false;
        }
      }
    }
    return true;
  }
  //Implied end tags
  generateImpliedEndTags() {
    while (this.currentTagId !== void 0 && IMPLICIT_END_TAG_REQUIRED.has(this.currentTagId)) {
      this.pop();
    }
  }
  generateImpliedEndTagsThoroughly() {
    while (this.currentTagId !== void 0 && IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)) {
      this.pop();
    }
  }
  generateImpliedEndTagsWithExclusion(exclusionId) {
    while (this.currentTagId !== void 0 && this.currentTagId !== exclusionId && IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId)) {
      this.pop();
    }
  }
};

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/parser/formatting-element-list.js
var NOAH_ARK_CAPACITY = 3;
var EntryType;
(function(EntryType2) {
  EntryType2[EntryType2["Marker"] = 0] = "Marker";
  EntryType2[EntryType2["Element"] = 1] = "Element";
})(EntryType || (EntryType = {}));
var MARKER = { type: EntryType.Marker };
var FormattingElementList = class {
  constructor(treeAdapter) {
    this.treeAdapter = treeAdapter;
    this.entries = [];
    this.bookmark = null;
  }
  //Noah Ark's condition
  //OPTIMIZATION: at first we try to find possible candidates for exclusion using
  //lightweight heuristics without thorough attributes check.
  _getNoahArkConditionCandidates(newElement, neAttrs) {
    const candidates = [];
    const neAttrsLength = neAttrs.length;
    const neTagName = this.treeAdapter.getTagName(newElement);
    const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement);
    for (let i3 = 0; i3 < this.entries.length; i3++) {
      const entry = this.entries[i3];
      if (entry.type === EntryType.Marker) {
        break;
      }
      const { element: element7 } = entry;
      if (this.treeAdapter.getTagName(element7) === neTagName && this.treeAdapter.getNamespaceURI(element7) === neNamespaceURI) {
        const elementAttrs = this.treeAdapter.getAttrList(element7);
        if (elementAttrs.length === neAttrsLength) {
          candidates.push({ idx: i3, attrs: elementAttrs });
        }
      }
    }
    return candidates;
  }
  _ensureNoahArkCondition(newElement) {
    if (this.entries.length < NOAH_ARK_CAPACITY)
      return;
    const neAttrs = this.treeAdapter.getAttrList(newElement);
    const candidates = this._getNoahArkConditionCandidates(newElement, neAttrs);
    if (candidates.length < NOAH_ARK_CAPACITY)
      return;
    const neAttrsMap = new Map(neAttrs.map((neAttr) => [neAttr.name, neAttr.value]));
    let validCandidates = 0;
    for (let i3 = 0; i3 < candidates.length; i3++) {
      const candidate = candidates[i3];
      if (candidate.attrs.every((cAttr) => neAttrsMap.get(cAttr.name) === cAttr.value)) {
        validCandidates += 1;
        if (validCandidates >= NOAH_ARK_CAPACITY) {
          this.entries.splice(candidate.idx, 1);
        }
      }
    }
  }
  //Mutations
  insertMarker() {
    this.entries.unshift(MARKER);
  }
  pushElement(element7, token) {
    this._ensureNoahArkCondition(element7);
    this.entries.unshift({
      type: EntryType.Element,
      element: element7,
      token
    });
  }
  insertElementAfterBookmark(element7, token) {
    const bookmarkIdx = this.entries.indexOf(this.bookmark);
    this.entries.splice(bookmarkIdx, 0, {
      type: EntryType.Element,
      element: element7,
      token
    });
  }
  removeEntry(entry) {
    const entryIndex = this.entries.indexOf(entry);
    if (entryIndex !== -1) {
      this.entries.splice(entryIndex, 1);
    }
  }
  /**
   * Clears the list of formatting elements up to the last marker.
   *
   * @see https://html.spec.whatwg.org/multipage/parsing.html#clear-the-list-of-active-formatting-elements-up-to-the-last-marker
   */
  clearToLastMarker() {
    const markerIdx = this.entries.indexOf(MARKER);
    if (markerIdx === -1) {
      this.entries.length = 0;
    } else {
      this.entries.splice(0, markerIdx + 1);
    }
  }
  //Search
  getElementEntryInScopeWithTagName(tagName) {
    const entry = this.entries.find((entry2) => entry2.type === EntryType.Marker || this.treeAdapter.getTagName(entry2.element) === tagName);
    return entry && entry.type === EntryType.Element ? entry : null;
  }
  getElementEntry(element7) {
    return this.entries.find((entry) => entry.type === EntryType.Element && entry.element === element7);
  }
};

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/tree-adapters/default.js
var defaultTreeAdapter = {
  //Node construction
  createDocument() {
    return {
      nodeName: "#document",
      mode: DOCUMENT_MODE.NO_QUIRKS,
      childNodes: []
    };
  },
  createDocumentFragment() {
    return {
      nodeName: "#document-fragment",
      childNodes: []
    };
  },
  createElement(tagName, namespaceURI, attrs) {
    return {
      nodeName: tagName,
      tagName,
      attrs,
      namespaceURI,
      childNodes: [],
      parentNode: null
    };
  },
  createCommentNode(data) {
    return {
      nodeName: "#comment",
      data,
      parentNode: null
    };
  },
  createTextNode(value) {
    return {
      nodeName: "#text",
      value,
      parentNode: null
    };
  },
  //Tree mutation
  appendChild(parentNode2, newNode) {
    parentNode2.childNodes.push(newNode);
    newNode.parentNode = parentNode2;
  },
  insertBefore(parentNode2, newNode, referenceNode) {
    const insertionIdx = parentNode2.childNodes.indexOf(referenceNode);
    parentNode2.childNodes.splice(insertionIdx, 0, newNode);
    newNode.parentNode = parentNode2;
  },
  setTemplateContent(templateElement, contentElement) {
    templateElement.content = contentElement;
  },
  getTemplateContent(templateElement) {
    return templateElement.content;
  },
  setDocumentType(document4, name, publicId, systemId) {
    const doctypeNode = document4.childNodes.find((node2) => node2.nodeName === "#documentType");
    if (doctypeNode) {
      doctypeNode.name = name;
      doctypeNode.publicId = publicId;
      doctypeNode.systemId = systemId;
    } else {
      const node2 = {
        nodeName: "#documentType",
        name,
        publicId,
        systemId,
        parentNode: null
      };
      defaultTreeAdapter.appendChild(document4, node2);
    }
  },
  setDocumentMode(document4, mode) {
    document4.mode = mode;
  },
  getDocumentMode(document4) {
    return document4.mode;
  },
  detachNode(node2) {
    if (node2.parentNode) {
      const idx = node2.parentNode.childNodes.indexOf(node2);
      node2.parentNode.childNodes.splice(idx, 1);
      node2.parentNode = null;
    }
  },
  insertText(parentNode2, text10) {
    if (parentNode2.childNodes.length > 0) {
      const prevNode = parentNode2.childNodes[parentNode2.childNodes.length - 1];
      if (defaultTreeAdapter.isTextNode(prevNode)) {
        prevNode.value += text10;
        return;
      }
    }
    defaultTreeAdapter.appendChild(parentNode2, defaultTreeAdapter.createTextNode(text10));
  },
  insertTextBefore(parentNode2, text10, referenceNode) {
    const prevNode = parentNode2.childNodes[parentNode2.childNodes.indexOf(referenceNode) - 1];
    if (prevNode && defaultTreeAdapter.isTextNode(prevNode)) {
      prevNode.value += text10;
    } else {
      defaultTreeAdapter.insertBefore(parentNode2, defaultTreeAdapter.createTextNode(text10), referenceNode);
    }
  },
  adoptAttributes(recipient, attrs) {
    const recipientAttrsMap = new Set(recipient.attrs.map((attr2) => attr2.name));
    for (let j4 = 0; j4 < attrs.length; j4++) {
      if (!recipientAttrsMap.has(attrs[j4].name)) {
        recipient.attrs.push(attrs[j4]);
      }
    }
  },
  //Tree traversing
  getFirstChild(node2) {
    return node2.childNodes[0];
  },
  getChildNodes(node2) {
    return node2.childNodes;
  },
  getParentNode(node2) {
    return node2.parentNode;
  },
  getAttrList(element7) {
    return element7.attrs;
  },
  //Node data
  getTagName(element7) {
    return element7.tagName;
  },
  getNamespaceURI(element7) {
    return element7.namespaceURI;
  },
  getTextNodeContent(textNode) {
    return textNode.value;
  },
  getCommentNodeContent(commentNode) {
    return commentNode.data;
  },
  getDocumentTypeNodeName(doctypeNode) {
    return doctypeNode.name;
  },
  getDocumentTypeNodePublicId(doctypeNode) {
    return doctypeNode.publicId;
  },
  getDocumentTypeNodeSystemId(doctypeNode) {
    return doctypeNode.systemId;
  },
  //Node types
  isTextNode(node2) {
    return node2.nodeName === "#text";
  },
  isCommentNode(node2) {
    return node2.nodeName === "#comment";
  },
  isDocumentTypeNode(node2) {
    return node2.nodeName === "#documentType";
  },
  isElementNode(node2) {
    return Object.prototype.hasOwnProperty.call(node2, "tagName");
  },
  // Source code location
  setNodeSourceCodeLocation(node2, location3) {
    node2.sourceCodeLocation = location3;
  },
  getNodeSourceCodeLocation(node2) {
    return node2.sourceCodeLocation;
  },
  updateNodeSourceCodeLocation(node2, endLocation) {
    node2.sourceCodeLocation = { ...node2.sourceCodeLocation, ...endLocation };
  }
};

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/common/doctype.js
var VALID_DOCTYPE_NAME = "html";
var VALID_SYSTEM_ID = "about:legacy-compat";
var QUIRKS_MODE_SYSTEM_ID = "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd";
var QUIRKS_MODE_PUBLIC_ID_PREFIXES = [
  "+//silmaril//dtd html pro v0r11 19970101//",
  "-//as//dtd html 3.0 aswedit + extensions//",
  "-//advasoft ltd//dtd html 3.0 aswedit + extensions//",
  "-//ietf//dtd html 2.0 level 1//",
  "-//ietf//dtd html 2.0 level 2//",
  "-//ietf//dtd html 2.0 strict level 1//",
  "-//ietf//dtd html 2.0 strict level 2//",
  "-//ietf//dtd html 2.0 strict//",
  "-//ietf//dtd html 2.0//",
  "-//ietf//dtd html 2.1e//",
  "-//ietf//dtd html 3.0//",
  "-//ietf//dtd html 3.2 final//",
  "-//ietf//dtd html 3.2//",
  "-//ietf//dtd html 3//",
  "-//ietf//dtd html level 0//",
  "-//ietf//dtd html level 1//",
  "-//ietf//dtd html level 2//",
  "-//ietf//dtd html level 3//",
  "-//ietf//dtd html strict level 0//",
  "-//ietf//dtd html strict level 1//",
  "-//ietf//dtd html strict level 2//",
  "-//ietf//dtd html strict level 3//",
  "-//ietf//dtd html strict//",
  "-//ietf//dtd html//",
  "-//metrius//dtd metrius presentational//",
  "-//microsoft//dtd internet explorer 2.0 html strict//",
  "-//microsoft//dtd internet explorer 2.0 html//",
  "-//microsoft//dtd internet explorer 2.0 tables//",
  "-//microsoft//dtd internet explorer 3.0 html strict//",
  "-//microsoft//dtd internet explorer 3.0 html//",
  "-//microsoft//dtd internet explorer 3.0 tables//",
  "-//netscape comm. corp.//dtd html//",
  "-//netscape comm. corp.//dtd strict html//",
  "-//o'reilly and associates//dtd html 2.0//",
  "-//o'reilly and associates//dtd html extended 1.0//",
  "-//o'reilly and associates//dtd html extended relaxed 1.0//",
  "-//sq//dtd html 2.0 hotmetal + extensions//",
  "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//",
  "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//",
  "-//spyglass//dtd html 2.0 extended//",
  "-//sun microsystems corp.//dtd hotjava html//",
  "-//sun microsystems corp.//dtd hotjava strict html//",
  "-//w3c//dtd html 3 1995-03-24//",
  "-//w3c//dtd html 3.2 draft//",
  "-//w3c//dtd html 3.2 final//",
  "-//w3c//dtd html 3.2//",
  "-//w3c//dtd html 3.2s draft//",
  "-//w3c//dtd html 4.0 frameset//",
  "-//w3c//dtd html 4.0 transitional//",
  "-//w3c//dtd html experimental 19960712//",
  "-//w3c//dtd html experimental 970421//",
  "-//w3c//dtd w3 html//",
  "-//w3o//dtd w3 html 3.0//",
  "-//webtechs//dtd mozilla html 2.0//",
  "-//webtechs//dtd mozilla html//"
];
var QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = [
  ...QUIRKS_MODE_PUBLIC_ID_PREFIXES,
  "-//w3c//dtd html 4.01 frameset//",
  "-//w3c//dtd html 4.01 transitional//"
];
var QUIRKS_MODE_PUBLIC_IDS = /* @__PURE__ */ new Set([
  "-//w3o//dtd w3 html strict 3.0//en//",
  "-/w3c/dtd html 4.0 transitional/en",
  "html"
]);
var LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ["-//w3c//dtd xhtml 1.0 frameset//", "-//w3c//dtd xhtml 1.0 transitional//"];
var LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = [
  ...LIMITED_QUIRKS_PUBLIC_ID_PREFIXES,
  "-//w3c//dtd html 4.01 frameset//",
  "-//w3c//dtd html 4.01 transitional//"
];
function hasPrefix(publicId, prefixes) {
  return prefixes.some((prefix3) => publicId.startsWith(prefix3));
}
function isConforming(token) {
  return token.name === VALID_DOCTYPE_NAME && token.publicId === null && (token.systemId === null || token.systemId === VALID_SYSTEM_ID);
}
function getDocumentMode(token) {
  if (token.name !== VALID_DOCTYPE_NAME) {
    return DOCUMENT_MODE.QUIRKS;
  }
  const { systemId } = token;
  if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) {
    return DOCUMENT_MODE.QUIRKS;
  }
  let { publicId } = token;
  if (publicId !== null) {
    publicId = publicId.toLowerCase();
    if (QUIRKS_MODE_PUBLIC_IDS.has(publicId)) {
      return DOCUMENT_MODE.QUIRKS;
    }
    let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES;
    if (hasPrefix(publicId, prefixes)) {
      return DOCUMENT_MODE.QUIRKS;
    }
    prefixes = systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES;
    if (hasPrefix(publicId, prefixes)) {
      return DOCUMENT_MODE.LIMITED_QUIRKS;
    }
  }
  return DOCUMENT_MODE.NO_QUIRKS;
}

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/common/foreign-content.js
var foreign_content_exports = {};
__export(foreign_content_exports, {
  SVG_TAG_NAMES_ADJUSTMENT_MAP: () => SVG_TAG_NAMES_ADJUSTMENT_MAP,
  adjustTokenMathMLAttrs: () => adjustTokenMathMLAttrs,
  adjustTokenSVGAttrs: () => adjustTokenSVGAttrs,
  adjustTokenSVGTagName: () => adjustTokenSVGTagName,
  adjustTokenXMLAttrs: () => adjustTokenXMLAttrs,
  causesExit: () => causesExit,
  isIntegrationPoint: () => isIntegrationPoint
});
var MIME_TYPES = {
  TEXT_HTML: "text/html",
  APPLICATION_XML: "application/xhtml+xml"
};
var DEFINITION_URL_ATTR = "definitionurl";
var ADJUSTED_DEFINITION_URL_ATTR = "definitionURL";
var SVG_ATTRS_ADJUSTMENT_MAP = new Map([
  "attributeName",
  "attributeType",
  "baseFrequency",
  "baseProfile",
  "calcMode",
  "clipPathUnits",
  "diffuseConstant",
  "edgeMode",
  "filterUnits",
  "glyphRef",
  "gradientTransform",
  "gradientUnits",
  "kernelMatrix",
  "kernelUnitLength",
  "keyPoints",
  "keySplines",
  "keyTimes",
  "lengthAdjust",
  "limitingConeAngle",
  "markerHeight",
  "markerUnits",
  "markerWidth",
  "maskContentUnits",
  "maskUnits",
  "numOctaves",
  "pathLength",
  "patternContentUnits",
  "patternTransform",
  "patternUnits",
  "pointsAtX",
  "pointsAtY",
  "pointsAtZ",
  "preserveAlpha",
  "preserveAspectRatio",
  "primitiveUnits",
  "refX",
  "refY",
  "repeatCount",
  "repeatDur",
  "requiredExtensions",
  "requiredFeatures",
  "specularConstant",
  "specularExponent",
  "spreadMethod",
  "startOffset",
  "stdDeviation",
  "stitchTiles",
  "surfaceScale",
  "systemLanguage",
  "tableValues",
  "targetX",
  "targetY",
  "textLength",
  "viewBox",
  "viewTarget",
  "xChannelSelector",
  "yChannelSelector",
  "zoomAndPan"
].map((attr2) => [attr2.toLowerCase(), attr2]));
var XML_ATTRS_ADJUSTMENT_MAP = /* @__PURE__ */ new Map([
  ["xlink:actuate", { prefix: "xlink", name: "actuate", namespace: NS.XLINK }],
  ["xlink:arcrole", { prefix: "xlink", name: "arcrole", namespace: NS.XLINK }],
  ["xlink:href", { prefix: "xlink", name: "href", namespace: NS.XLINK }],
  ["xlink:role", { prefix: "xlink", name: "role", namespace: NS.XLINK }],
  ["xlink:show", { prefix: "xlink", name: "show", namespace: NS.XLINK }],
  ["xlink:title", { prefix: "xlink", name: "title", namespace: NS.XLINK }],
  ["xlink:type", { prefix: "xlink", name: "type", namespace: NS.XLINK }],
  ["xml:lang", { prefix: "xml", name: "lang", namespace: NS.XML }],
  ["xml:space", { prefix: "xml", name: "space", namespace: NS.XML }],
  ["xmlns", { prefix: "", name: "xmlns", namespace: NS.XMLNS }],
  ["xmlns:xlink", { prefix: "xmlns", name: "xlink", namespace: NS.XMLNS }]
]);
var SVG_TAG_NAMES_ADJUSTMENT_MAP = new Map([
  "altGlyph",
  "altGlyphDef",
  "altGlyphItem",
  "animateColor",
  "animateMotion",
  "animateTransform",
  "clipPath",
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feDistantLight",
  "feFlood",
  "feFuncA",
  "feFuncB",
  "feFuncG",
  "feFuncR",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMergeNode",
  "feMorphology",
  "feOffset",
  "fePointLight",
  "feSpecularLighting",
  "feSpotLight",
  "feTile",
  "feTurbulence",
  "foreignObject",
  "glyphRef",
  "linearGradient",
  "radialGradient",
  "textPath"
].map((tn4) => [tn4.toLowerCase(), tn4]));
var EXITS_FOREIGN_CONTENT = /* @__PURE__ */ new Set([
  TAG_ID.B,
  TAG_ID.BIG,
  TAG_ID.BLOCKQUOTE,
  TAG_ID.BODY,
  TAG_ID.BR,
  TAG_ID.CENTER,
  TAG_ID.CODE,
  TAG_ID.DD,
  TAG_ID.DIV,
  TAG_ID.DL,
  TAG_ID.DT,
  TAG_ID.EM,
  TAG_ID.EMBED,
  TAG_ID.H1,
  TAG_ID.H2,
  TAG_ID.H3,
  TAG_ID.H4,
  TAG_ID.H5,
  TAG_ID.H6,
  TAG_ID.HEAD,
  TAG_ID.HR,
  TAG_ID.I,
  TAG_ID.IMG,
  TAG_ID.LI,
  TAG_ID.LISTING,
  TAG_ID.MENU,
  TAG_ID.META,
  TAG_ID.NOBR,
  TAG_ID.OL,
  TAG_ID.P,
  TAG_ID.PRE,
  TAG_ID.RUBY,
  TAG_ID.S,
  TAG_ID.SMALL,
  TAG_ID.SPAN,
  TAG_ID.STRONG,
  TAG_ID.STRIKE,
  TAG_ID.SUB,
  TAG_ID.SUP,
  TAG_ID.TABLE,
  TAG_ID.TT,
  TAG_ID.U,
  TAG_ID.UL,
  TAG_ID.VAR
]);
function causesExit(startTagToken) {
  const tn4 = startTagToken.tagID;
  const isFontWithAttrs = tn4 === TAG_ID.FONT && startTagToken.attrs.some(({ name }) => name === ATTRS.COLOR || name === ATTRS.SIZE || name === ATTRS.FACE);
  return isFontWithAttrs || EXITS_FOREIGN_CONTENT.has(tn4);
}
function adjustTokenMathMLAttrs(token) {
  for (let i3 = 0; i3 < token.attrs.length; i3++) {
    if (token.attrs[i3].name === DEFINITION_URL_ATTR) {
      token.attrs[i3].name = ADJUSTED_DEFINITION_URL_ATTR;
      break;
    }
  }
}
function adjustTokenSVGAttrs(token) {
  for (let i3 = 0; i3 < token.attrs.length; i3++) {
    const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i3].name);
    if (adjustedAttrName != null) {
      token.attrs[i3].name = adjustedAttrName;
    }
  }
}
function adjustTokenXMLAttrs(token) {
  for (let i3 = 0; i3 < token.attrs.length; i3++) {
    const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP.get(token.attrs[i3].name);
    if (adjustedAttrEntry) {
      token.attrs[i3].prefix = adjustedAttrEntry.prefix;
      token.attrs[i3].name = adjustedAttrEntry.name;
      token.attrs[i3].namespace = adjustedAttrEntry.namespace;
    }
  }
}
function adjustTokenSVGTagName(token) {
  const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP.get(token.tagName);
  if (adjustedTagName != null) {
    token.tagName = adjustedTagName;
    token.tagID = getTagID(token.tagName);
  }
}
function isMathMLTextIntegrationPoint(tn4, ns) {
  return ns === NS.MATHML && (tn4 === TAG_ID.MI || tn4 === TAG_ID.MO || tn4 === TAG_ID.MN || tn4 === TAG_ID.MS || tn4 === TAG_ID.MTEXT);
}
function isHtmlIntegrationPoint(tn4, ns, attrs) {
  if (ns === NS.MATHML && tn4 === TAG_ID.ANNOTATION_XML) {
    for (let i3 = 0; i3 < attrs.length; i3++) {
      if (attrs[i3].name === ATTRS.ENCODING) {
        const value = attrs[i3].value.toLowerCase();
        return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML;
      }
    }
  }
  return ns === NS.SVG && (tn4 === TAG_ID.FOREIGN_OBJECT || tn4 === TAG_ID.DESC || tn4 === TAG_ID.TITLE);
}
function isIntegrationPoint(tn4, ns, attrs, foreignNS) {
  return (!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn4, ns, attrs) || (!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn4, ns);
}

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/parser/index.js
var HIDDEN_INPUT_TYPE = "hidden";
var AA_OUTER_LOOP_ITER = 8;
var AA_INNER_LOOP_ITER = 3;
var InsertionMode;
(function(InsertionMode2) {
  InsertionMode2[InsertionMode2["INITIAL"] = 0] = "INITIAL";
  InsertionMode2[InsertionMode2["BEFORE_HTML"] = 1] = "BEFORE_HTML";
  InsertionMode2[InsertionMode2["BEFORE_HEAD"] = 2] = "BEFORE_HEAD";
  InsertionMode2[InsertionMode2["IN_HEAD"] = 3] = "IN_HEAD";
  InsertionMode2[InsertionMode2["IN_HEAD_NO_SCRIPT"] = 4] = "IN_HEAD_NO_SCRIPT";
  InsertionMode2[InsertionMode2["AFTER_HEAD"] = 5] = "AFTER_HEAD";
  InsertionMode2[InsertionMode2["IN_BODY"] = 6] = "IN_BODY";
  InsertionMode2[InsertionMode2["TEXT"] = 7] = "TEXT";
  InsertionMode2[InsertionMode2["IN_TABLE"] = 8] = "IN_TABLE";
  InsertionMode2[InsertionMode2["IN_TABLE_TEXT"] = 9] = "IN_TABLE_TEXT";
  InsertionMode2[InsertionMode2["IN_CAPTION"] = 10] = "IN_CAPTION";
  InsertionMode2[InsertionMode2["IN_COLUMN_GROUP"] = 11] = "IN_COLUMN_GROUP";
  InsertionMode2[InsertionMode2["IN_TABLE_BODY"] = 12] = "IN_TABLE_BODY";
  InsertionMode2[InsertionMode2["IN_ROW"] = 13] = "IN_ROW";
  InsertionMode2[InsertionMode2["IN_CELL"] = 14] = "IN_CELL";
  InsertionMode2[InsertionMode2["IN_SELECT"] = 15] = "IN_SELECT";
  InsertionMode2[InsertionMode2["IN_SELECT_IN_TABLE"] = 16] = "IN_SELECT_IN_TABLE";
  InsertionMode2[InsertionMode2["IN_TEMPLATE"] = 17] = "IN_TEMPLATE";
  InsertionMode2[InsertionMode2["AFTER_BODY"] = 18] = "AFTER_BODY";
  InsertionMode2[InsertionMode2["IN_FRAMESET"] = 19] = "IN_FRAMESET";
  InsertionMode2[InsertionMode2["AFTER_FRAMESET"] = 20] = "AFTER_FRAMESET";
  InsertionMode2[InsertionMode2["AFTER_AFTER_BODY"] = 21] = "AFTER_AFTER_BODY";
  InsertionMode2[InsertionMode2["AFTER_AFTER_FRAMESET"] = 22] = "AFTER_AFTER_FRAMESET";
})(InsertionMode || (InsertionMode = {}));
var BASE_LOC = {
  startLine: -1,
  startCol: -1,
  startOffset: -1,
  endLine: -1,
  endCol: -1,
  endOffset: -1
};
var TABLE_STRUCTURE_TAGS = /* @__PURE__ */ new Set([TAG_ID.TABLE, TAG_ID.TBODY, TAG_ID.TFOOT, TAG_ID.THEAD, TAG_ID.TR]);
var defaultParserOptions = {
  scriptingEnabled: true,
  sourceCodeLocationInfo: false,
  treeAdapter: defaultTreeAdapter,
  onParseError: null
};
var Parser = class {
  constructor(options2, document4, fragmentContext = null, scriptHandler = null) {
    this.fragmentContext = fragmentContext;
    this.scriptHandler = scriptHandler;
    this.currentToken = null;
    this.stopped = false;
    this.insertionMode = InsertionMode.INITIAL;
    this.originalInsertionMode = InsertionMode.INITIAL;
    this.headElement = null;
    this.formElement = null;
    this.currentNotInHTML = false;
    this.tmplInsertionModeStack = [];
    this.pendingCharacterTokens = [];
    this.hasNonWhitespacePendingCharacterToken = false;
    this.framesetOk = true;
    this.skipNextNewLine = false;
    this.fosterParentingEnabled = false;
    this.options = {
      ...defaultParserOptions,
      ...options2
    };
    this.treeAdapter = this.options.treeAdapter;
    this.onParseError = this.options.onParseError;
    if (this.onParseError) {
      this.options.sourceCodeLocationInfo = true;
    }
    this.document = document4 !== null && document4 !== void 0 ? document4 : this.treeAdapter.createDocument();
    this.tokenizer = new Tokenizer(this.options, this);
    this.activeFormattingElements = new FormattingElementList(this.treeAdapter);
    this.fragmentContextID = fragmentContext ? getTagID(this.treeAdapter.getTagName(fragmentContext)) : TAG_ID.UNKNOWN;
    this._setContextModes(fragmentContext !== null && fragmentContext !== void 0 ? fragmentContext : this.document, this.fragmentContextID);
    this.openElements = new OpenElementStack(this.document, this.treeAdapter, this);
  }
  // API
  static parse(html7, options2) {
    const parser = new this(options2);
    parser.tokenizer.write(html7, true);
    return parser.document;
  }
  static getFragmentParser(fragmentContext, options2) {
    const opts = {
      ...defaultParserOptions,
      ...options2
    };
    fragmentContext !== null && fragmentContext !== void 0 ? fragmentContext : fragmentContext = opts.treeAdapter.createElement(TAG_NAMES.TEMPLATE, NS.HTML, []);
    const documentMock = opts.treeAdapter.createElement("documentmock", NS.HTML, []);
    const parser = new this(opts, documentMock, fragmentContext);
    if (parser.fragmentContextID === TAG_ID.TEMPLATE) {
      parser.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE);
    }
    parser._initTokenizerForFragmentParsing();
    parser._insertFakeRootElement();
    parser._resetInsertionMode();
    parser._findFormInFragmentContext();
    return parser;
  }
  getFragment() {
    const rootElement = this.treeAdapter.getFirstChild(this.document);
    const fragment = this.treeAdapter.createDocumentFragment();
    this._adoptNodes(rootElement, fragment);
    return fragment;
  }
  //Errors
  /** @internal */
  _err(token, code5, beforeToken) {
    var _a2;
    if (!this.onParseError)
      return;
    const loc = (_a2 = token.location) !== null && _a2 !== void 0 ? _a2 : BASE_LOC;
    const err = {
      code: code5,
      startLine: loc.startLine,
      startCol: loc.startCol,
      startOffset: loc.startOffset,
      endLine: beforeToken ? loc.startLine : loc.endLine,
      endCol: beforeToken ? loc.startCol : loc.endCol,
      endOffset: beforeToken ? loc.startOffset : loc.endOffset
    };
    this.onParseError(err);
  }
  //Stack events
  /** @internal */
  onItemPush(node2, tid, isTop) {
    var _a2, _b;
    (_b = (_a2 = this.treeAdapter).onItemPush) === null || _b === void 0 ? void 0 : _b.call(_a2, node2);
    if (isTop && this.openElements.stackTop > 0)
      this._setContextModes(node2, tid);
  }
  /** @internal */
  onItemPop(node2, isTop) {
    var _a2, _b;
    if (this.options.sourceCodeLocationInfo) {
      this._setEndLocation(node2, this.currentToken);
    }
    (_b = (_a2 = this.treeAdapter).onItemPop) === null || _b === void 0 ? void 0 : _b.call(_a2, node2, this.openElements.current);
    if (isTop) {
      let current;
      let currentTagId;
      if (this.openElements.stackTop === 0 && this.fragmentContext) {
        current = this.fragmentContext;
        currentTagId = this.fragmentContextID;
      } else {
        ({ current, currentTagId } = this.openElements);
      }
      this._setContextModes(current, currentTagId);
    }
  }
  _setContextModes(current, tid) {
    const isHTML = current === this.document || current && this.treeAdapter.getNamespaceURI(current) === NS.HTML;
    this.currentNotInHTML = !isHTML;
    this.tokenizer.inForeignNode = !isHTML && current !== void 0 && tid !== void 0 && !this._isIntegrationPoint(tid, current);
  }
  /** @protected */
  _switchToTextParsing(currentToken, nextTokenizerState) {
    this._insertElement(currentToken, NS.HTML);
    this.tokenizer.state = nextTokenizerState;
    this.originalInsertionMode = this.insertionMode;
    this.insertionMode = InsertionMode.TEXT;
  }
  switchToPlaintextParsing() {
    this.insertionMode = InsertionMode.TEXT;
    this.originalInsertionMode = InsertionMode.IN_BODY;
    this.tokenizer.state = TokenizerMode.PLAINTEXT;
  }
  //Fragment parsing
  /** @protected */
  _getAdjustedCurrentElement() {
    return this.openElements.stackTop === 0 && this.fragmentContext ? this.fragmentContext : this.openElements.current;
  }
  /** @protected */
  _findFormInFragmentContext() {
    let node2 = this.fragmentContext;
    while (node2) {
      if (this.treeAdapter.getTagName(node2) === TAG_NAMES.FORM) {
        this.formElement = node2;
        break;
      }
      node2 = this.treeAdapter.getParentNode(node2);
    }
  }
  _initTokenizerForFragmentParsing() {
    if (!this.fragmentContext || this.treeAdapter.getNamespaceURI(this.fragmentContext) !== NS.HTML) {
      return;
    }
    switch (this.fragmentContextID) {
      case TAG_ID.TITLE:
      case TAG_ID.TEXTAREA: {
        this.tokenizer.state = TokenizerMode.RCDATA;
        break;
      }
      case TAG_ID.STYLE:
      case TAG_ID.XMP:
      case TAG_ID.IFRAME:
      case TAG_ID.NOEMBED:
      case TAG_ID.NOFRAMES:
      case TAG_ID.NOSCRIPT: {
        this.tokenizer.state = TokenizerMode.RAWTEXT;
        break;
      }
      case TAG_ID.SCRIPT: {
        this.tokenizer.state = TokenizerMode.SCRIPT_DATA;
        break;
      }
      case TAG_ID.PLAINTEXT: {
        this.tokenizer.state = TokenizerMode.PLAINTEXT;
        break;
      }
      default:
    }
  }
  //Tree mutation
  /** @protected */
  _setDocumentType(token) {
    const name = token.name || "";
    const publicId = token.publicId || "";
    const systemId = token.systemId || "";
    this.treeAdapter.setDocumentType(this.document, name, publicId, systemId);
    if (token.location) {
      const documentChildren = this.treeAdapter.getChildNodes(this.document);
      const docTypeNode = documentChildren.find((node2) => this.treeAdapter.isDocumentTypeNode(node2));
      if (docTypeNode) {
        this.treeAdapter.setNodeSourceCodeLocation(docTypeNode, token.location);
      }
    }
  }
  /** @protected */
  _attachElementToTree(element7, location3) {
    if (this.options.sourceCodeLocationInfo) {
      const loc = location3 && {
        ...location3,
        startTag: location3
      };
      this.treeAdapter.setNodeSourceCodeLocation(element7, loc);
    }
    if (this._shouldFosterParentOnInsertion()) {
      this._fosterParentElement(element7);
    } else {
      const parent = this.openElements.currentTmplContentOrNode;
      this.treeAdapter.appendChild(parent !== null && parent !== void 0 ? parent : this.document, element7);
    }
  }
  /**
   * For self-closing tags. Add an element to the tree, but skip adding it
   * to the stack.
   */
  /** @protected */
  _appendElement(token, namespaceURI) {
    const element7 = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs);
    this._attachElementToTree(element7, token.location);
  }
  /** @protected */
  _insertElement(token, namespaceURI) {
    const element7 = this.treeAdapter.createElement(token.tagName, namespaceURI, token.attrs);
    this._attachElementToTree(element7, token.location);
    this.openElements.push(element7, token.tagID);
  }
  /** @protected */
  _insertFakeElement(tagName, tagID) {
    const element7 = this.treeAdapter.createElement(tagName, NS.HTML, []);
    this._attachElementToTree(element7, null);
    this.openElements.push(element7, tagID);
  }
  /** @protected */
  _insertTemplate(token) {
    const tmpl = this.treeAdapter.createElement(token.tagName, NS.HTML, token.attrs);
    const content5 = this.treeAdapter.createDocumentFragment();
    this.treeAdapter.setTemplateContent(tmpl, content5);
    this._attachElementToTree(tmpl, token.location);
    this.openElements.push(tmpl, token.tagID);
    if (this.options.sourceCodeLocationInfo)
      this.treeAdapter.setNodeSourceCodeLocation(content5, null);
  }
  /** @protected */
  _insertFakeRootElement() {
    const element7 = this.treeAdapter.createElement(TAG_NAMES.HTML, NS.HTML, []);
    if (this.options.sourceCodeLocationInfo)
      this.treeAdapter.setNodeSourceCodeLocation(element7, null);
    this.treeAdapter.appendChild(this.openElements.current, element7);
    this.openElements.push(element7, TAG_ID.HTML);
  }
  /** @protected */
  _appendCommentNode(token, parent) {
    const commentNode = this.treeAdapter.createCommentNode(token.data);
    this.treeAdapter.appendChild(parent, commentNode);
    if (this.options.sourceCodeLocationInfo) {
      this.treeAdapter.setNodeSourceCodeLocation(commentNode, token.location);
    }
  }
  /** @protected */
  _insertCharacters(token) {
    let parent;
    let beforeElement;
    if (this._shouldFosterParentOnInsertion()) {
      ({ parent, beforeElement } = this._findFosterParentingLocation());
      if (beforeElement) {
        this.treeAdapter.insertTextBefore(parent, token.chars, beforeElement);
      } else {
        this.treeAdapter.insertText(parent, token.chars);
      }
    } else {
      parent = this.openElements.currentTmplContentOrNode;
      this.treeAdapter.insertText(parent, token.chars);
    }
    if (!token.location)
      return;
    const siblings2 = this.treeAdapter.getChildNodes(parent);
    const textNodeIdx = beforeElement ? siblings2.lastIndexOf(beforeElement) : siblings2.length;
    const textNode = siblings2[textNodeIdx - 1];
    const tnLoc = this.treeAdapter.getNodeSourceCodeLocation(textNode);
    if (tnLoc) {
      const { endLine, endCol, endOffset } = token.location;
      this.treeAdapter.updateNodeSourceCodeLocation(textNode, { endLine, endCol, endOffset });
    } else if (this.options.sourceCodeLocationInfo) {
      this.treeAdapter.setNodeSourceCodeLocation(textNode, token.location);
    }
  }
  /** @protected */
  _adoptNodes(donor, recipient) {
    for (let child = this.treeAdapter.getFirstChild(donor); child; child = this.treeAdapter.getFirstChild(donor)) {
      this.treeAdapter.detachNode(child);
      this.treeAdapter.appendChild(recipient, child);
    }
  }
  /** @protected */
  _setEndLocation(element7, closingToken) {
    if (this.treeAdapter.getNodeSourceCodeLocation(element7) && closingToken.location) {
      const ctLoc = closingToken.location;
      const tn4 = this.treeAdapter.getTagName(element7);
      const endLoc = (
        // NOTE: For cases like <p> <p> </p> - First 'p' closes without a closing
        // tag and for cases like <td> <p> </td> - 'p' closes without a closing tag.
        closingToken.type === TokenType.END_TAG && tn4 === closingToken.tagName ? {
          endTag: { ...ctLoc },
          endLine: ctLoc.endLine,
          endCol: ctLoc.endCol,
          endOffset: ctLoc.endOffset
        } : {
          endLine: ctLoc.startLine,
          endCol: ctLoc.startCol,
          endOffset: ctLoc.startOffset
        }
      );
      this.treeAdapter.updateNodeSourceCodeLocation(element7, endLoc);
    }
  }
  //Token processing
  shouldProcessStartTagTokenInForeignContent(token) {
    if (!this.currentNotInHTML)
      return false;
    let current;
    let currentTagId;
    if (this.openElements.stackTop === 0 && this.fragmentContext) {
      current = this.fragmentContext;
      currentTagId = this.fragmentContextID;
    } else {
      ({ current, currentTagId } = this.openElements);
    }
    if (token.tagID === TAG_ID.SVG && this.treeAdapter.getTagName(current) === TAG_NAMES.ANNOTATION_XML && this.treeAdapter.getNamespaceURI(current) === NS.MATHML) {
      return false;
    }
    return (
      // Check that `current` is not an integration point for HTML or MathML elements.
      this.tokenizer.inForeignNode || // If it _is_ an integration point, then we might have to check that it is not an HTML
      // integration point.
      (token.tagID === TAG_ID.MGLYPH || token.tagID === TAG_ID.MALIGNMARK) && currentTagId !== void 0 && !this._isIntegrationPoint(currentTagId, current, NS.HTML)
    );
  }
  /** @protected */
  _processToken(token) {
    switch (token.type) {
      case TokenType.CHARACTER: {
        this.onCharacter(token);
        break;
      }
      case TokenType.NULL_CHARACTER: {
        this.onNullCharacter(token);
        break;
      }
      case TokenType.COMMENT: {
        this.onComment(token);
        break;
      }
      case TokenType.DOCTYPE: {
        this.onDoctype(token);
        break;
      }
      case TokenType.START_TAG: {
        this._processStartTag(token);
        break;
      }
      case TokenType.END_TAG: {
        this.onEndTag(token);
        break;
      }
      case TokenType.EOF: {
        this.onEof(token);
        break;
      }
      case TokenType.WHITESPACE_CHARACTER: {
        this.onWhitespaceCharacter(token);
        break;
      }
    }
  }
  //Integration points
  /** @protected */
  _isIntegrationPoint(tid, element7, foreignNS) {
    const ns = this.treeAdapter.getNamespaceURI(element7);
    const attrs = this.treeAdapter.getAttrList(element7);
    return isIntegrationPoint(tid, ns, attrs, foreignNS);
  }
  //Active formatting elements reconstruction
  /** @protected */
  _reconstructActiveFormattingElements() {
    const listLength = this.activeFormattingElements.entries.length;
    if (listLength) {
      const endIndex = this.activeFormattingElements.entries.findIndex((entry) => entry.type === EntryType.Marker || this.openElements.contains(entry.element));
      const unopenIdx = endIndex === -1 ? listLength - 1 : endIndex - 1;
      for (let i3 = unopenIdx; i3 >= 0; i3--) {
        const entry = this.activeFormattingElements.entries[i3];
        this._insertElement(entry.token, this.treeAdapter.getNamespaceURI(entry.element));
        entry.element = this.openElements.current;
      }
    }
  }
  //Close elements
  /** @protected */
  _closeTableCell() {
    this.openElements.generateImpliedEndTags();
    this.openElements.popUntilTableCellPopped();
    this.activeFormattingElements.clearToLastMarker();
    this.insertionMode = InsertionMode.IN_ROW;
  }
  /** @protected */
  _closePElement() {
    this.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.P);
    this.openElements.popUntilTagNamePopped(TAG_ID.P);
  }
  //Insertion modes
  /** @protected */
  _resetInsertionMode() {
    for (let i3 = this.openElements.stackTop; i3 >= 0; i3--) {
      switch (i3 === 0 && this.fragmentContext ? this.fragmentContextID : this.openElements.tagIDs[i3]) {
        case TAG_ID.TR: {
          this.insertionMode = InsertionMode.IN_ROW;
          return;
        }
        case TAG_ID.TBODY:
        case TAG_ID.THEAD:
        case TAG_ID.TFOOT: {
          this.insertionMode = InsertionMode.IN_TABLE_BODY;
          return;
        }
        case TAG_ID.CAPTION: {
          this.insertionMode = InsertionMode.IN_CAPTION;
          return;
        }
        case TAG_ID.COLGROUP: {
          this.insertionMode = InsertionMode.IN_COLUMN_GROUP;
          return;
        }
        case TAG_ID.TABLE: {
          this.insertionMode = InsertionMode.IN_TABLE;
          return;
        }
        case TAG_ID.BODY: {
          this.insertionMode = InsertionMode.IN_BODY;
          return;
        }
        case TAG_ID.FRAMESET: {
          this.insertionMode = InsertionMode.IN_FRAMESET;
          return;
        }
        case TAG_ID.SELECT: {
          this._resetInsertionModeForSelect(i3);
          return;
        }
        case TAG_ID.TEMPLATE: {
          this.insertionMode = this.tmplInsertionModeStack[0];
          return;
        }
        case TAG_ID.HTML: {
          this.insertionMode = this.headElement ? InsertionMode.AFTER_HEAD : InsertionMode.BEFORE_HEAD;
          return;
        }
        case TAG_ID.TD:
        case TAG_ID.TH: {
          if (i3 > 0) {
            this.insertionMode = InsertionMode.IN_CELL;
            return;
          }
          break;
        }
        case TAG_ID.HEAD: {
          if (i3 > 0) {
            this.insertionMode = InsertionMode.IN_HEAD;
            return;
          }
          break;
        }
      }
    }
    this.insertionMode = InsertionMode.IN_BODY;
  }
  /** @protected */
  _resetInsertionModeForSelect(selectIdx) {
    if (selectIdx > 0) {
      for (let i3 = selectIdx - 1; i3 > 0; i3--) {
        const tn4 = this.openElements.tagIDs[i3];
        if (tn4 === TAG_ID.TEMPLATE) {
          break;
        } else if (tn4 === TAG_ID.TABLE) {
          this.insertionMode = InsertionMode.IN_SELECT_IN_TABLE;
          return;
        }
      }
    }
    this.insertionMode = InsertionMode.IN_SELECT;
  }
  //Foster parenting
  /** @protected */
  _isElementCausesFosterParenting(tn4) {
    return TABLE_STRUCTURE_TAGS.has(tn4);
  }
  /** @protected */
  _shouldFosterParentOnInsertion() {
    return this.fosterParentingEnabled && this.openElements.currentTagId !== void 0 && this._isElementCausesFosterParenting(this.openElements.currentTagId);
  }
  /** @protected */
  _findFosterParentingLocation() {
    for (let i3 = this.openElements.stackTop; i3 >= 0; i3--) {
      const openElement = this.openElements.items[i3];
      switch (this.openElements.tagIDs[i3]) {
        case TAG_ID.TEMPLATE: {
          if (this.treeAdapter.getNamespaceURI(openElement) === NS.HTML) {
            return { parent: this.treeAdapter.getTemplateContent(openElement), beforeElement: null };
          }
          break;
        }
        case TAG_ID.TABLE: {
          const parent = this.treeAdapter.getParentNode(openElement);
          if (parent) {
            return { parent, beforeElement: openElement };
          }
          return { parent: this.openElements.items[i3 - 1], beforeElement: null };
        }
        default:
      }
    }
    return { parent: this.openElements.items[0], beforeElement: null };
  }
  /** @protected */
  _fosterParentElement(element7) {
    const location3 = this._findFosterParentingLocation();
    if (location3.beforeElement) {
      this.treeAdapter.insertBefore(location3.parent, element7, location3.beforeElement);
    } else {
      this.treeAdapter.appendChild(location3.parent, element7);
    }
  }
  //Special elements
  /** @protected */
  _isSpecialElement(element7, id2) {
    const ns = this.treeAdapter.getNamespaceURI(element7);
    return SPECIAL_ELEMENTS[ns].has(id2);
  }
  /** @internal */
  onCharacter(token) {
    this.skipNextNewLine = false;
    if (this.tokenizer.inForeignNode) {
      characterInForeignContent(this, token);
      return;
    }
    switch (this.insertionMode) {
      case InsertionMode.INITIAL: {
        tokenInInitialMode(this, token);
        break;
      }
      case InsertionMode.BEFORE_HTML: {
        tokenBeforeHtml(this, token);
        break;
      }
      case InsertionMode.BEFORE_HEAD: {
        tokenBeforeHead(this, token);
        break;
      }
      case InsertionMode.IN_HEAD: {
        tokenInHead(this, token);
        break;
      }
      case InsertionMode.IN_HEAD_NO_SCRIPT: {
        tokenInHeadNoScript(this, token);
        break;
      }
      case InsertionMode.AFTER_HEAD: {
        tokenAfterHead(this, token);
        break;
      }
      case InsertionMode.IN_BODY:
      case InsertionMode.IN_CAPTION:
      case InsertionMode.IN_CELL:
      case InsertionMode.IN_TEMPLATE: {
        characterInBody(this, token);
        break;
      }
      case InsertionMode.TEXT:
      case InsertionMode.IN_SELECT:
      case InsertionMode.IN_SELECT_IN_TABLE: {
        this._insertCharacters(token);
        break;
      }
      case InsertionMode.IN_TABLE:
      case InsertionMode.IN_TABLE_BODY:
      case InsertionMode.IN_ROW: {
        characterInTable(this, token);
        break;
      }
      case InsertionMode.IN_TABLE_TEXT: {
        characterInTableText(this, token);
        break;
      }
      case InsertionMode.IN_COLUMN_GROUP: {
        tokenInColumnGroup(this, token);
        break;
      }
      case InsertionMode.AFTER_BODY: {
        tokenAfterBody(this, token);
        break;
      }
      case InsertionMode.AFTER_AFTER_BODY: {
        tokenAfterAfterBody(this, token);
        break;
      }
      default:
    }
  }
  /** @internal */
  onNullCharacter(token) {
    this.skipNextNewLine = false;
    if (this.tokenizer.inForeignNode) {
      nullCharacterInForeignContent(this, token);
      return;
    }
    switch (this.insertionMode) {
      case InsertionMode.INITIAL: {
        tokenInInitialMode(this, token);
        break;
      }
      case InsertionMode.BEFORE_HTML: {
        tokenBeforeHtml(this, token);
        break;
      }
      case InsertionMode.BEFORE_HEAD: {
        tokenBeforeHead(this, token);
        break;
      }
      case InsertionMode.IN_HEAD: {
        tokenInHead(this, token);
        break;
      }
      case InsertionMode.IN_HEAD_NO_SCRIPT: {
        tokenInHeadNoScript(this, token);
        break;
      }
      case InsertionMode.AFTER_HEAD: {
        tokenAfterHead(this, token);
        break;
      }
      case InsertionMode.TEXT: {
        this._insertCharacters(token);
        break;
      }
      case InsertionMode.IN_TABLE:
      case InsertionMode.IN_TABLE_BODY:
      case InsertionMode.IN_ROW: {
        characterInTable(this, token);
        break;
      }
      case InsertionMode.IN_COLUMN_GROUP: {
        tokenInColumnGroup(this, token);
        break;
      }
      case InsertionMode.AFTER_BODY: {
        tokenAfterBody(this, token);
        break;
      }
      case InsertionMode.AFTER_AFTER_BODY: {
        tokenAfterAfterBody(this, token);
        break;
      }
      default:
    }
  }
  /** @internal */
  onComment(token) {
    this.skipNextNewLine = false;
    if (this.currentNotInHTML) {
      appendComment(this, token);
      return;
    }
    switch (this.insertionMode) {
      case InsertionMode.INITIAL:
      case InsertionMode.BEFORE_HTML:
      case InsertionMode.BEFORE_HEAD:
      case InsertionMode.IN_HEAD:
      case InsertionMode.IN_HEAD_NO_SCRIPT:
      case InsertionMode.AFTER_HEAD:
      case InsertionMode.IN_BODY:
      case InsertionMode.IN_TABLE:
      case InsertionMode.IN_CAPTION:
      case InsertionMode.IN_COLUMN_GROUP:
      case InsertionMode.IN_TABLE_BODY:
      case InsertionMode.IN_ROW:
      case InsertionMode.IN_CELL:
      case InsertionMode.IN_SELECT:
      case InsertionMode.IN_SELECT_IN_TABLE:
      case InsertionMode.IN_TEMPLATE:
      case InsertionMode.IN_FRAMESET:
      case InsertionMode.AFTER_FRAMESET: {
        appendComment(this, token);
        break;
      }
      case InsertionMode.IN_TABLE_TEXT: {
        tokenInTableText(this, token);
        break;
      }
      case InsertionMode.AFTER_BODY: {
        appendCommentToRootHtmlElement(this, token);
        break;
      }
      case InsertionMode.AFTER_AFTER_BODY:
      case InsertionMode.AFTER_AFTER_FRAMESET: {
        appendCommentToDocument(this, token);
        break;
      }
      default:
    }
  }
  /** @internal */
  onDoctype(token) {
    this.skipNextNewLine = false;
    switch (this.insertionMode) {
      case InsertionMode.INITIAL: {
        doctypeInInitialMode(this, token);
        break;
      }
      case InsertionMode.BEFORE_HEAD:
      case InsertionMode.IN_HEAD:
      case InsertionMode.IN_HEAD_NO_SCRIPT:
      case InsertionMode.AFTER_HEAD: {
        this._err(token, ERR.misplacedDoctype);
        break;
      }
      case InsertionMode.IN_TABLE_TEXT: {
        tokenInTableText(this, token);
        break;
      }
      default:
    }
  }
  /** @internal */
  onStartTag(token) {
    this.skipNextNewLine = false;
    this.currentToken = token;
    this._processStartTag(token);
    if (token.selfClosing && !token.ackSelfClosing) {
      this._err(token, ERR.nonVoidHtmlElementStartTagWithTrailingSolidus);
    }
  }
  /**
   * Processes a given start tag.
   *
   * `onStartTag` checks if a self-closing tag was recognized. When a token
   * is moved inbetween multiple insertion modes, this check for self-closing
   * could lead to false positives. To avoid this, `_processStartTag` is used
   * for nested calls.
   *
   * @param token The token to process.
   * @protected
   */
  _processStartTag(token) {
    if (this.shouldProcessStartTagTokenInForeignContent(token)) {
      startTagInForeignContent(this, token);
    } else {
      this._startTagOutsideForeignContent(token);
    }
  }
  /** @protected */
  _startTagOutsideForeignContent(token) {
    switch (this.insertionMode) {
      case InsertionMode.INITIAL: {
        tokenInInitialMode(this, token);
        break;
      }
      case InsertionMode.BEFORE_HTML: {
        startTagBeforeHtml(this, token);
        break;
      }
      case InsertionMode.BEFORE_HEAD: {
        startTagBeforeHead(this, token);
        break;
      }
      case InsertionMode.IN_HEAD: {
        startTagInHead(this, token);
        break;
      }
      case InsertionMode.IN_HEAD_NO_SCRIPT: {
        startTagInHeadNoScript(this, token);
        break;
      }
      case InsertionMode.AFTER_HEAD: {
        startTagAfterHead(this, token);
        break;
      }
      case InsertionMode.IN_BODY: {
        startTagInBody(this, token);
        break;
      }
      case InsertionMode.IN_TABLE: {
        startTagInTable(this, token);
        break;
      }
      case InsertionMode.IN_TABLE_TEXT: {
        tokenInTableText(this, token);
        break;
      }
      case InsertionMode.IN_CAPTION: {
        startTagInCaption(this, token);
        break;
      }
      case InsertionMode.IN_COLUMN_GROUP: {
        startTagInColumnGroup(this, token);
        break;
      }
      case InsertionMode.IN_TABLE_BODY: {
        startTagInTableBody(this, token);
        break;
      }
      case InsertionMode.IN_ROW: {
        startTagInRow(this, token);
        break;
      }
      case InsertionMode.IN_CELL: {
        startTagInCell(this, token);
        break;
      }
      case InsertionMode.IN_SELECT: {
        startTagInSelect(this, token);
        break;
      }
      case InsertionMode.IN_SELECT_IN_TABLE: {
        startTagInSelectInTable(this, token);
        break;
      }
      case InsertionMode.IN_TEMPLATE: {
        startTagInTemplate(this, token);
        break;
      }
      case InsertionMode.AFTER_BODY: {
        startTagAfterBody(this, token);
        break;
      }
      case InsertionMode.IN_FRAMESET: {
        startTagInFrameset(this, token);
        break;
      }
      case InsertionMode.AFTER_FRAMESET: {
        startTagAfterFrameset(this, token);
        break;
      }
      case InsertionMode.AFTER_AFTER_BODY: {
        startTagAfterAfterBody(this, token);
        break;
      }
      case InsertionMode.AFTER_AFTER_FRAMESET: {
        startTagAfterAfterFrameset(this, token);
        break;
      }
      default:
    }
  }
  /** @internal */
  onEndTag(token) {
    this.skipNextNewLine = false;
    this.currentToken = token;
    if (this.currentNotInHTML) {
      endTagInForeignContent(this, token);
    } else {
      this._endTagOutsideForeignContent(token);
    }
  }
  /** @protected */
  _endTagOutsideForeignContent(token) {
    switch (this.insertionMode) {
      case InsertionMode.INITIAL: {
        tokenInInitialMode(this, token);
        break;
      }
      case InsertionMode.BEFORE_HTML: {
        endTagBeforeHtml(this, token);
        break;
      }
      case InsertionMode.BEFORE_HEAD: {
        endTagBeforeHead(this, token);
        break;
      }
      case InsertionMode.IN_HEAD: {
        endTagInHead(this, token);
        break;
      }
      case InsertionMode.IN_HEAD_NO_SCRIPT: {
        endTagInHeadNoScript(this, token);
        break;
      }
      case InsertionMode.AFTER_HEAD: {
        endTagAfterHead(this, token);
        break;
      }
      case InsertionMode.IN_BODY: {
        endTagInBody(this, token);
        break;
      }
      case InsertionMode.TEXT: {
        endTagInText(this, token);
        break;
      }
      case InsertionMode.IN_TABLE: {
        endTagInTable(this, token);
        break;
      }
      case InsertionMode.IN_TABLE_TEXT: {
        tokenInTableText(this, token);
        break;
      }
      case InsertionMode.IN_CAPTION: {
        endTagInCaption(this, token);
        break;
      }
      case InsertionMode.IN_COLUMN_GROUP: {
        endTagInColumnGroup(this, token);
        break;
      }
      case InsertionMode.IN_TABLE_BODY: {
        endTagInTableBody(this, token);
        break;
      }
      case InsertionMode.IN_ROW: {
        endTagInRow(this, token);
        break;
      }
      case InsertionMode.IN_CELL: {
        endTagInCell(this, token);
        break;
      }
      case InsertionMode.IN_SELECT: {
        endTagInSelect(this, token);
        break;
      }
      case InsertionMode.IN_SELECT_IN_TABLE: {
        endTagInSelectInTable(this, token);
        break;
      }
      case InsertionMode.IN_TEMPLATE: {
        endTagInTemplate(this, token);
        break;
      }
      case InsertionMode.AFTER_BODY: {
        endTagAfterBody(this, token);
        break;
      }
      case InsertionMode.IN_FRAMESET: {
        endTagInFrameset(this, token);
        break;
      }
      case InsertionMode.AFTER_FRAMESET: {
        endTagAfterFrameset(this, token);
        break;
      }
      case InsertionMode.AFTER_AFTER_BODY: {
        tokenAfterAfterBody(this, token);
        break;
      }
      default:
    }
  }
  /** @internal */
  onEof(token) {
    switch (this.insertionMode) {
      case InsertionMode.INITIAL: {
        tokenInInitialMode(this, token);
        break;
      }
      case InsertionMode.BEFORE_HTML: {
        tokenBeforeHtml(this, token);
        break;
      }
      case InsertionMode.BEFORE_HEAD: {
        tokenBeforeHead(this, token);
        break;
      }
      case InsertionMode.IN_HEAD: {
        tokenInHead(this, token);
        break;
      }
      case InsertionMode.IN_HEAD_NO_SCRIPT: {
        tokenInHeadNoScript(this, token);
        break;
      }
      case InsertionMode.AFTER_HEAD: {
        tokenAfterHead(this, token);
        break;
      }
      case InsertionMode.IN_BODY:
      case InsertionMode.IN_TABLE:
      case InsertionMode.IN_CAPTION:
      case InsertionMode.IN_COLUMN_GROUP:
      case InsertionMode.IN_TABLE_BODY:
      case InsertionMode.IN_ROW:
      case InsertionMode.IN_CELL:
      case InsertionMode.IN_SELECT:
      case InsertionMode.IN_SELECT_IN_TABLE: {
        eofInBody(this, token);
        break;
      }
      case InsertionMode.TEXT: {
        eofInText(this, token);
        break;
      }
      case InsertionMode.IN_TABLE_TEXT: {
        tokenInTableText(this, token);
        break;
      }
      case InsertionMode.IN_TEMPLATE: {
        eofInTemplate(this, token);
        break;
      }
      case InsertionMode.AFTER_BODY:
      case InsertionMode.IN_FRAMESET:
      case InsertionMode.AFTER_FRAMESET:
      case InsertionMode.AFTER_AFTER_BODY:
      case InsertionMode.AFTER_AFTER_FRAMESET: {
        stopParsing(this, token);
        break;
      }
      default:
    }
  }
  /** @internal */
  onWhitespaceCharacter(token) {
    if (this.skipNextNewLine) {
      this.skipNextNewLine = false;
      if (token.chars.charCodeAt(0) === CODE_POINTS.LINE_FEED) {
        if (token.chars.length === 1) {
          return;
        }
        token.chars = token.chars.substr(1);
      }
    }
    if (this.tokenizer.inForeignNode) {
      this._insertCharacters(token);
      return;
    }
    switch (this.insertionMode) {
      case InsertionMode.IN_HEAD:
      case InsertionMode.IN_HEAD_NO_SCRIPT:
      case InsertionMode.AFTER_HEAD:
      case InsertionMode.TEXT:
      case InsertionMode.IN_COLUMN_GROUP:
      case InsertionMode.IN_SELECT:
      case InsertionMode.IN_SELECT_IN_TABLE:
      case InsertionMode.IN_FRAMESET:
      case InsertionMode.AFTER_FRAMESET: {
        this._insertCharacters(token);
        break;
      }
      case InsertionMode.IN_BODY:
      case InsertionMode.IN_CAPTION:
      case InsertionMode.IN_CELL:
      case InsertionMode.IN_TEMPLATE:
      case InsertionMode.AFTER_BODY:
      case InsertionMode.AFTER_AFTER_BODY:
      case InsertionMode.AFTER_AFTER_FRAMESET: {
        whitespaceCharacterInBody(this, token);
        break;
      }
      case InsertionMode.IN_TABLE:
      case InsertionMode.IN_TABLE_BODY:
      case InsertionMode.IN_ROW: {
        characterInTable(this, token);
        break;
      }
      case InsertionMode.IN_TABLE_TEXT: {
        whitespaceCharacterInTableText(this, token);
        break;
      }
      default:
    }
  }
};
function aaObtainFormattingElementEntry(p4, token) {
  let formattingElementEntry = p4.activeFormattingElements.getElementEntryInScopeWithTagName(token.tagName);
  if (formattingElementEntry) {
    if (!p4.openElements.contains(formattingElementEntry.element)) {
      p4.activeFormattingElements.removeEntry(formattingElementEntry);
      formattingElementEntry = null;
    } else if (!p4.openElements.hasInScope(token.tagID)) {
      formattingElementEntry = null;
    }
  } else {
    genericEndTagInBody(p4, token);
  }
  return formattingElementEntry;
}
function aaObtainFurthestBlock(p4, formattingElementEntry) {
  let furthestBlock = null;
  let idx = p4.openElements.stackTop;
  for (; idx >= 0; idx--) {
    const element7 = p4.openElements.items[idx];
    if (element7 === formattingElementEntry.element) {
      break;
    }
    if (p4._isSpecialElement(element7, p4.openElements.tagIDs[idx])) {
      furthestBlock = element7;
    }
  }
  if (!furthestBlock) {
    p4.openElements.shortenToLength(Math.max(idx, 0));
    p4.activeFormattingElements.removeEntry(formattingElementEntry);
  }
  return furthestBlock;
}
function aaInnerLoop(p4, furthestBlock, formattingElement) {
  let lastElement = furthestBlock;
  let nextElement = p4.openElements.getCommonAncestor(furthestBlock);
  for (let i3 = 0, element7 = nextElement; element7 !== formattingElement; i3++, element7 = nextElement) {
    nextElement = p4.openElements.getCommonAncestor(element7);
    const elementEntry = p4.activeFormattingElements.getElementEntry(element7);
    const counterOverflow = elementEntry && i3 >= AA_INNER_LOOP_ITER;
    const shouldRemoveFromOpenElements = !elementEntry || counterOverflow;
    if (shouldRemoveFromOpenElements) {
      if (counterOverflow) {
        p4.activeFormattingElements.removeEntry(elementEntry);
      }
      p4.openElements.remove(element7);
    } else {
      element7 = aaRecreateElementFromEntry(p4, elementEntry);
      if (lastElement === furthestBlock) {
        p4.activeFormattingElements.bookmark = elementEntry;
      }
      p4.treeAdapter.detachNode(lastElement);
      p4.treeAdapter.appendChild(element7, lastElement);
      lastElement = element7;
    }
  }
  return lastElement;
}
function aaRecreateElementFromEntry(p4, elementEntry) {
  const ns = p4.treeAdapter.getNamespaceURI(elementEntry.element);
  const newElement = p4.treeAdapter.createElement(elementEntry.token.tagName, ns, elementEntry.token.attrs);
  p4.openElements.replace(elementEntry.element, newElement);
  elementEntry.element = newElement;
  return newElement;
}
function aaInsertLastNodeInCommonAncestor(p4, commonAncestor, lastElement) {
  const tn4 = p4.treeAdapter.getTagName(commonAncestor);
  const tid = getTagID(tn4);
  if (p4._isElementCausesFosterParenting(tid)) {
    p4._fosterParentElement(lastElement);
  } else {
    const ns = p4.treeAdapter.getNamespaceURI(commonAncestor);
    if (tid === TAG_ID.TEMPLATE && ns === NS.HTML) {
      commonAncestor = p4.treeAdapter.getTemplateContent(commonAncestor);
    }
    p4.treeAdapter.appendChild(commonAncestor, lastElement);
  }
}
function aaReplaceFormattingElement(p4, furthestBlock, formattingElementEntry) {
  const ns = p4.treeAdapter.getNamespaceURI(formattingElementEntry.element);
  const { token } = formattingElementEntry;
  const newElement = p4.treeAdapter.createElement(token.tagName, ns, token.attrs);
  p4._adoptNodes(furthestBlock, newElement);
  p4.treeAdapter.appendChild(furthestBlock, newElement);
  p4.activeFormattingElements.insertElementAfterBookmark(newElement, token);
  p4.activeFormattingElements.removeEntry(formattingElementEntry);
  p4.openElements.remove(formattingElementEntry.element);
  p4.openElements.insertAfter(furthestBlock, newElement, token.tagID);
}
function callAdoptionAgency(p4, token) {
  for (let i3 = 0; i3 < AA_OUTER_LOOP_ITER; i3++) {
    const formattingElementEntry = aaObtainFormattingElementEntry(p4, token);
    if (!formattingElementEntry) {
      break;
    }
    const furthestBlock = aaObtainFurthestBlock(p4, formattingElementEntry);
    if (!furthestBlock) {
      break;
    }
    p4.activeFormattingElements.bookmark = formattingElementEntry;
    const lastElement = aaInnerLoop(p4, furthestBlock, formattingElementEntry.element);
    const commonAncestor = p4.openElements.getCommonAncestor(formattingElementEntry.element);
    p4.treeAdapter.detachNode(lastElement);
    if (commonAncestor)
      aaInsertLastNodeInCommonAncestor(p4, commonAncestor, lastElement);
    aaReplaceFormattingElement(p4, furthestBlock, formattingElementEntry);
  }
}
function appendComment(p4, token) {
  p4._appendCommentNode(token, p4.openElements.currentTmplContentOrNode);
}
function appendCommentToRootHtmlElement(p4, token) {
  p4._appendCommentNode(token, p4.openElements.items[0]);
}
function appendCommentToDocument(p4, token) {
  p4._appendCommentNode(token, p4.document);
}
function stopParsing(p4, token) {
  p4.stopped = true;
  if (token.location) {
    const target = p4.fragmentContext ? 0 : 2;
    for (let i3 = p4.openElements.stackTop; i3 >= target; i3--) {
      p4._setEndLocation(p4.openElements.items[i3], token);
    }
    if (!p4.fragmentContext && p4.openElements.stackTop >= 0) {
      const htmlElement = p4.openElements.items[0];
      const htmlLocation = p4.treeAdapter.getNodeSourceCodeLocation(htmlElement);
      if (htmlLocation && !htmlLocation.endTag) {
        p4._setEndLocation(htmlElement, token);
        if (p4.openElements.stackTop >= 1) {
          const bodyElement = p4.openElements.items[1];
          const bodyLocation = p4.treeAdapter.getNodeSourceCodeLocation(bodyElement);
          if (bodyLocation && !bodyLocation.endTag) {
            p4._setEndLocation(bodyElement, token);
          }
        }
      }
    }
  }
}
function doctypeInInitialMode(p4, token) {
  p4._setDocumentType(token);
  const mode = token.forceQuirks ? DOCUMENT_MODE.QUIRKS : getDocumentMode(token);
  if (!isConforming(token)) {
    p4._err(token, ERR.nonConformingDoctype);
  }
  p4.treeAdapter.setDocumentMode(p4.document, mode);
  p4.insertionMode = InsertionMode.BEFORE_HTML;
}
function tokenInInitialMode(p4, token) {
  p4._err(token, ERR.missingDoctype, true);
  p4.treeAdapter.setDocumentMode(p4.document, DOCUMENT_MODE.QUIRKS);
  p4.insertionMode = InsertionMode.BEFORE_HTML;
  p4._processToken(token);
}
function startTagBeforeHtml(p4, token) {
  if (token.tagID === TAG_ID.HTML) {
    p4._insertElement(token, NS.HTML);
    p4.insertionMode = InsertionMode.BEFORE_HEAD;
  } else {
    tokenBeforeHtml(p4, token);
  }
}
function endTagBeforeHtml(p4, token) {
  const tn4 = token.tagID;
  if (tn4 === TAG_ID.HTML || tn4 === TAG_ID.HEAD || tn4 === TAG_ID.BODY || tn4 === TAG_ID.BR) {
    tokenBeforeHtml(p4, token);
  }
}
function tokenBeforeHtml(p4, token) {
  p4._insertFakeRootElement();
  p4.insertionMode = InsertionMode.BEFORE_HEAD;
  p4._processToken(token);
}
function startTagBeforeHead(p4, token) {
  switch (token.tagID) {
    case TAG_ID.HTML: {
      startTagInBody(p4, token);
      break;
    }
    case TAG_ID.HEAD: {
      p4._insertElement(token, NS.HTML);
      p4.headElement = p4.openElements.current;
      p4.insertionMode = InsertionMode.IN_HEAD;
      break;
    }
    default: {
      tokenBeforeHead(p4, token);
    }
  }
}
function endTagBeforeHead(p4, token) {
  const tn4 = token.tagID;
  if (tn4 === TAG_ID.HEAD || tn4 === TAG_ID.BODY || tn4 === TAG_ID.HTML || tn4 === TAG_ID.BR) {
    tokenBeforeHead(p4, token);
  } else {
    p4._err(token, ERR.endTagWithoutMatchingOpenElement);
  }
}
function tokenBeforeHead(p4, token) {
  p4._insertFakeElement(TAG_NAMES.HEAD, TAG_ID.HEAD);
  p4.headElement = p4.openElements.current;
  p4.insertionMode = InsertionMode.IN_HEAD;
  p4._processToken(token);
}
function startTagInHead(p4, token) {
  switch (token.tagID) {
    case TAG_ID.HTML: {
      startTagInBody(p4, token);
      break;
    }
    case TAG_ID.BASE:
    case TAG_ID.BASEFONT:
    case TAG_ID.BGSOUND:
    case TAG_ID.LINK:
    case TAG_ID.META: {
      p4._appendElement(token, NS.HTML);
      token.ackSelfClosing = true;
      break;
    }
    case TAG_ID.TITLE: {
      p4._switchToTextParsing(token, TokenizerMode.RCDATA);
      break;
    }
    case TAG_ID.NOSCRIPT: {
      if (p4.options.scriptingEnabled) {
        p4._switchToTextParsing(token, TokenizerMode.RAWTEXT);
      } else {
        p4._insertElement(token, NS.HTML);
        p4.insertionMode = InsertionMode.IN_HEAD_NO_SCRIPT;
      }
      break;
    }
    case TAG_ID.NOFRAMES:
    case TAG_ID.STYLE: {
      p4._switchToTextParsing(token, TokenizerMode.RAWTEXT);
      break;
    }
    case TAG_ID.SCRIPT: {
      p4._switchToTextParsing(token, TokenizerMode.SCRIPT_DATA);
      break;
    }
    case TAG_ID.TEMPLATE: {
      p4._insertTemplate(token);
      p4.activeFormattingElements.insertMarker();
      p4.framesetOk = false;
      p4.insertionMode = InsertionMode.IN_TEMPLATE;
      p4.tmplInsertionModeStack.unshift(InsertionMode.IN_TEMPLATE);
      break;
    }
    case TAG_ID.HEAD: {
      p4._err(token, ERR.misplacedStartTagForHeadElement);
      break;
    }
    default: {
      tokenInHead(p4, token);
    }
  }
}
function endTagInHead(p4, token) {
  switch (token.tagID) {
    case TAG_ID.HEAD: {
      p4.openElements.pop();
      p4.insertionMode = InsertionMode.AFTER_HEAD;
      break;
    }
    case TAG_ID.BODY:
    case TAG_ID.BR:
    case TAG_ID.HTML: {
      tokenInHead(p4, token);
      break;
    }
    case TAG_ID.TEMPLATE: {
      templateEndTagInHead(p4, token);
      break;
    }
    default: {
      p4._err(token, ERR.endTagWithoutMatchingOpenElement);
    }
  }
}
function templateEndTagInHead(p4, token) {
  if (p4.openElements.tmplCount > 0) {
    p4.openElements.generateImpliedEndTagsThoroughly();
    if (p4.openElements.currentTagId !== TAG_ID.TEMPLATE) {
      p4._err(token, ERR.closingOfElementWithOpenChildElements);
    }
    p4.openElements.popUntilTagNamePopped(TAG_ID.TEMPLATE);
    p4.activeFormattingElements.clearToLastMarker();
    p4.tmplInsertionModeStack.shift();
    p4._resetInsertionMode();
  } else {
    p4._err(token, ERR.endTagWithoutMatchingOpenElement);
  }
}
function tokenInHead(p4, token) {
  p4.openElements.pop();
  p4.insertionMode = InsertionMode.AFTER_HEAD;
  p4._processToken(token);
}
function startTagInHeadNoScript(p4, token) {
  switch (token.tagID) {
    case TAG_ID.HTML: {
      startTagInBody(p4, token);
      break;
    }
    case TAG_ID.BASEFONT:
    case TAG_ID.BGSOUND:
    case TAG_ID.HEAD:
    case TAG_ID.LINK:
    case TAG_ID.META:
    case TAG_ID.NOFRAMES:
    case TAG_ID.STYLE: {
      startTagInHead(p4, token);
      break;
    }
    case TAG_ID.NOSCRIPT: {
      p4._err(token, ERR.nestedNoscriptInHead);
      break;
    }
    default: {
      tokenInHeadNoScript(p4, token);
    }
  }
}
function endTagInHeadNoScript(p4, token) {
  switch (token.tagID) {
    case TAG_ID.NOSCRIPT: {
      p4.openElements.pop();
      p4.insertionMode = InsertionMode.IN_HEAD;
      break;
    }
    case TAG_ID.BR: {
      tokenInHeadNoScript(p4, token);
      break;
    }
    default: {
      p4._err(token, ERR.endTagWithoutMatchingOpenElement);
    }
  }
}
function tokenInHeadNoScript(p4, token) {
  const errCode = token.type === TokenType.EOF ? ERR.openElementsLeftAfterEof : ERR.disallowedContentInNoscriptInHead;
  p4._err(token, errCode);
  p4.openElements.pop();
  p4.insertionMode = InsertionMode.IN_HEAD;
  p4._processToken(token);
}
function startTagAfterHead(p4, token) {
  switch (token.tagID) {
    case TAG_ID.HTML: {
      startTagInBody(p4, token);
      break;
    }
    case TAG_ID.BODY: {
      p4._insertElement(token, NS.HTML);
      p4.framesetOk = false;
      p4.insertionMode = InsertionMode.IN_BODY;
      break;
    }
    case TAG_ID.FRAMESET: {
      p4._insertElement(token, NS.HTML);
      p4.insertionMode = InsertionMode.IN_FRAMESET;
      break;
    }
    case TAG_ID.BASE:
    case TAG_ID.BASEFONT:
    case TAG_ID.BGSOUND:
    case TAG_ID.LINK:
    case TAG_ID.META:
    case TAG_ID.NOFRAMES:
    case TAG_ID.SCRIPT:
    case TAG_ID.STYLE:
    case TAG_ID.TEMPLATE:
    case TAG_ID.TITLE: {
      p4._err(token, ERR.abandonedHeadElementChild);
      p4.openElements.push(p4.headElement, TAG_ID.HEAD);
      startTagInHead(p4, token);
      p4.openElements.remove(p4.headElement);
      break;
    }
    case TAG_ID.HEAD: {
      p4._err(token, ERR.misplacedStartTagForHeadElement);
      break;
    }
    default: {
      tokenAfterHead(p4, token);
    }
  }
}
function endTagAfterHead(p4, token) {
  switch (token.tagID) {
    case TAG_ID.BODY:
    case TAG_ID.HTML:
    case TAG_ID.BR: {
      tokenAfterHead(p4, token);
      break;
    }
    case TAG_ID.TEMPLATE: {
      templateEndTagInHead(p4, token);
      break;
    }
    default: {
      p4._err(token, ERR.endTagWithoutMatchingOpenElement);
    }
  }
}
function tokenAfterHead(p4, token) {
  p4._insertFakeElement(TAG_NAMES.BODY, TAG_ID.BODY);
  p4.insertionMode = InsertionMode.IN_BODY;
  modeInBody(p4, token);
}
function modeInBody(p4, token) {
  switch (token.type) {
    case TokenType.CHARACTER: {
      characterInBody(p4, token);
      break;
    }
    case TokenType.WHITESPACE_CHARACTER: {
      whitespaceCharacterInBody(p4, token);
      break;
    }
    case TokenType.COMMENT: {
      appendComment(p4, token);
      break;
    }
    case TokenType.START_TAG: {
      startTagInBody(p4, token);
      break;
    }
    case TokenType.END_TAG: {
      endTagInBody(p4, token);
      break;
    }
    case TokenType.EOF: {
      eofInBody(p4, token);
      break;
    }
    default:
  }
}
function whitespaceCharacterInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  p4._insertCharacters(token);
}
function characterInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  p4._insertCharacters(token);
  p4.framesetOk = false;
}
function htmlStartTagInBody(p4, token) {
  if (p4.openElements.tmplCount === 0) {
    p4.treeAdapter.adoptAttributes(p4.openElements.items[0], token.attrs);
  }
}
function bodyStartTagInBody(p4, token) {
  const bodyElement = p4.openElements.tryPeekProperlyNestedBodyElement();
  if (bodyElement && p4.openElements.tmplCount === 0) {
    p4.framesetOk = false;
    p4.treeAdapter.adoptAttributes(bodyElement, token.attrs);
  }
}
function framesetStartTagInBody(p4, token) {
  const bodyElement = p4.openElements.tryPeekProperlyNestedBodyElement();
  if (p4.framesetOk && bodyElement) {
    p4.treeAdapter.detachNode(bodyElement);
    p4.openElements.popAllUpToHtmlElement();
    p4._insertElement(token, NS.HTML);
    p4.insertionMode = InsertionMode.IN_FRAMESET;
  }
}
function addressStartTagInBody(p4, token) {
  if (p4.openElements.hasInButtonScope(TAG_ID.P)) {
    p4._closePElement();
  }
  p4._insertElement(token, NS.HTML);
}
function numberedHeaderStartTagInBody(p4, token) {
  if (p4.openElements.hasInButtonScope(TAG_ID.P)) {
    p4._closePElement();
  }
  if (p4.openElements.currentTagId !== void 0 && NUMBERED_HEADERS.has(p4.openElements.currentTagId)) {
    p4.openElements.pop();
  }
  p4._insertElement(token, NS.HTML);
}
function preStartTagInBody(p4, token) {
  if (p4.openElements.hasInButtonScope(TAG_ID.P)) {
    p4._closePElement();
  }
  p4._insertElement(token, NS.HTML);
  p4.skipNextNewLine = true;
  p4.framesetOk = false;
}
function formStartTagInBody(p4, token) {
  const inTemplate = p4.openElements.tmplCount > 0;
  if (!p4.formElement || inTemplate) {
    if (p4.openElements.hasInButtonScope(TAG_ID.P)) {
      p4._closePElement();
    }
    p4._insertElement(token, NS.HTML);
    if (!inTemplate) {
      p4.formElement = p4.openElements.current;
    }
  }
}
function listItemStartTagInBody(p4, token) {
  p4.framesetOk = false;
  const tn4 = token.tagID;
  for (let i3 = p4.openElements.stackTop; i3 >= 0; i3--) {
    const elementId = p4.openElements.tagIDs[i3];
    if (tn4 === TAG_ID.LI && elementId === TAG_ID.LI || (tn4 === TAG_ID.DD || tn4 === TAG_ID.DT) && (elementId === TAG_ID.DD || elementId === TAG_ID.DT)) {
      p4.openElements.generateImpliedEndTagsWithExclusion(elementId);
      p4.openElements.popUntilTagNamePopped(elementId);
      break;
    }
    if (elementId !== TAG_ID.ADDRESS && elementId !== TAG_ID.DIV && elementId !== TAG_ID.P && p4._isSpecialElement(p4.openElements.items[i3], elementId)) {
      break;
    }
  }
  if (p4.openElements.hasInButtonScope(TAG_ID.P)) {
    p4._closePElement();
  }
  p4._insertElement(token, NS.HTML);
}
function plaintextStartTagInBody(p4, token) {
  if (p4.openElements.hasInButtonScope(TAG_ID.P)) {
    p4._closePElement();
  }
  p4._insertElement(token, NS.HTML);
  p4.tokenizer.state = TokenizerMode.PLAINTEXT;
}
function buttonStartTagInBody(p4, token) {
  if (p4.openElements.hasInScope(TAG_ID.BUTTON)) {
    p4.openElements.generateImpliedEndTags();
    p4.openElements.popUntilTagNamePopped(TAG_ID.BUTTON);
  }
  p4._reconstructActiveFormattingElements();
  p4._insertElement(token, NS.HTML);
  p4.framesetOk = false;
}
function aStartTagInBody(p4, token) {
  const activeElementEntry = p4.activeFormattingElements.getElementEntryInScopeWithTagName(TAG_NAMES.A);
  if (activeElementEntry) {
    callAdoptionAgency(p4, token);
    p4.openElements.remove(activeElementEntry.element);
    p4.activeFormattingElements.removeEntry(activeElementEntry);
  }
  p4._reconstructActiveFormattingElements();
  p4._insertElement(token, NS.HTML);
  p4.activeFormattingElements.pushElement(p4.openElements.current, token);
}
function bStartTagInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  p4._insertElement(token, NS.HTML);
  p4.activeFormattingElements.pushElement(p4.openElements.current, token);
}
function nobrStartTagInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  if (p4.openElements.hasInScope(TAG_ID.NOBR)) {
    callAdoptionAgency(p4, token);
    p4._reconstructActiveFormattingElements();
  }
  p4._insertElement(token, NS.HTML);
  p4.activeFormattingElements.pushElement(p4.openElements.current, token);
}
function appletStartTagInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  p4._insertElement(token, NS.HTML);
  p4.activeFormattingElements.insertMarker();
  p4.framesetOk = false;
}
function tableStartTagInBody(p4, token) {
  if (p4.treeAdapter.getDocumentMode(p4.document) !== DOCUMENT_MODE.QUIRKS && p4.openElements.hasInButtonScope(TAG_ID.P)) {
    p4._closePElement();
  }
  p4._insertElement(token, NS.HTML);
  p4.framesetOk = false;
  p4.insertionMode = InsertionMode.IN_TABLE;
}
function areaStartTagInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  p4._appendElement(token, NS.HTML);
  p4.framesetOk = false;
  token.ackSelfClosing = true;
}
function isHiddenInput(token) {
  const inputType = getTokenAttr(token, ATTRS.TYPE);
  return inputType != null && inputType.toLowerCase() === HIDDEN_INPUT_TYPE;
}
function inputStartTagInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  p4._appendElement(token, NS.HTML);
  if (!isHiddenInput(token)) {
    p4.framesetOk = false;
  }
  token.ackSelfClosing = true;
}
function paramStartTagInBody(p4, token) {
  p4._appendElement(token, NS.HTML);
  token.ackSelfClosing = true;
}
function hrStartTagInBody(p4, token) {
  if (p4.openElements.hasInButtonScope(TAG_ID.P)) {
    p4._closePElement();
  }
  p4._appendElement(token, NS.HTML);
  p4.framesetOk = false;
  token.ackSelfClosing = true;
}
function imageStartTagInBody(p4, token) {
  token.tagName = TAG_NAMES.IMG;
  token.tagID = TAG_ID.IMG;
  areaStartTagInBody(p4, token);
}
function textareaStartTagInBody(p4, token) {
  p4._insertElement(token, NS.HTML);
  p4.skipNextNewLine = true;
  p4.tokenizer.state = TokenizerMode.RCDATA;
  p4.originalInsertionMode = p4.insertionMode;
  p4.framesetOk = false;
  p4.insertionMode = InsertionMode.TEXT;
}
function xmpStartTagInBody(p4, token) {
  if (p4.openElements.hasInButtonScope(TAG_ID.P)) {
    p4._closePElement();
  }
  p4._reconstructActiveFormattingElements();
  p4.framesetOk = false;
  p4._switchToTextParsing(token, TokenizerMode.RAWTEXT);
}
function iframeStartTagInBody(p4, token) {
  p4.framesetOk = false;
  p4._switchToTextParsing(token, TokenizerMode.RAWTEXT);
}
function rawTextStartTagInBody(p4, token) {
  p4._switchToTextParsing(token, TokenizerMode.RAWTEXT);
}
function selectStartTagInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  p4._insertElement(token, NS.HTML);
  p4.framesetOk = false;
  p4.insertionMode = p4.insertionMode === InsertionMode.IN_TABLE || p4.insertionMode === InsertionMode.IN_CAPTION || p4.insertionMode === InsertionMode.IN_TABLE_BODY || p4.insertionMode === InsertionMode.IN_ROW || p4.insertionMode === InsertionMode.IN_CELL ? InsertionMode.IN_SELECT_IN_TABLE : InsertionMode.IN_SELECT;
}
function optgroupStartTagInBody(p4, token) {
  if (p4.openElements.currentTagId === TAG_ID.OPTION) {
    p4.openElements.pop();
  }
  p4._reconstructActiveFormattingElements();
  p4._insertElement(token, NS.HTML);
}
function rbStartTagInBody(p4, token) {
  if (p4.openElements.hasInScope(TAG_ID.RUBY)) {
    p4.openElements.generateImpliedEndTags();
  }
  p4._insertElement(token, NS.HTML);
}
function rtStartTagInBody(p4, token) {
  if (p4.openElements.hasInScope(TAG_ID.RUBY)) {
    p4.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.RTC);
  }
  p4._insertElement(token, NS.HTML);
}
function mathStartTagInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  adjustTokenMathMLAttrs(token);
  adjustTokenXMLAttrs(token);
  if (token.selfClosing) {
    p4._appendElement(token, NS.MATHML);
  } else {
    p4._insertElement(token, NS.MATHML);
  }
  token.ackSelfClosing = true;
}
function svgStartTagInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  adjustTokenSVGAttrs(token);
  adjustTokenXMLAttrs(token);
  if (token.selfClosing) {
    p4._appendElement(token, NS.SVG);
  } else {
    p4._insertElement(token, NS.SVG);
  }
  token.ackSelfClosing = true;
}
function genericStartTagInBody(p4, token) {
  p4._reconstructActiveFormattingElements();
  p4._insertElement(token, NS.HTML);
}
function startTagInBody(p4, token) {
  switch (token.tagID) {
    case TAG_ID.I:
    case TAG_ID.S:
    case TAG_ID.B:
    case TAG_ID.U:
    case TAG_ID.EM:
    case TAG_ID.TT:
    case TAG_ID.BIG:
    case TAG_ID.CODE:
    case TAG_ID.FONT:
    case TAG_ID.SMALL:
    case TAG_ID.STRIKE:
    case TAG_ID.STRONG: {
      bStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.A: {
      aStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.H1:
    case TAG_ID.H2:
    case TAG_ID.H3:
    case TAG_ID.H4:
    case TAG_ID.H5:
    case TAG_ID.H6: {
      numberedHeaderStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.P:
    case TAG_ID.DL:
    case TAG_ID.OL:
    case TAG_ID.UL:
    case TAG_ID.DIV:
    case TAG_ID.DIR:
    case TAG_ID.NAV:
    case TAG_ID.MAIN:
    case TAG_ID.MENU:
    case TAG_ID.ASIDE:
    case TAG_ID.CENTER:
    case TAG_ID.FIGURE:
    case TAG_ID.FOOTER:
    case TAG_ID.HEADER:
    case TAG_ID.HGROUP:
    case TAG_ID.DIALOG:
    case TAG_ID.DETAILS:
    case TAG_ID.ADDRESS:
    case TAG_ID.ARTICLE:
    case TAG_ID.SEARCH:
    case TAG_ID.SECTION:
    case TAG_ID.SUMMARY:
    case TAG_ID.FIELDSET:
    case TAG_ID.BLOCKQUOTE:
    case TAG_ID.FIGCAPTION: {
      addressStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.LI:
    case TAG_ID.DD:
    case TAG_ID.DT: {
      listItemStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.BR:
    case TAG_ID.IMG:
    case TAG_ID.WBR:
    case TAG_ID.AREA:
    case TAG_ID.EMBED:
    case TAG_ID.KEYGEN: {
      areaStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.HR: {
      hrStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.RB:
    case TAG_ID.RTC: {
      rbStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.RT:
    case TAG_ID.RP: {
      rtStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.PRE:
    case TAG_ID.LISTING: {
      preStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.XMP: {
      xmpStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.SVG: {
      svgStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.HTML: {
      htmlStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.BASE:
    case TAG_ID.LINK:
    case TAG_ID.META:
    case TAG_ID.STYLE:
    case TAG_ID.TITLE:
    case TAG_ID.SCRIPT:
    case TAG_ID.BGSOUND:
    case TAG_ID.BASEFONT:
    case TAG_ID.TEMPLATE: {
      startTagInHead(p4, token);
      break;
    }
    case TAG_ID.BODY: {
      bodyStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.FORM: {
      formStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.NOBR: {
      nobrStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.MATH: {
      mathStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.TABLE: {
      tableStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.INPUT: {
      inputStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.PARAM:
    case TAG_ID.TRACK:
    case TAG_ID.SOURCE: {
      paramStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.IMAGE: {
      imageStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.BUTTON: {
      buttonStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.APPLET:
    case TAG_ID.OBJECT:
    case TAG_ID.MARQUEE: {
      appletStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.IFRAME: {
      iframeStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.SELECT: {
      selectStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.OPTION:
    case TAG_ID.OPTGROUP: {
      optgroupStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.NOEMBED:
    case TAG_ID.NOFRAMES: {
      rawTextStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.FRAMESET: {
      framesetStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.TEXTAREA: {
      textareaStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.NOSCRIPT: {
      if (p4.options.scriptingEnabled) {
        rawTextStartTagInBody(p4, token);
      } else {
        genericStartTagInBody(p4, token);
      }
      break;
    }
    case TAG_ID.PLAINTEXT: {
      plaintextStartTagInBody(p4, token);
      break;
    }
    case TAG_ID.COL:
    case TAG_ID.TH:
    case TAG_ID.TD:
    case TAG_ID.TR:
    case TAG_ID.HEAD:
    case TAG_ID.FRAME:
    case TAG_ID.TBODY:
    case TAG_ID.TFOOT:
    case TAG_ID.THEAD:
    case TAG_ID.CAPTION:
    case TAG_ID.COLGROUP: {
      break;
    }
    default: {
      genericStartTagInBody(p4, token);
    }
  }
}
function bodyEndTagInBody(p4, token) {
  if (p4.openElements.hasInScope(TAG_ID.BODY)) {
    p4.insertionMode = InsertionMode.AFTER_BODY;
    if (p4.options.sourceCodeLocationInfo) {
      const bodyElement = p4.openElements.tryPeekProperlyNestedBodyElement();
      if (bodyElement) {
        p4._setEndLocation(bodyElement, token);
      }
    }
  }
}
function htmlEndTagInBody(p4, token) {
  if (p4.openElements.hasInScope(TAG_ID.BODY)) {
    p4.insertionMode = InsertionMode.AFTER_BODY;
    endTagAfterBody(p4, token);
  }
}
function addressEndTagInBody(p4, token) {
  const tn4 = token.tagID;
  if (p4.openElements.hasInScope(tn4)) {
    p4.openElements.generateImpliedEndTags();
    p4.openElements.popUntilTagNamePopped(tn4);
  }
}
function formEndTagInBody(p4) {
  const inTemplate = p4.openElements.tmplCount > 0;
  const { formElement } = p4;
  if (!inTemplate) {
    p4.formElement = null;
  }
  if ((formElement || inTemplate) && p4.openElements.hasInScope(TAG_ID.FORM)) {
    p4.openElements.generateImpliedEndTags();
    if (inTemplate) {
      p4.openElements.popUntilTagNamePopped(TAG_ID.FORM);
    } else if (formElement) {
      p4.openElements.remove(formElement);
    }
  }
}
function pEndTagInBody(p4) {
  if (!p4.openElements.hasInButtonScope(TAG_ID.P)) {
    p4._insertFakeElement(TAG_NAMES.P, TAG_ID.P);
  }
  p4._closePElement();
}
function liEndTagInBody(p4) {
  if (p4.openElements.hasInListItemScope(TAG_ID.LI)) {
    p4.openElements.generateImpliedEndTagsWithExclusion(TAG_ID.LI);
    p4.openElements.popUntilTagNamePopped(TAG_ID.LI);
  }
}
function ddEndTagInBody(p4, token) {
  const tn4 = token.tagID;
  if (p4.openElements.hasInScope(tn4)) {
    p4.openElements.generateImpliedEndTagsWithExclusion(tn4);
    p4.openElements.popUntilTagNamePopped(tn4);
  }
}
function numberedHeaderEndTagInBody(p4) {
  if (p4.openElements.hasNumberedHeaderInScope()) {
    p4.openElements.generateImpliedEndTags();
    p4.openElements.popUntilNumberedHeaderPopped();
  }
}
function appletEndTagInBody(p4, token) {
  const tn4 = token.tagID;
  if (p4.openElements.hasInScope(tn4)) {
    p4.openElements.generateImpliedEndTags();
    p4.openElements.popUntilTagNamePopped(tn4);
    p4.activeFormattingElements.clearToLastMarker();
  }
}
function brEndTagInBody(p4) {
  p4._reconstructActiveFormattingElements();
  p4._insertFakeElement(TAG_NAMES.BR, TAG_ID.BR);
  p4.openElements.pop();
  p4.framesetOk = false;
}
function genericEndTagInBody(p4, token) {
  const tn4 = token.tagName;
  const tid = token.tagID;
  for (let i3 = p4.openElements.stackTop; i3 > 0; i3--) {
    const element7 = p4.openElements.items[i3];
    const elementId = p4.openElements.tagIDs[i3];
    if (tid === elementId && (tid !== TAG_ID.UNKNOWN || p4.treeAdapter.getTagName(element7) === tn4)) {
      p4.openElements.generateImpliedEndTagsWithExclusion(tid);
      if (p4.openElements.stackTop >= i3)
        p4.openElements.shortenToLength(i3);
      break;
    }
    if (p4._isSpecialElement(element7, elementId)) {
      break;
    }
  }
}
function endTagInBody(p4, token) {
  switch (token.tagID) {
    case TAG_ID.A:
    case TAG_ID.B:
    case TAG_ID.I:
    case TAG_ID.S:
    case TAG_ID.U:
    case TAG_ID.EM:
    case TAG_ID.TT:
    case TAG_ID.BIG:
    case TAG_ID.CODE:
    case TAG_ID.FONT:
    case TAG_ID.NOBR:
    case TAG_ID.SMALL:
    case TAG_ID.STRIKE:
    case TAG_ID.STRONG: {
      callAdoptionAgency(p4, token);
      break;
    }
    case TAG_ID.P: {
      pEndTagInBody(p4);
      break;
    }
    case TAG_ID.DL:
    case TAG_ID.UL:
    case TAG_ID.OL:
    case TAG_ID.DIR:
    case TAG_ID.DIV:
    case TAG_ID.NAV:
    case TAG_ID.PRE:
    case TAG_ID.MAIN:
    case TAG_ID.MENU:
    case TAG_ID.ASIDE:
    case TAG_ID.BUTTON:
    case TAG_ID.CENTER:
    case TAG_ID.FIGURE:
    case TAG_ID.FOOTER:
    case TAG_ID.HEADER:
    case TAG_ID.HGROUP:
    case TAG_ID.DIALOG:
    case TAG_ID.ADDRESS:
    case TAG_ID.ARTICLE:
    case TAG_ID.DETAILS:
    case TAG_ID.SEARCH:
    case TAG_ID.SECTION:
    case TAG_ID.SUMMARY:
    case TAG_ID.LISTING:
    case TAG_ID.FIELDSET:
    case TAG_ID.BLOCKQUOTE:
    case TAG_ID.FIGCAPTION: {
      addressEndTagInBody(p4, token);
      break;
    }
    case TAG_ID.LI: {
      liEndTagInBody(p4);
      break;
    }
    case TAG_ID.DD:
    case TAG_ID.DT: {
      ddEndTagInBody(p4, token);
      break;
    }
    case TAG_ID.H1:
    case TAG_ID.H2:
    case TAG_ID.H3:
    case TAG_ID.H4:
    case TAG_ID.H5:
    case TAG_ID.H6: {
      numberedHeaderEndTagInBody(p4);
      break;
    }
    case TAG_ID.BR: {
      brEndTagInBody(p4);
      break;
    }
    case TAG_ID.BODY: {
      bodyEndTagInBody(p4, token);
      break;
    }
    case TAG_ID.HTML: {
      htmlEndTagInBody(p4, token);
      break;
    }
    case TAG_ID.FORM: {
      formEndTagInBody(p4);
      break;
    }
    case TAG_ID.APPLET:
    case TAG_ID.OBJECT:
    case TAG_ID.MARQUEE: {
      appletEndTagInBody(p4, token);
      break;
    }
    case TAG_ID.TEMPLATE: {
      templateEndTagInHead(p4, token);
      break;
    }
    default: {
      genericEndTagInBody(p4, token);
    }
  }
}
function eofInBody(p4, token) {
  if (p4.tmplInsertionModeStack.length > 0) {
    eofInTemplate(p4, token);
  } else {
    stopParsing(p4, token);
  }
}
function endTagInText(p4, token) {
  var _a2;
  if (token.tagID === TAG_ID.SCRIPT) {
    (_a2 = p4.scriptHandler) === null || _a2 === void 0 ? void 0 : _a2.call(p4, p4.openElements.current);
  }
  p4.openElements.pop();
  p4.insertionMode = p4.originalInsertionMode;
}
function eofInText(p4, token) {
  p4._err(token, ERR.eofInElementThatCanContainOnlyText);
  p4.openElements.pop();
  p4.insertionMode = p4.originalInsertionMode;
  p4.onEof(token);
}
function characterInTable(p4, token) {
  if (p4.openElements.currentTagId !== void 0 && TABLE_STRUCTURE_TAGS.has(p4.openElements.currentTagId)) {
    p4.pendingCharacterTokens.length = 0;
    p4.hasNonWhitespacePendingCharacterToken = false;
    p4.originalInsertionMode = p4.insertionMode;
    p4.insertionMode = InsertionMode.IN_TABLE_TEXT;
    switch (token.type) {
      case TokenType.CHARACTER: {
        characterInTableText(p4, token);
        break;
      }
      case TokenType.WHITESPACE_CHARACTER: {
        whitespaceCharacterInTableText(p4, token);
        break;
      }
    }
  } else {
    tokenInTable(p4, token);
  }
}
function captionStartTagInTable(p4, token) {
  p4.openElements.clearBackToTableContext();
  p4.activeFormattingElements.insertMarker();
  p4._insertElement(token, NS.HTML);
  p4.insertionMode = InsertionMode.IN_CAPTION;
}
function colgroupStartTagInTable(p4, token) {
  p4.openElements.clearBackToTableContext();
  p4._insertElement(token, NS.HTML);
  p4.insertionMode = InsertionMode.IN_COLUMN_GROUP;
}
function colStartTagInTable(p4, token) {
  p4.openElements.clearBackToTableContext();
  p4._insertFakeElement(TAG_NAMES.COLGROUP, TAG_ID.COLGROUP);
  p4.insertionMode = InsertionMode.IN_COLUMN_GROUP;
  startTagInColumnGroup(p4, token);
}
function tbodyStartTagInTable(p4, token) {
  p4.openElements.clearBackToTableContext();
  p4._insertElement(token, NS.HTML);
  p4.insertionMode = InsertionMode.IN_TABLE_BODY;
}
function tdStartTagInTable(p4, token) {
  p4.openElements.clearBackToTableContext();
  p4._insertFakeElement(TAG_NAMES.TBODY, TAG_ID.TBODY);
  p4.insertionMode = InsertionMode.IN_TABLE_BODY;
  startTagInTableBody(p4, token);
}
function tableStartTagInTable(p4, token) {
  if (p4.openElements.hasInTableScope(TAG_ID.TABLE)) {
    p4.openElements.popUntilTagNamePopped(TAG_ID.TABLE);
    p4._resetInsertionMode();
    p4._processStartTag(token);
  }
}
function inputStartTagInTable(p4, token) {
  if (isHiddenInput(token)) {
    p4._appendElement(token, NS.HTML);
  } else {
    tokenInTable(p4, token);
  }
  token.ackSelfClosing = true;
}
function formStartTagInTable(p4, token) {
  if (!p4.formElement && p4.openElements.tmplCount === 0) {
    p4._insertElement(token, NS.HTML);
    p4.formElement = p4.openElements.current;
    p4.openElements.pop();
  }
}
function startTagInTable(p4, token) {
  switch (token.tagID) {
    case TAG_ID.TD:
    case TAG_ID.TH:
    case TAG_ID.TR: {
      tdStartTagInTable(p4, token);
      break;
    }
    case TAG_ID.STYLE:
    case TAG_ID.SCRIPT:
    case TAG_ID.TEMPLATE: {
      startTagInHead(p4, token);
      break;
    }
    case TAG_ID.COL: {
      colStartTagInTable(p4, token);
      break;
    }
    case TAG_ID.FORM: {
      formStartTagInTable(p4, token);
      break;
    }
    case TAG_ID.TABLE: {
      tableStartTagInTable(p4, token);
      break;
    }
    case TAG_ID.TBODY:
    case TAG_ID.TFOOT:
    case TAG_ID.THEAD: {
      tbodyStartTagInTable(p4, token);
      break;
    }
    case TAG_ID.INPUT: {
      inputStartTagInTable(p4, token);
      break;
    }
    case TAG_ID.CAPTION: {
      captionStartTagInTable(p4, token);
      break;
    }
    case TAG_ID.COLGROUP: {
      colgroupStartTagInTable(p4, token);
      break;
    }
    default: {
      tokenInTable(p4, token);
    }
  }
}
function endTagInTable(p4, token) {
  switch (token.tagID) {
    case TAG_ID.TABLE: {
      if (p4.openElements.hasInTableScope(TAG_ID.TABLE)) {
        p4.openElements.popUntilTagNamePopped(TAG_ID.TABLE);
        p4._resetInsertionMode();
      }
      break;
    }
    case TAG_ID.TEMPLATE: {
      templateEndTagInHead(p4, token);
      break;
    }
    case TAG_ID.BODY:
    case TAG_ID.CAPTION:
    case TAG_ID.COL:
    case TAG_ID.COLGROUP:
    case TAG_ID.HTML:
    case TAG_ID.TBODY:
    case TAG_ID.TD:
    case TAG_ID.TFOOT:
    case TAG_ID.TH:
    case TAG_ID.THEAD:
    case TAG_ID.TR: {
      break;
    }
    default: {
      tokenInTable(p4, token);
    }
  }
}
function tokenInTable(p4, token) {
  const savedFosterParentingState = p4.fosterParentingEnabled;
  p4.fosterParentingEnabled = true;
  modeInBody(p4, token);
  p4.fosterParentingEnabled = savedFosterParentingState;
}
function whitespaceCharacterInTableText(p4, token) {
  p4.pendingCharacterTokens.push(token);
}
function characterInTableText(p4, token) {
  p4.pendingCharacterTokens.push(token);
  p4.hasNonWhitespacePendingCharacterToken = true;
}
function tokenInTableText(p4, token) {
  let i3 = 0;
  if (p4.hasNonWhitespacePendingCharacterToken) {
    for (; i3 < p4.pendingCharacterTokens.length; i3++) {
      tokenInTable(p4, p4.pendingCharacterTokens[i3]);
    }
  } else {
    for (; i3 < p4.pendingCharacterTokens.length; i3++) {
      p4._insertCharacters(p4.pendingCharacterTokens[i3]);
    }
  }
  p4.insertionMode = p4.originalInsertionMode;
  p4._processToken(token);
}
var TABLE_VOID_ELEMENTS = /* @__PURE__ */ new Set([TAG_ID.CAPTION, TAG_ID.COL, TAG_ID.COLGROUP, TAG_ID.TBODY, TAG_ID.TD, TAG_ID.TFOOT, TAG_ID.TH, TAG_ID.THEAD, TAG_ID.TR]);
function startTagInCaption(p4, token) {
  const tn4 = token.tagID;
  if (TABLE_VOID_ELEMENTS.has(tn4)) {
    if (p4.openElements.hasInTableScope(TAG_ID.CAPTION)) {
      p4.openElements.generateImpliedEndTags();
      p4.openElements.popUntilTagNamePopped(TAG_ID.CAPTION);
      p4.activeFormattingElements.clearToLastMarker();
      p4.insertionMode = InsertionMode.IN_TABLE;
      startTagInTable(p4, token);
    }
  } else {
    startTagInBody(p4, token);
  }
}
function endTagInCaption(p4, token) {
  const tn4 = token.tagID;
  switch (tn4) {
    case TAG_ID.CAPTION:
    case TAG_ID.TABLE: {
      if (p4.openElements.hasInTableScope(TAG_ID.CAPTION)) {
        p4.openElements.generateImpliedEndTags();
        p4.openElements.popUntilTagNamePopped(TAG_ID.CAPTION);
        p4.activeFormattingElements.clearToLastMarker();
        p4.insertionMode = InsertionMode.IN_TABLE;
        if (tn4 === TAG_ID.TABLE) {
          endTagInTable(p4, token);
        }
      }
      break;
    }
    case TAG_ID.BODY:
    case TAG_ID.COL:
    case TAG_ID.COLGROUP:
    case TAG_ID.HTML:
    case TAG_ID.TBODY:
    case TAG_ID.TD:
    case TAG_ID.TFOOT:
    case TAG_ID.TH:
    case TAG_ID.THEAD:
    case TAG_ID.TR: {
      break;
    }
    default: {
      endTagInBody(p4, token);
    }
  }
}
function startTagInColumnGroup(p4, token) {
  switch (token.tagID) {
    case TAG_ID.HTML: {
      startTagInBody(p4, token);
      break;
    }
    case TAG_ID.COL: {
      p4._appendElement(token, NS.HTML);
      token.ackSelfClosing = true;
      break;
    }
    case TAG_ID.TEMPLATE: {
      startTagInHead(p4, token);
      break;
    }
    default: {
      tokenInColumnGroup(p4, token);
    }
  }
}
function endTagInColumnGroup(p4, token) {
  switch (token.tagID) {
    case TAG_ID.COLGROUP: {
      if (p4.openElements.currentTagId === TAG_ID.COLGROUP) {
        p4.openElements.pop();
        p4.insertionMode = InsertionMode.IN_TABLE;
      }
      break;
    }
    case TAG_ID.TEMPLATE: {
      templateEndTagInHead(p4, token);
      break;
    }
    case TAG_ID.COL: {
      break;
    }
    default: {
      tokenInColumnGroup(p4, token);
    }
  }
}
function tokenInColumnGroup(p4, token) {
  if (p4.openElements.currentTagId === TAG_ID.COLGROUP) {
    p4.openElements.pop();
    p4.insertionMode = InsertionMode.IN_TABLE;
    p4._processToken(token);
  }
}
function startTagInTableBody(p4, token) {
  switch (token.tagID) {
    case TAG_ID.TR: {
      p4.openElements.clearBackToTableBodyContext();
      p4._insertElement(token, NS.HTML);
      p4.insertionMode = InsertionMode.IN_ROW;
      break;
    }
    case TAG_ID.TH:
    case TAG_ID.TD: {
      p4.openElements.clearBackToTableBodyContext();
      p4._insertFakeElement(TAG_NAMES.TR, TAG_ID.TR);
      p4.insertionMode = InsertionMode.IN_ROW;
      startTagInRow(p4, token);
      break;
    }
    case TAG_ID.CAPTION:
    case TAG_ID.COL:
    case TAG_ID.COLGROUP:
    case TAG_ID.TBODY:
    case TAG_ID.TFOOT:
    case TAG_ID.THEAD: {
      if (p4.openElements.hasTableBodyContextInTableScope()) {
        p4.openElements.clearBackToTableBodyContext();
        p4.openElements.pop();
        p4.insertionMode = InsertionMode.IN_TABLE;
        startTagInTable(p4, token);
      }
      break;
    }
    default: {
      startTagInTable(p4, token);
    }
  }
}
function endTagInTableBody(p4, token) {
  const tn4 = token.tagID;
  switch (token.tagID) {
    case TAG_ID.TBODY:
    case TAG_ID.TFOOT:
    case TAG_ID.THEAD: {
      if (p4.openElements.hasInTableScope(tn4)) {
        p4.openElements.clearBackToTableBodyContext();
        p4.openElements.pop();
        p4.insertionMode = InsertionMode.IN_TABLE;
      }
      break;
    }
    case TAG_ID.TABLE: {
      if (p4.openElements.hasTableBodyContextInTableScope()) {
        p4.openElements.clearBackToTableBodyContext();
        p4.openElements.pop();
        p4.insertionMode = InsertionMode.IN_TABLE;
        endTagInTable(p4, token);
      }
      break;
    }
    case TAG_ID.BODY:
    case TAG_ID.CAPTION:
    case TAG_ID.COL:
    case TAG_ID.COLGROUP:
    case TAG_ID.HTML:
    case TAG_ID.TD:
    case TAG_ID.TH:
    case TAG_ID.TR: {
      break;
    }
    default: {
      endTagInTable(p4, token);
    }
  }
}
function startTagInRow(p4, token) {
  switch (token.tagID) {
    case TAG_ID.TH:
    case TAG_ID.TD: {
      p4.openElements.clearBackToTableRowContext();
      p4._insertElement(token, NS.HTML);
      p4.insertionMode = InsertionMode.IN_CELL;
      p4.activeFormattingElements.insertMarker();
      break;
    }
    case TAG_ID.CAPTION:
    case TAG_ID.COL:
    case TAG_ID.COLGROUP:
    case TAG_ID.TBODY:
    case TAG_ID.TFOOT:
    case TAG_ID.THEAD:
    case TAG_ID.TR: {
      if (p4.openElements.hasInTableScope(TAG_ID.TR)) {
        p4.openElements.clearBackToTableRowContext();
        p4.openElements.pop();
        p4.insertionMode = InsertionMode.IN_TABLE_BODY;
        startTagInTableBody(p4, token);
      }
      break;
    }
    default: {
      startTagInTable(p4, token);
    }
  }
}
function endTagInRow(p4, token) {
  switch (token.tagID) {
    case TAG_ID.TR: {
      if (p4.openElements.hasInTableScope(TAG_ID.TR)) {
        p4.openElements.clearBackToTableRowContext();
        p4.openElements.pop();
        p4.insertionMode = InsertionMode.IN_TABLE_BODY;
      }
      break;
    }
    case TAG_ID.TABLE: {
      if (p4.openElements.hasInTableScope(TAG_ID.TR)) {
        p4.openElements.clearBackToTableRowContext();
        p4.openElements.pop();
        p4.insertionMode = InsertionMode.IN_TABLE_BODY;
        endTagInTableBody(p4, token);
      }
      break;
    }
    case TAG_ID.TBODY:
    case TAG_ID.TFOOT:
    case TAG_ID.THEAD: {
      if (p4.openElements.hasInTableScope(token.tagID) || p4.openElements.hasInTableScope(TAG_ID.TR)) {
        p4.openElements.clearBackToTableRowContext();
        p4.openElements.pop();
        p4.insertionMode = InsertionMode.IN_TABLE_BODY;
        endTagInTableBody(p4, token);
      }
      break;
    }
    case TAG_ID.BODY:
    case TAG_ID.CAPTION:
    case TAG_ID.COL:
    case TAG_ID.COLGROUP:
    case TAG_ID.HTML:
    case TAG_ID.TD:
    case TAG_ID.TH: {
      break;
    }
    default: {
      endTagInTable(p4, token);
    }
  }
}
function startTagInCell(p4, token) {
  const tn4 = token.tagID;
  if (TABLE_VOID_ELEMENTS.has(tn4)) {
    if (p4.openElements.hasInTableScope(TAG_ID.TD) || p4.openElements.hasInTableScope(TAG_ID.TH)) {
      p4._closeTableCell();
      startTagInRow(p4, token);
    }
  } else {
    startTagInBody(p4, token);
  }
}
function endTagInCell(p4, token) {
  const tn4 = token.tagID;
  switch (tn4) {
    case TAG_ID.TD:
    case TAG_ID.TH: {
      if (p4.openElements.hasInTableScope(tn4)) {
        p4.openElements.generateImpliedEndTags();
        p4.openElements.popUntilTagNamePopped(tn4);
        p4.activeFormattingElements.clearToLastMarker();
        p4.insertionMode = InsertionMode.IN_ROW;
      }
      break;
    }
    case TAG_ID.TABLE:
    case TAG_ID.TBODY:
    case TAG_ID.TFOOT:
    case TAG_ID.THEAD:
    case TAG_ID.TR: {
      if (p4.openElements.hasInTableScope(tn4)) {
        p4._closeTableCell();
        endTagInRow(p4, token);
      }
      break;
    }
    case TAG_ID.BODY:
    case TAG_ID.CAPTION:
    case TAG_ID.COL:
    case TAG_ID.COLGROUP:
    case TAG_ID.HTML: {
      break;
    }
    default: {
      endTagInBody(p4, token);
    }
  }
}
function startTagInSelect(p4, token) {
  switch (token.tagID) {
    case TAG_ID.HTML: {
      startTagInBody(p4, token);
      break;
    }
    case TAG_ID.OPTION: {
      if (p4.openElements.currentTagId === TAG_ID.OPTION) {
        p4.openElements.pop();
      }
      p4._insertElement(token, NS.HTML);
      break;
    }
    case TAG_ID.OPTGROUP: {
      if (p4.openElements.currentTagId === TAG_ID.OPTION) {
        p4.openElements.pop();
      }
      if (p4.openElements.currentTagId === TAG_ID.OPTGROUP) {
        p4.openElements.pop();
      }
      p4._insertElement(token, NS.HTML);
      break;
    }
    case TAG_ID.HR: {
      if (p4.openElements.currentTagId === TAG_ID.OPTION) {
        p4.openElements.pop();
      }
      if (p4.openElements.currentTagId === TAG_ID.OPTGROUP) {
        p4.openElements.pop();
      }
      p4._appendElement(token, NS.HTML);
      token.ackSelfClosing = true;
      break;
    }
    case TAG_ID.INPUT:
    case TAG_ID.KEYGEN:
    case TAG_ID.TEXTAREA:
    case TAG_ID.SELECT: {
      if (p4.openElements.hasInSelectScope(TAG_ID.SELECT)) {
        p4.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
        p4._resetInsertionMode();
        if (token.tagID !== TAG_ID.SELECT) {
          p4._processStartTag(token);
        }
      }
      break;
    }
    case TAG_ID.SCRIPT:
    case TAG_ID.TEMPLATE: {
      startTagInHead(p4, token);
      break;
    }
    default:
  }
}
function endTagInSelect(p4, token) {
  switch (token.tagID) {
    case TAG_ID.OPTGROUP: {
      if (p4.openElements.stackTop > 0 && p4.openElements.currentTagId === TAG_ID.OPTION && p4.openElements.tagIDs[p4.openElements.stackTop - 1] === TAG_ID.OPTGROUP) {
        p4.openElements.pop();
      }
      if (p4.openElements.currentTagId === TAG_ID.OPTGROUP) {
        p4.openElements.pop();
      }
      break;
    }
    case TAG_ID.OPTION: {
      if (p4.openElements.currentTagId === TAG_ID.OPTION) {
        p4.openElements.pop();
      }
      break;
    }
    case TAG_ID.SELECT: {
      if (p4.openElements.hasInSelectScope(TAG_ID.SELECT)) {
        p4.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
        p4._resetInsertionMode();
      }
      break;
    }
    case TAG_ID.TEMPLATE: {
      templateEndTagInHead(p4, token);
      break;
    }
    default:
  }
}
function startTagInSelectInTable(p4, token) {
  const tn4 = token.tagID;
  if (tn4 === TAG_ID.CAPTION || tn4 === TAG_ID.TABLE || tn4 === TAG_ID.TBODY || tn4 === TAG_ID.TFOOT || tn4 === TAG_ID.THEAD || tn4 === TAG_ID.TR || tn4 === TAG_ID.TD || tn4 === TAG_ID.TH) {
    p4.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
    p4._resetInsertionMode();
    p4._processStartTag(token);
  } else {
    startTagInSelect(p4, token);
  }
}
function endTagInSelectInTable(p4, token) {
  const tn4 = token.tagID;
  if (tn4 === TAG_ID.CAPTION || tn4 === TAG_ID.TABLE || tn4 === TAG_ID.TBODY || tn4 === TAG_ID.TFOOT || tn4 === TAG_ID.THEAD || tn4 === TAG_ID.TR || tn4 === TAG_ID.TD || tn4 === TAG_ID.TH) {
    if (p4.openElements.hasInTableScope(tn4)) {
      p4.openElements.popUntilTagNamePopped(TAG_ID.SELECT);
      p4._resetInsertionMode();
      p4.onEndTag(token);
    }
  } else {
    endTagInSelect(p4, token);
  }
}
function startTagInTemplate(p4, token) {
  switch (token.tagID) {
    // First, handle tags that can start without a mode change
    case TAG_ID.BASE:
    case TAG_ID.BASEFONT:
    case TAG_ID.BGSOUND:
    case TAG_ID.LINK:
    case TAG_ID.META:
    case TAG_ID.NOFRAMES:
    case TAG_ID.SCRIPT:
    case TAG_ID.STYLE:
    case TAG_ID.TEMPLATE:
    case TAG_ID.TITLE: {
      startTagInHead(p4, token);
      break;
    }
    // Re-process the token in the appropriate mode
    case TAG_ID.CAPTION:
    case TAG_ID.COLGROUP:
    case TAG_ID.TBODY:
    case TAG_ID.TFOOT:
    case TAG_ID.THEAD: {
      p4.tmplInsertionModeStack[0] = InsertionMode.IN_TABLE;
      p4.insertionMode = InsertionMode.IN_TABLE;
      startTagInTable(p4, token);
      break;
    }
    case TAG_ID.COL: {
      p4.tmplInsertionModeStack[0] = InsertionMode.IN_COLUMN_GROUP;
      p4.insertionMode = InsertionMode.IN_COLUMN_GROUP;
      startTagInColumnGroup(p4, token);
      break;
    }
    case TAG_ID.TR: {
      p4.tmplInsertionModeStack[0] = InsertionMode.IN_TABLE_BODY;
      p4.insertionMode = InsertionMode.IN_TABLE_BODY;
      startTagInTableBody(p4, token);
      break;
    }
    case TAG_ID.TD:
    case TAG_ID.TH: {
      p4.tmplInsertionModeStack[0] = InsertionMode.IN_ROW;
      p4.insertionMode = InsertionMode.IN_ROW;
      startTagInRow(p4, token);
      break;
    }
    default: {
      p4.tmplInsertionModeStack[0] = InsertionMode.IN_BODY;
      p4.insertionMode = InsertionMode.IN_BODY;
      startTagInBody(p4, token);
    }
  }
}
function endTagInTemplate(p4, token) {
  if (token.tagID === TAG_ID.TEMPLATE) {
    templateEndTagInHead(p4, token);
  }
}
function eofInTemplate(p4, token) {
  if (p4.openElements.tmplCount > 0) {
    p4.openElements.popUntilTagNamePopped(TAG_ID.TEMPLATE);
    p4.activeFormattingElements.clearToLastMarker();
    p4.tmplInsertionModeStack.shift();
    p4._resetInsertionMode();
    p4.onEof(token);
  } else {
    stopParsing(p4, token);
  }
}
function startTagAfterBody(p4, token) {
  if (token.tagID === TAG_ID.HTML) {
    startTagInBody(p4, token);
  } else {
    tokenAfterBody(p4, token);
  }
}
function endTagAfterBody(p4, token) {
  var _a2;
  if (token.tagID === TAG_ID.HTML) {
    if (!p4.fragmentContext) {
      p4.insertionMode = InsertionMode.AFTER_AFTER_BODY;
    }
    if (p4.options.sourceCodeLocationInfo && p4.openElements.tagIDs[0] === TAG_ID.HTML) {
      p4._setEndLocation(p4.openElements.items[0], token);
      const bodyElement = p4.openElements.items[1];
      if (bodyElement && !((_a2 = p4.treeAdapter.getNodeSourceCodeLocation(bodyElement)) === null || _a2 === void 0 ? void 0 : _a2.endTag)) {
        p4._setEndLocation(bodyElement, token);
      }
    }
  } else {
    tokenAfterBody(p4, token);
  }
}
function tokenAfterBody(p4, token) {
  p4.insertionMode = InsertionMode.IN_BODY;
  modeInBody(p4, token);
}
function startTagInFrameset(p4, token) {
  switch (token.tagID) {
    case TAG_ID.HTML: {
      startTagInBody(p4, token);
      break;
    }
    case TAG_ID.FRAMESET: {
      p4._insertElement(token, NS.HTML);
      break;
    }
    case TAG_ID.FRAME: {
      p4._appendElement(token, NS.HTML);
      token.ackSelfClosing = true;
      break;
    }
    case TAG_ID.NOFRAMES: {
      startTagInHead(p4, token);
      break;
    }
    default:
  }
}
function endTagInFrameset(p4, token) {
  if (token.tagID === TAG_ID.FRAMESET && !p4.openElements.isRootHtmlElementCurrent()) {
    p4.openElements.pop();
    if (!p4.fragmentContext && p4.openElements.currentTagId !== TAG_ID.FRAMESET) {
      p4.insertionMode = InsertionMode.AFTER_FRAMESET;
    }
  }
}
function startTagAfterFrameset(p4, token) {
  switch (token.tagID) {
    case TAG_ID.HTML: {
      startTagInBody(p4, token);
      break;
    }
    case TAG_ID.NOFRAMES: {
      startTagInHead(p4, token);
      break;
    }
    default:
  }
}
function endTagAfterFrameset(p4, token) {
  if (token.tagID === TAG_ID.HTML) {
    p4.insertionMode = InsertionMode.AFTER_AFTER_FRAMESET;
  }
}
function startTagAfterAfterBody(p4, token) {
  if (token.tagID === TAG_ID.HTML) {
    startTagInBody(p4, token);
  } else {
    tokenAfterAfterBody(p4, token);
  }
}
function tokenAfterAfterBody(p4, token) {
  p4.insertionMode = InsertionMode.IN_BODY;
  modeInBody(p4, token);
}
function startTagAfterAfterFrameset(p4, token) {
  switch (token.tagID) {
    case TAG_ID.HTML: {
      startTagInBody(p4, token);
      break;
    }
    case TAG_ID.NOFRAMES: {
      startTagInHead(p4, token);
      break;
    }
    default:
  }
}
function nullCharacterInForeignContent(p4, token) {
  token.chars = REPLACEMENT_CHARACTER;
  p4._insertCharacters(token);
}
function characterInForeignContent(p4, token) {
  p4._insertCharacters(token);
  p4.framesetOk = false;
}
function popUntilHtmlOrIntegrationPoint(p4) {
  while (p4.treeAdapter.getNamespaceURI(p4.openElements.current) !== NS.HTML && p4.openElements.currentTagId !== void 0 && !p4._isIntegrationPoint(p4.openElements.currentTagId, p4.openElements.current)) {
    p4.openElements.pop();
  }
}
function startTagInForeignContent(p4, token) {
  if (causesExit(token)) {
    popUntilHtmlOrIntegrationPoint(p4);
    p4._startTagOutsideForeignContent(token);
  } else {
    const current = p4._getAdjustedCurrentElement();
    const currentNs = p4.treeAdapter.getNamespaceURI(current);
    if (currentNs === NS.MATHML) {
      adjustTokenMathMLAttrs(token);
    } else if (currentNs === NS.SVG) {
      adjustTokenSVGTagName(token);
      adjustTokenSVGAttrs(token);
    }
    adjustTokenXMLAttrs(token);
    if (token.selfClosing) {
      p4._appendElement(token, currentNs);
    } else {
      p4._insertElement(token, currentNs);
    }
    token.ackSelfClosing = true;
  }
}
function endTagInForeignContent(p4, token) {
  if (token.tagID === TAG_ID.P || token.tagID === TAG_ID.BR) {
    popUntilHtmlOrIntegrationPoint(p4);
    p4._endTagOutsideForeignContent(token);
    return;
  }
  for (let i3 = p4.openElements.stackTop; i3 > 0; i3--) {
    const element7 = p4.openElements.items[i3];
    if (p4.treeAdapter.getNamespaceURI(element7) === NS.HTML) {
      p4._endTagOutsideForeignContent(token);
      break;
    }
    const tagName = p4.treeAdapter.getTagName(element7);
    if (tagName.toLowerCase() === token.tagName) {
      token.tagName = tagName;
      p4.openElements.shortenToLength(i3);
      break;
    }
  }
}

// ../../node_modules/.pnpm/entities@6.0.1/node_modules/entities/dist/esm/escape.js
var xmlCodeMap = /* @__PURE__ */ new Map([
  [34, "&quot;"],
  [38, "&amp;"],
  [39, "&apos;"],
  [60, "&lt;"],
  [62, "&gt;"]
]);
var getCodePoint = (
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  String.prototype.codePointAt == null ? (c3, index4) => (c3.charCodeAt(index4) & 64512) === 55296 ? (c3.charCodeAt(index4) - 55296) * 1024 + c3.charCodeAt(index4 + 1) - 56320 + 65536 : c3.charCodeAt(index4) : (
    // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
    (input2, index4) => input2.codePointAt(index4)
  )
);
function getEscaper(regex, map7) {
  return function escape2(data) {
    let match2;
    let lastIndex = 0;
    let result = "";
    while (match2 = regex.exec(data)) {
      if (lastIndex !== match2.index) {
        result += data.substring(lastIndex, match2.index);
      }
      result += map7.get(match2[0].charCodeAt(0));
      lastIndex = match2.index + 1;
    }
    return result + data.substring(lastIndex);
  };
}
var escapeUTF8 = getEscaper(/["&'<>]/g, xmlCodeMap);
var escapeAttribute = getEscaper(/["&\u00A0]/g, /* @__PURE__ */ new Map([
  [34, "&quot;"],
  [38, "&amp;"],
  [160, "&nbsp;"]
]));
var escapeText = getEscaper(/[&<>\u00A0]/g, /* @__PURE__ */ new Map([
  [38, "&amp;"],
  [60, "&lt;"],
  [62, "&gt;"],
  [160, "&nbsp;"]
]));

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/serializer/index.js
var VOID_ELEMENTS = /* @__PURE__ */ new Set([
  TAG_NAMES.AREA,
  TAG_NAMES.BASE,
  TAG_NAMES.BASEFONT,
  TAG_NAMES.BGSOUND,
  TAG_NAMES.BR,
  TAG_NAMES.COL,
  TAG_NAMES.EMBED,
  TAG_NAMES.FRAME,
  TAG_NAMES.HR,
  TAG_NAMES.IMG,
  TAG_NAMES.INPUT,
  TAG_NAMES.KEYGEN,
  TAG_NAMES.LINK,
  TAG_NAMES.META,
  TAG_NAMES.PARAM,
  TAG_NAMES.SOURCE,
  TAG_NAMES.TRACK,
  TAG_NAMES.WBR
]);

// ../../node_modules/.pnpm/parse5@7.3.0/node_modules/parse5/dist/index.js
function parse4(html7, options2) {
  return Parser.parse(html7, options2);
}
function parseFragment(fragmentContext, html7, options2) {
  if (typeof fragmentContext === "string") {
    options2 = html7;
    html7 = fragmentContext;
    fragmentContext = null;
  }
  const parser = Parser.getFragmentParser(fragmentContext, options2);
  parser.tokenizer.write(html7, true);
  return parser.getFragment();
}

// ../../node_modules/.pnpm/unist-util-stringify-position@4.0.0/node_modules/unist-util-stringify-position/lib/index.js
function stringifyPosition(value) {
  if (!value || typeof value !== "object") {
    return "";
  }
  if ("position" in value || "type" in value) {
    return position2(value.position);
  }
  if ("start" in value || "end" in value) {
    return position2(value);
  }
  if ("line" in value || "column" in value) {
    return point2(value);
  }
  return "";
}
function point2(point5) {
  return index(point5 && point5.line) + ":" + index(point5 && point5.column);
}
function position2(pos) {
  return point2(pos && pos.start) + "-" + point2(pos && pos.end);
}
function index(value) {
  return value && typeof value === "number" ? value : 1;
}

// ../../node_modules/.pnpm/vfile-message@4.0.3/node_modules/vfile-message/lib/index.js
var VFileMessage = class extends Error {
  /**
   * Create a message for `reason`.
   *
   * > 🪦 **Note**: also has obsolete signatures.
   *
   * @overload
   * @param {string} reason
   * @param {Options | null | undefined} [options]
   * @returns
   *
   * @overload
   * @param {string} reason
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @overload
   * @param {string} reason
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @overload
   * @param {string} reason
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @param {Error | VFileMessage | string} causeOrReason
   *   Reason for message, should use markdown.
   * @param {Node | NodeLike | Options | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
   *   Configuration (optional).
   * @param {string | null | undefined} [origin]
   *   Place in code where the message originates (example:
   *   `'my-package:my-rule'` or `'my-rule'`).
   * @returns
   *   Instance of `VFileMessage`.
   */
  // eslint-disable-next-line complexity
  constructor(causeOrReason, optionsOrParentOrPlace, origin) {
    super();
    if (typeof optionsOrParentOrPlace === "string") {
      origin = optionsOrParentOrPlace;
      optionsOrParentOrPlace = void 0;
    }
    let reason = "";
    let options2 = {};
    let legacyCause = false;
    if (optionsOrParentOrPlace) {
      if ("line" in optionsOrParentOrPlace && "column" in optionsOrParentOrPlace) {
        options2 = { place: optionsOrParentOrPlace };
      } else if ("start" in optionsOrParentOrPlace && "end" in optionsOrParentOrPlace) {
        options2 = { place: optionsOrParentOrPlace };
      } else if ("type" in optionsOrParentOrPlace) {
        options2 = {
          ancestors: [optionsOrParentOrPlace],
          place: optionsOrParentOrPlace.position
        };
      } else {
        options2 = { ...optionsOrParentOrPlace };
      }
    }
    if (typeof causeOrReason === "string") {
      reason = causeOrReason;
    } else if (!options2.cause && causeOrReason) {
      legacyCause = true;
      reason = causeOrReason.message;
      options2.cause = causeOrReason;
    }
    if (!options2.ruleId && !options2.source && typeof origin === "string") {
      const index4 = origin.indexOf(":");
      if (index4 === -1) {
        options2.ruleId = origin;
      } else {
        options2.source = origin.slice(0, index4);
        options2.ruleId = origin.slice(index4 + 1);
      }
    }
    if (!options2.place && options2.ancestors && options2.ancestors) {
      const parent = options2.ancestors[options2.ancestors.length - 1];
      if (parent) {
        options2.place = parent.position;
      }
    }
    const start = options2.place && "start" in options2.place ? options2.place.start : options2.place;
    this.ancestors = options2.ancestors || void 0;
    this.cause = options2.cause || void 0;
    this.column = start ? start.column : void 0;
    this.fatal = void 0;
    this.file = "";
    this.message = reason;
    this.line = start ? start.line : void 0;
    this.name = stringifyPosition(options2.place) || "1:1";
    this.place = options2.place || void 0;
    this.reason = this.message;
    this.ruleId = options2.ruleId || void 0;
    this.source = options2.source || void 0;
    this.stack = legacyCause && options2.cause && typeof options2.cause.stack === "string" ? options2.cause.stack : "";
    this.actual = void 0;
    this.expected = void 0;
    this.note = void 0;
    this.url = void 0;
  }
};
VFileMessage.prototype.file = "";
VFileMessage.prototype.name = "";
VFileMessage.prototype.reason = "";
VFileMessage.prototype.message = "";
VFileMessage.prototype.stack = "";
VFileMessage.prototype.column = void 0;
VFileMessage.prototype.line = void 0;
VFileMessage.prototype.ancestors = void 0;
VFileMessage.prototype.cause = void 0;
VFileMessage.prototype.fatal = void 0;
VFileMessage.prototype.place = void 0;
VFileMessage.prototype.ruleId = void 0;
VFileMessage.prototype.source = void 0;

// ../../node_modules/.pnpm/vfile@6.0.3/node_modules/vfile/lib/minpath.browser.js
var minpath = { basename, dirname, extname, join: join2, sep: "/" };
function basename(path2, extname2) {
  if (extname2 !== void 0 && typeof extname2 !== "string") {
    throw new TypeError('"ext" argument must be a string');
  }
  assertPath(path2);
  let start = 0;
  let end = -1;
  let index4 = path2.length;
  let seenNonSlash;
  if (extname2 === void 0 || extname2.length === 0 || extname2.length > path2.length) {
    while (index4--) {
      if (path2.codePointAt(index4) === 47) {
        if (seenNonSlash) {
          start = index4 + 1;
          break;
        }
      } else if (end < 0) {
        seenNonSlash = true;
        end = index4 + 1;
      }
    }
    return end < 0 ? "" : path2.slice(start, end);
  }
  if (extname2 === path2) {
    return "";
  }
  let firstNonSlashEnd = -1;
  let extnameIndex = extname2.length - 1;
  while (index4--) {
    if (path2.codePointAt(index4) === 47) {
      if (seenNonSlash) {
        start = index4 + 1;
        break;
      }
    } else {
      if (firstNonSlashEnd < 0) {
        seenNonSlash = true;
        firstNonSlashEnd = index4 + 1;
      }
      if (extnameIndex > -1) {
        if (path2.codePointAt(index4) === extname2.codePointAt(extnameIndex--)) {
          if (extnameIndex < 0) {
            end = index4;
          }
        } else {
          extnameIndex = -1;
          end = firstNonSlashEnd;
        }
      }
    }
  }
  if (start === end) {
    end = firstNonSlashEnd;
  } else if (end < 0) {
    end = path2.length;
  }
  return path2.slice(start, end);
}
function dirname(path2) {
  assertPath(path2);
  if (path2.length === 0) {
    return ".";
  }
  let end = -1;
  let index4 = path2.length;
  let unmatchedSlash;
  while (--index4) {
    if (path2.codePointAt(index4) === 47) {
      if (unmatchedSlash) {
        end = index4;
        break;
      }
    } else if (!unmatchedSlash) {
      unmatchedSlash = true;
    }
  }
  return end < 0 ? path2.codePointAt(0) === 47 ? "/" : "." : end === 1 && path2.codePointAt(0) === 47 ? "//" : path2.slice(0, end);
}
function extname(path2) {
  assertPath(path2);
  let index4 = path2.length;
  let end = -1;
  let startPart = 0;
  let startDot = -1;
  let preDotState = 0;
  let unmatchedSlash;
  while (index4--) {
    const code5 = path2.codePointAt(index4);
    if (code5 === 47) {
      if (unmatchedSlash) {
        startPart = index4 + 1;
        break;
      }
      continue;
    }
    if (end < 0) {
      unmatchedSlash = true;
      end = index4 + 1;
    }
    if (code5 === 46) {
      if (startDot < 0) {
        startDot = index4;
      } else if (preDotState !== 1) {
        preDotState = 1;
      }
    } else if (startDot > -1) {
      preDotState = -1;
    }
  }
  if (startDot < 0 || end < 0 || // We saw a non-dot character immediately before the dot.
  preDotState === 0 || // The (right-most) trimmed path component is exactly `..`.
  preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
    return "";
  }
  return path2.slice(startDot, end);
}
function join2(...segments) {
  let index4 = -1;
  let joined;
  while (++index4 < segments.length) {
    assertPath(segments[index4]);
    if (segments[index4]) {
      joined = joined === void 0 ? segments[index4] : joined + "/" + segments[index4];
    }
  }
  return joined === void 0 ? "." : normalize3(joined);
}
function normalize3(path2) {
  assertPath(path2);
  const absolute = path2.codePointAt(0) === 47;
  let value = normalizeString(path2, !absolute);
  if (value.length === 0 && !absolute) {
    value = ".";
  }
  if (value.length > 0 && path2.codePointAt(path2.length - 1) === 47) {
    value += "/";
  }
  return absolute ? "/" + value : value;
}
function normalizeString(path2, allowAboveRoot) {
  let result = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let index4 = -1;
  let code5;
  let lastSlashIndex;
  while (++index4 <= path2.length) {
    if (index4 < path2.length) {
      code5 = path2.codePointAt(index4);
    } else if (code5 === 47) {
      break;
    } else {
      code5 = 47;
    }
    if (code5 === 47) {
      if (lastSlash === index4 - 1 || dots === 1) {
      } else if (lastSlash !== index4 - 1 && dots === 2) {
        if (result.length < 2 || lastSegmentLength !== 2 || result.codePointAt(result.length - 1) !== 46 || result.codePointAt(result.length - 2) !== 46) {
          if (result.length > 2) {
            lastSlashIndex = result.lastIndexOf("/");
            if (lastSlashIndex !== result.length - 1) {
              if (lastSlashIndex < 0) {
                result = "";
                lastSegmentLength = 0;
              } else {
                result = result.slice(0, lastSlashIndex);
                lastSegmentLength = result.length - 1 - result.lastIndexOf("/");
              }
              lastSlash = index4;
              dots = 0;
              continue;
            }
          } else if (result.length > 0) {
            result = "";
            lastSegmentLength = 0;
            lastSlash = index4;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          result = result.length > 0 ? result + "/.." : "..";
          lastSegmentLength = 2;
        }
      } else {
        if (result.length > 0) {
          result += "/" + path2.slice(lastSlash + 1, index4);
        } else {
          result = path2.slice(lastSlash + 1, index4);
        }
        lastSegmentLength = index4 - lastSlash - 1;
      }
      lastSlash = index4;
      dots = 0;
    } else if (code5 === 46 && dots > -1) {
      dots++;
    } else {
      dots = -1;
    }
  }
  return result;
}
function assertPath(path2) {
  if (typeof path2 !== "string") {
    throw new TypeError(
      "Path must be a string. Received " + JSON.stringify(path2)
    );
  }
}

// ../../node_modules/.pnpm/vfile@6.0.3/node_modules/vfile/lib/minproc.browser.js
var minproc = { cwd };
function cwd() {
  return "/";
}

// ../../node_modules/.pnpm/vfile@6.0.3/node_modules/vfile/lib/minurl.shared.js
function isUrl(fileUrlOrPath) {
  return Boolean(
    fileUrlOrPath !== null && typeof fileUrlOrPath === "object" && "href" in fileUrlOrPath && fileUrlOrPath.href && "protocol" in fileUrlOrPath && fileUrlOrPath.protocol && // @ts-expect-error: indexing is fine.
    fileUrlOrPath.auth === void 0
  );
}

// ../../node_modules/.pnpm/vfile@6.0.3/node_modules/vfile/lib/minurl.browser.js
function urlToPath(path2) {
  if (typeof path2 === "string") {
    path2 = new URL(path2);
  } else if (!isUrl(path2)) {
    const error2 = new TypeError(
      'The "path" argument must be of type string or an instance of URL. Received `' + path2 + "`"
    );
    error2.code = "ERR_INVALID_ARG_TYPE";
    throw error2;
  }
  if (path2.protocol !== "file:") {
    const error2 = new TypeError("The URL must be of scheme file");
    error2.code = "ERR_INVALID_URL_SCHEME";
    throw error2;
  }
  return getPathFromURLPosix(path2);
}
function getPathFromURLPosix(url) {
  if (url.hostname !== "") {
    const error2 = new TypeError(
      'File URL host must be "localhost" or empty on darwin'
    );
    error2.code = "ERR_INVALID_FILE_URL_HOST";
    throw error2;
  }
  const pathname = url.pathname;
  let index4 = -1;
  while (++index4 < pathname.length) {
    if (pathname.codePointAt(index4) === 37 && pathname.codePointAt(index4 + 1) === 50) {
      const third = pathname.codePointAt(index4 + 2);
      if (third === 70 || third === 102) {
        const error2 = new TypeError(
          "File URL path must not include encoded / characters"
        );
        error2.code = "ERR_INVALID_FILE_URL_PATH";
        throw error2;
      }
    }
  }
  return decodeURIComponent(pathname);
}

// ../../node_modules/.pnpm/vfile@6.0.3/node_modules/vfile/lib/index.js
var order = (
  /** @type {const} */
  [
    "history",
    "path",
    "basename",
    "stem",
    "extname",
    "dirname"
  ]
);
var VFile = class {
  /**
   * Create a new virtual file.
   *
   * `options` is treated as:
   *
   * *   `string` or `Uint8Array` — `{value: options}`
   * *   `URL` — `{path: options}`
   * *   `VFile` — shallow copies its data over to the new file
   * *   `object` — all fields are shallow copied over to the new file
   *
   * Path related fields are set in the following order (least specific to
   * most specific): `history`, `path`, `basename`, `stem`, `extname`,
   * `dirname`.
   *
   * You cannot set `dirname` or `extname` without setting either `history`,
   * `path`, `basename`, or `stem` too.
   *
   * @param {Compatible | null | undefined} [value]
   *   File value.
   * @returns
   *   New instance.
   */
  constructor(value) {
    let options2;
    if (!value) {
      options2 = {};
    } else if (isUrl(value)) {
      options2 = { path: value };
    } else if (typeof value === "string" || isUint8Array(value)) {
      options2 = { value };
    } else {
      options2 = value;
    }
    this.cwd = "cwd" in options2 ? "" : minproc.cwd();
    this.data = {};
    this.history = [];
    this.messages = [];
    this.value;
    this.map;
    this.result;
    this.stored;
    let index4 = -1;
    while (++index4 < order.length) {
      const field2 = order[index4];
      if (field2 in options2 && options2[field2] !== void 0 && options2[field2] !== null) {
        this[field2] = field2 === "history" ? [...options2[field2]] : options2[field2];
      }
    }
    let field;
    for (field in options2) {
      if (!order.includes(field)) {
        this[field] = options2[field];
      }
    }
  }
  /**
   * Get the basename (including extname) (example: `'index.min.js'`).
   *
   * @returns {string | undefined}
   *   Basename.
   */
  get basename() {
    return typeof this.path === "string" ? minpath.basename(this.path) : void 0;
  }
  /**
   * Set basename (including extname) (`'index.min.js'`).
   *
   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
   * on windows).
   * Cannot be nullified (use `file.path = file.dirname` instead).
   *
   * @param {string} basename
   *   Basename.
   * @returns {undefined}
   *   Nothing.
   */
  set basename(basename2) {
    assertNonEmpty(basename2, "basename");
    assertPart(basename2, "basename");
    this.path = minpath.join(this.dirname || "", basename2);
  }
  /**
   * Get the parent path (example: `'~'`).
   *
   * @returns {string | undefined}
   *   Dirname.
   */
  get dirname() {
    return typeof this.path === "string" ? minpath.dirname(this.path) : void 0;
  }
  /**
   * Set the parent path (example: `'~'`).
   *
   * Cannot be set if there’s no `path` yet.
   *
   * @param {string | undefined} dirname
   *   Dirname.
   * @returns {undefined}
   *   Nothing.
   */
  set dirname(dirname2) {
    assertPath2(this.basename, "dirname");
    this.path = minpath.join(dirname2 || "", this.basename);
  }
  /**
   * Get the extname (including dot) (example: `'.js'`).
   *
   * @returns {string | undefined}
   *   Extname.
   */
  get extname() {
    return typeof this.path === "string" ? minpath.extname(this.path) : void 0;
  }
  /**
   * Set the extname (including dot) (example: `'.js'`).
   *
   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
   * on windows).
   * Cannot be set if there’s no `path` yet.
   *
   * @param {string | undefined} extname
   *   Extname.
   * @returns {undefined}
   *   Nothing.
   */
  set extname(extname2) {
    assertPart(extname2, "extname");
    assertPath2(this.dirname, "extname");
    if (extname2) {
      if (extname2.codePointAt(0) !== 46) {
        throw new Error("`extname` must start with `.`");
      }
      if (extname2.includes(".", 1)) {
        throw new Error("`extname` cannot contain multiple dots");
      }
    }
    this.path = minpath.join(this.dirname, this.stem + (extname2 || ""));
  }
  /**
   * Get the full path (example: `'~/index.min.js'`).
   *
   * @returns {string}
   *   Path.
   */
  get path() {
    return this.history[this.history.length - 1];
  }
  /**
   * Set the full path (example: `'~/index.min.js'`).
   *
   * Cannot be nullified.
   * You can set a file URL (a `URL` object with a `file:` protocol) which will
   * be turned into a path with `url.fileURLToPath`.
   *
   * @param {URL | string} path
   *   Path.
   * @returns {undefined}
   *   Nothing.
   */
  set path(path2) {
    if (isUrl(path2)) {
      path2 = urlToPath(path2);
    }
    assertNonEmpty(path2, "path");
    if (this.path !== path2) {
      this.history.push(path2);
    }
  }
  /**
   * Get the stem (basename w/o extname) (example: `'index.min'`).
   *
   * @returns {string | undefined}
   *   Stem.
   */
  get stem() {
    return typeof this.path === "string" ? minpath.basename(this.path, this.extname) : void 0;
  }
  /**
   * Set the stem (basename w/o extname) (example: `'index.min'`).
   *
   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
   * on windows).
   * Cannot be nullified (use `file.path = file.dirname` instead).
   *
   * @param {string} stem
   *   Stem.
   * @returns {undefined}
   *   Nothing.
   */
  set stem(stem) {
    assertNonEmpty(stem, "stem");
    assertPart(stem, "stem");
    this.path = minpath.join(this.dirname || "", stem + (this.extname || ""));
  }
  // Normal prototypal methods.
  /**
   * Create a fatal message for `reason` associated with the file.
   *
   * The `fatal` field of the message is set to `true` (error; file not usable)
   * and the `file` field is set to the current file path.
   * The message is added to the `messages` field on `file`.
   *
   * > 🪦 **Note**: also has obsolete signatures.
   *
   * @overload
   * @param {string} reason
   * @param {MessageOptions | null | undefined} [options]
   * @returns {never}
   *
   * @overload
   * @param {string} reason
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @overload
   * @param {string} reason
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @overload
   * @param {string} reason
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @param {Error | VFileMessage | string} causeOrReason
   *   Reason for message, should use markdown.
   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
   *   Configuration (optional).
   * @param {string | null | undefined} [origin]
   *   Place in code where the message originates (example:
   *   `'my-package:my-rule'` or `'my-rule'`).
   * @returns {never}
   *   Never.
   * @throws {VFileMessage}
   *   Message.
   */
  fail(causeOrReason, optionsOrParentOrPlace, origin) {
    const message = this.message(causeOrReason, optionsOrParentOrPlace, origin);
    message.fatal = true;
    throw message;
  }
  /**
   * Create an info message for `reason` associated with the file.
   *
   * The `fatal` field of the message is set to `undefined` (info; change
   * likely not needed) and the `file` field is set to the current file path.
   * The message is added to the `messages` field on `file`.
   *
   * > 🪦 **Note**: also has obsolete signatures.
   *
   * @overload
   * @param {string} reason
   * @param {MessageOptions | null | undefined} [options]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @param {Error | VFileMessage | string} causeOrReason
   *   Reason for message, should use markdown.
   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
   *   Configuration (optional).
   * @param {string | null | undefined} [origin]
   *   Place in code where the message originates (example:
   *   `'my-package:my-rule'` or `'my-rule'`).
   * @returns {VFileMessage}
   *   Message.
   */
  info(causeOrReason, optionsOrParentOrPlace, origin) {
    const message = this.message(causeOrReason, optionsOrParentOrPlace, origin);
    message.fatal = void 0;
    return message;
  }
  /**
   * Create a message for `reason` associated with the file.
   *
   * The `fatal` field of the message is set to `false` (warning; change may be
   * needed) and the `file` field is set to the current file path.
   * The message is added to the `messages` field on `file`.
   *
   * > 🪦 **Note**: also has obsolete signatures.
   *
   * @overload
   * @param {string} reason
   * @param {MessageOptions | null | undefined} [options]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @param {Error | VFileMessage | string} causeOrReason
   *   Reason for message, should use markdown.
   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
   *   Configuration (optional).
   * @param {string | null | undefined} [origin]
   *   Place in code where the message originates (example:
   *   `'my-package:my-rule'` or `'my-rule'`).
   * @returns {VFileMessage}
   *   Message.
   */
  message(causeOrReason, optionsOrParentOrPlace, origin) {
    const message = new VFileMessage(
      // @ts-expect-error: the overloads are fine.
      causeOrReason,
      optionsOrParentOrPlace,
      origin
    );
    if (this.path) {
      message.name = this.path + ":" + message.name;
      message.file = this.path;
    }
    message.fatal = false;
    this.messages.push(message);
    return message;
  }
  /**
   * Serialize the file.
   *
   * > **Note**: which encodings are supported depends on the engine.
   * > For info on Node.js, see:
   * > <https://nodejs.org/api/util.html#whatwg-supported-encodings>.
   *
   * @param {string | null | undefined} [encoding='utf8']
   *   Character encoding to understand `value` as when it’s a `Uint8Array`
   *   (default: `'utf-8'`).
   * @returns {string}
   *   Serialized file.
   */
  toString(encoding) {
    if (this.value === void 0) {
      return "";
    }
    if (typeof this.value === "string") {
      return this.value;
    }
    const decoder = new TextDecoder(encoding || void 0);
    return decoder.decode(this.value);
  }
};
function assertPart(part, name) {
  if (part && part.includes(minpath.sep)) {
    throw new Error(
      "`" + name + "` cannot be a path: did not expect `" + minpath.sep + "`"
    );
  }
}
function assertNonEmpty(part, name) {
  if (!part) {
    throw new Error("`" + name + "` cannot be empty");
  }
}
function assertPath2(path2, name) {
  if (!path2) {
    throw new Error("Setting `" + name + "` requires `path` to be set too");
  }
}
function isUint8Array(value) {
  return Boolean(
    value && typeof value === "object" && "byteLength" in value && "byteOffset" in value
  );
}

// ../../node_modules/.pnpm/hast-util-from-html@2.0.3/node_modules/hast-util-from-html/lib/errors.js
var errors = {
  /** @type {ErrorInfo} */
  abandonedHeadElementChild: {
    reason: "Unexpected metadata element after head",
    description: "Unexpected element after head. Expected the element before `</head>`",
    url: false
  },
  /** @type {ErrorInfo} */
  abruptClosingOfEmptyComment: {
    reason: "Unexpected abruptly closed empty comment",
    description: "Unexpected `>` or `->`. Expected `-->` to close comments"
  },
  /** @type {ErrorInfo} */
  abruptDoctypePublicIdentifier: {
    reason: "Unexpected abruptly closed public identifier",
    description: "Unexpected `>`. Expected a closing `\"` or `'` after the public identifier"
  },
  /** @type {ErrorInfo} */
  abruptDoctypeSystemIdentifier: {
    reason: "Unexpected abruptly closed system identifier",
    description: "Unexpected `>`. Expected a closing `\"` or `'` after the identifier identifier"
  },
  /** @type {ErrorInfo} */
  absenceOfDigitsInNumericCharacterReference: {
    reason: "Unexpected non-digit at start of numeric character reference",
    description: "Unexpected `%c`. Expected `[0-9]` for decimal references or `[0-9a-fA-F]` for hexadecimal references"
  },
  /** @type {ErrorInfo} */
  cdataInHtmlContent: {
    reason: "Unexpected CDATA section in HTML",
    description: "Unexpected `<![CDATA[` in HTML. Remove it, use a comment, or encode special characters instead"
  },
  /** @type {ErrorInfo} */
  characterReferenceOutsideUnicodeRange: {
    reason: "Unexpected too big numeric character reference",
    description: "Unexpectedly high character reference. Expected character references to be at most hexadecimal 10ffff (or decimal 1114111)"
  },
  /** @type {ErrorInfo} */
  closingOfElementWithOpenChildElements: {
    reason: "Unexpected closing tag with open child elements",
    description: "Unexpectedly closing tag. Expected other tags to be closed first",
    url: false
  },
  /** @type {ErrorInfo} */
  controlCharacterInInputStream: {
    reason: "Unexpected control character",
    description: "Unexpected control character `%x`. Expected a non-control code point, 0x00, or ASCII whitespace"
  },
  /** @type {ErrorInfo} */
  controlCharacterReference: {
    reason: "Unexpected control character reference",
    description: "Unexpectedly control character in reference. Expected a non-control code point, 0x00, or ASCII whitespace"
  },
  /** @type {ErrorInfo} */
  disallowedContentInNoscriptInHead: {
    reason: "Disallowed content inside `<noscript>` in `<head>`",
    description: "Unexpected text character `%c`. Only use text in `<noscript>`s in `<body>`",
    url: false
  },
  /** @type {ErrorInfo} */
  duplicateAttribute: {
    reason: "Unexpected duplicate attribute",
    description: "Unexpectedly double attribute. Expected attributes to occur only once"
  },
  /** @type {ErrorInfo} */
  endTagWithAttributes: {
    reason: "Unexpected attribute on closing tag",
    description: "Unexpected attribute. Expected `>` instead"
  },
  /** @type {ErrorInfo} */
  endTagWithTrailingSolidus: {
    reason: "Unexpected slash at end of closing tag",
    description: "Unexpected `%c-1`. Expected `>` instead"
  },
  /** @type {ErrorInfo} */
  endTagWithoutMatchingOpenElement: {
    reason: "Unexpected unopened end tag",
    description: "Unexpected end tag. Expected no end tag or another end tag",
    url: false
  },
  /** @type {ErrorInfo} */
  eofBeforeTagName: {
    reason: "Unexpected end of file",
    description: "Unexpected end of file. Expected tag name instead"
  },
  /** @type {ErrorInfo} */
  eofInCdata: {
    reason: "Unexpected end of file in CDATA",
    description: "Unexpected end of file. Expected `]]>` to close the CDATA"
  },
  /** @type {ErrorInfo} */
  eofInComment: {
    reason: "Unexpected end of file in comment",
    description: "Unexpected end of file. Expected `-->` to close the comment"
  },
  /** @type {ErrorInfo} */
  eofInDoctype: {
    reason: "Unexpected end of file in doctype",
    description: "Unexpected end of file. Expected a valid doctype (such as `<!doctype html>`)"
  },
  /** @type {ErrorInfo} */
  eofInElementThatCanContainOnlyText: {
    reason: "Unexpected end of file in element that can only contain text",
    description: "Unexpected end of file. Expected text or a closing tag",
    url: false
  },
  /** @type {ErrorInfo} */
  eofInScriptHtmlCommentLikeText: {
    reason: "Unexpected end of file in comment inside script",
    description: "Unexpected end of file. Expected `-->` to close the comment"
  },
  /** @type {ErrorInfo} */
  eofInTag: {
    reason: "Unexpected end of file in tag",
    description: "Unexpected end of file. Expected `>` to close the tag"
  },
  /** @type {ErrorInfo} */
  incorrectlyClosedComment: {
    reason: "Incorrectly closed comment",
    description: "Unexpected `%c-1`. Expected `-->` to close the comment"
  },
  /** @type {ErrorInfo} */
  incorrectlyOpenedComment: {
    reason: "Incorrectly opened comment",
    description: "Unexpected `%c`. Expected `<!--` to open the comment"
  },
  /** @type {ErrorInfo} */
  invalidCharacterSequenceAfterDoctypeName: {
    reason: "Invalid sequence after doctype name",
    description: "Unexpected sequence at `%c`. Expected `public` or `system`"
  },
  /** @type {ErrorInfo} */
  invalidFirstCharacterOfTagName: {
    reason: "Invalid first character in tag name",
    description: "Unexpected `%c`. Expected an ASCII letter instead"
  },
  /** @type {ErrorInfo} */
  misplacedDoctype: {
    reason: "Misplaced doctype",
    description: "Unexpected doctype. Expected doctype before head",
    url: false
  },
  /** @type {ErrorInfo} */
  misplacedStartTagForHeadElement: {
    reason: "Misplaced `<head>` start tag",
    description: "Unexpected start tag `<head>`. Expected `<head>` directly after doctype",
    url: false
  },
  /** @type {ErrorInfo} */
  missingAttributeValue: {
    reason: "Missing attribute value",
    description: "Unexpected `%c-1`. Expected an attribute value or no `%c-1` instead"
  },
  /** @type {ErrorInfo} */
  missingDoctype: {
    reason: "Missing doctype before other content",
    description: "Expected a `<!doctype html>` before anything else",
    url: false
  },
  /** @type {ErrorInfo} */
  missingDoctypeName: {
    reason: "Missing doctype name",
    description: "Unexpected doctype end at `%c`. Expected `html` instead"
  },
  /** @type {ErrorInfo} */
  missingDoctypePublicIdentifier: {
    reason: "Missing public identifier in doctype",
    description: "Unexpected `%c`. Expected identifier for `public` instead"
  },
  /** @type {ErrorInfo} */
  missingDoctypeSystemIdentifier: {
    reason: "Missing system identifier in doctype",
    description: 'Unexpected `%c`. Expected identifier for `system` instead (suggested: `"about:legacy-compat"`)'
  },
  /** @type {ErrorInfo} */
  missingEndTagName: {
    reason: "Missing name in end tag",
    description: "Unexpected `%c`. Expected an ASCII letter instead"
  },
  /** @type {ErrorInfo} */
  missingQuoteBeforeDoctypePublicIdentifier: {
    reason: "Missing quote before public identifier in doctype",
    description: "Unexpected `%c`. Expected `\"` or `'` instead"
  },
  /** @type {ErrorInfo} */
  missingQuoteBeforeDoctypeSystemIdentifier: {
    reason: "Missing quote before system identifier in doctype",
    description: "Unexpected `%c`. Expected `\"` or `'` instead"
  },
  /** @type {ErrorInfo} */
  missingSemicolonAfterCharacterReference: {
    reason: "Missing semicolon after character reference",
    description: "Unexpected `%c`. Expected `;` instead"
  },
  /** @type {ErrorInfo} */
  missingWhitespaceAfterDoctypePublicKeyword: {
    reason: "Missing whitespace after public identifier in doctype",
    description: "Unexpected `%c`. Expected ASCII whitespace instead"
  },
  /** @type {ErrorInfo} */
  missingWhitespaceAfterDoctypeSystemKeyword: {
    reason: "Missing whitespace after system identifier in doctype",
    description: "Unexpected `%c`. Expected ASCII whitespace instead"
  },
  /** @type {ErrorInfo} */
  missingWhitespaceBeforeDoctypeName: {
    reason: "Missing whitespace before doctype name",
    description: "Unexpected `%c`. Expected ASCII whitespace instead"
  },
  /** @type {ErrorInfo} */
  missingWhitespaceBetweenAttributes: {
    reason: "Missing whitespace between attributes",
    description: "Unexpected `%c`. Expected ASCII whitespace instead"
  },
  /** @type {ErrorInfo} */
  missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers: {
    reason: "Missing whitespace between public and system identifiers in doctype",
    description: "Unexpected `%c`. Expected ASCII whitespace instead"
  },
  /** @type {ErrorInfo} */
  nestedComment: {
    reason: "Unexpected nested comment",
    description: "Unexpected `<!--`. Expected `-->`"
  },
  /** @type {ErrorInfo} */
  nestedNoscriptInHead: {
    reason: "Unexpected nested `<noscript>` in `<head>`",
    description: "Unexpected `<noscript>`. Expected a closing tag or a meta element",
    url: false
  },
  /** @type {ErrorInfo} */
  nonConformingDoctype: {
    reason: "Unexpected non-conforming doctype declaration",
    description: 'Expected `<!doctype html>` or `<!doctype html system "about:legacy-compat">`',
    url: false
  },
  /** @type {ErrorInfo} */
  nonVoidHtmlElementStartTagWithTrailingSolidus: {
    reason: "Unexpected trailing slash on start tag of non-void element",
    description: "Unexpected `/`. Expected `>` instead"
  },
  /** @type {ErrorInfo} */
  noncharacterCharacterReference: {
    reason: "Unexpected noncharacter code point referenced by character reference",
    description: "Unexpected code point. Do not use noncharacters in HTML"
  },
  /** @type {ErrorInfo} */
  noncharacterInInputStream: {
    reason: "Unexpected noncharacter character",
    description: "Unexpected code point `%x`. Do not use noncharacters in HTML"
  },
  /** @type {ErrorInfo} */
  nullCharacterReference: {
    reason: "Unexpected NULL character referenced by character reference",
    description: "Unexpected code point. Do not use NULL characters in HTML"
  },
  /** @type {ErrorInfo} */
  openElementsLeftAfterEof: {
    reason: "Unexpected end of file",
    description: "Unexpected end of file. Expected closing tag instead",
    url: false
  },
  /** @type {ErrorInfo} */
  surrogateCharacterReference: {
    reason: "Unexpected surrogate character referenced by character reference",
    description: "Unexpected code point. Do not use lone surrogate characters in HTML"
  },
  /** @type {ErrorInfo} */
  surrogateInInputStream: {
    reason: "Unexpected surrogate character",
    description: "Unexpected code point `%x`. Do not use lone surrogate characters in HTML"
  },
  /** @type {ErrorInfo} */
  unexpectedCharacterAfterDoctypeSystemIdentifier: {
    reason: "Invalid character after system identifier in doctype",
    description: "Unexpected character at `%c`. Expected `>`"
  },
  /** @type {ErrorInfo} */
  unexpectedCharacterInAttributeName: {
    reason: "Unexpected character in attribute name",
    description: "Unexpected `%c`. Expected whitespace, `/`, `>`, `=`, or probably an ASCII letter"
  },
  /** @type {ErrorInfo} */
  unexpectedCharacterInUnquotedAttributeValue: {
    reason: "Unexpected character in unquoted attribute value",
    description: "Unexpected `%c`. Quote the attribute value to include it"
  },
  /** @type {ErrorInfo} */
  unexpectedEqualsSignBeforeAttributeName: {
    reason: "Unexpected equals sign before attribute name",
    description: "Unexpected `%c`. Add an attribute name before it"
  },
  /** @type {ErrorInfo} */
  unexpectedNullCharacter: {
    reason: "Unexpected NULL character",
    description: "Unexpected code point `%x`. Do not use NULL characters in HTML"
  },
  /** @type {ErrorInfo} */
  unexpectedQuestionMarkInsteadOfTagName: {
    reason: "Unexpected question mark instead of tag name",
    description: "Unexpected `%c`. Expected an ASCII letter instead"
  },
  /** @type {ErrorInfo} */
  unexpectedSolidusInTag: {
    reason: "Unexpected slash in tag",
    description: "Unexpected `%c-1`. Expected it followed by `>` or in a quoted attribute value"
  },
  /** @type {ErrorInfo} */
  unknownNamedCharacterReference: {
    reason: "Unexpected unknown named character reference",
    description: "Unexpected character reference. Expected known named character references"
  }
};

// ../../node_modules/.pnpm/hast-util-from-html@2.0.3/node_modules/hast-util-from-html/lib/index.js
var base2 = "https://html.spec.whatwg.org/multipage/parsing.html#parse-error-";
var dashToCamelRe = /-[a-z]/g;
var formatCRe = /%c(?:([-+])(\d+))?/g;
var formatXRe = /%x/g;
var fatalities = { 2: true, 1: false, 0: null };
var emptyOptions = {};
function fromHtml(value, options2) {
  const settings = options2 || emptyOptions;
  const onerror = settings.onerror;
  const file = value instanceof VFile ? value : new VFile(value);
  const parseFunction = settings.fragment ? parseFragment : parse4;
  const document4 = String(file);
  const p5Document = parseFunction(document4, {
    sourceCodeLocationInfo: true,
    // Note `parse5` types currently do not allow `undefined`.
    onParseError: settings.onerror ? internalOnerror : null,
    scriptingEnabled: false
  });
  return (
    /** @type {Root} */
    fromParse5(p5Document, {
      file,
      space: settings.space,
      verbose: settings.verbose
    })
  );
  function internalOnerror(error2) {
    const code5 = error2.code;
    const name = camelcase2(code5);
    const setting = settings[name];
    const config = setting === null || setting === void 0 ? true : setting;
    const level = typeof config === "number" ? config : config ? 1 : 0;
    if (level) {
      const info = errors[name];
      ok(info, "expected known error from `parse5`");
      const message = new VFileMessage(format(info.reason), {
        place: {
          start: {
            line: error2.startLine,
            column: error2.startCol,
            offset: error2.startOffset
          },
          end: {
            line: error2.endLine,
            column: error2.endCol,
            offset: error2.endOffset
          }
        },
        ruleId: code5,
        source: "hast-util-from-html"
      });
      if (file.path) {
        message.file = file.path;
        message.name = file.path + ":" + message.name;
      }
      message.fatal = fatalities[level];
      message.note = format(info.description);
      message.url = info.url === false ? void 0 : base2 + code5;
      ok(onerror, "`internalOnerror` is not passed if `onerror` is not set");
      onerror(message);
    }
    function format(value2) {
      return value2.replace(formatCRe, formatC).replace(formatXRe, formatX);
      function formatC(_2, $1, $22) {
        const offset4 = ($22 ? Number.parseInt($22, 10) : 0) * ($1 === "-" ? -1 : 1);
        const char = document4.charAt(error2.startOffset + offset4);
        return visualizeCharacter(char);
      }
      function formatX() {
        return visualizeCharacterCode(document4.charCodeAt(error2.startOffset));
      }
    }
  }
}
function camelcase2(value) {
  return (
    /** @type {ErrorCode} */
    value.replace(dashToCamelRe, dashToCamel)
  );
}
function dashToCamel($0) {
  return $0.charAt(1).toUpperCase();
}
function visualizeCharacter(char) {
  return char === "`" ? "` ` `" : char;
}
function visualizeCharacterCode(charCode) {
  return "0x" + charCode.toString(16).toUpperCase();
}

// ../../node_modules/.pnpm/rehype-parse@9.0.1/node_modules/rehype-parse/lib/index.js
function rehypeParse(options2) {
  const self2 = this;
  const { emitParseErrors, ...settings } = { ...self2.data("settings"), ...options2 };
  self2.parser = parser;
  function parser(document4, file) {
    return fromHtml(document4, {
      ...settings,
      onerror: emitParseErrors ? function(message) {
        if (file.path) {
          message.name = file.path + ":" + message.name;
          message.file = file.path;
        }
        file.messages.push(message);
      } : void 0
    });
  }
}

// ../../node_modules/.pnpm/@ungap+structured-clone@1.3.0/node_modules/@ungap/structured-clone/esm/types.js
var VOID = -1;
var PRIMITIVE = 0;
var ARRAY = 1;
var OBJECT = 2;
var DATE = 3;
var REGEXP = 4;
var MAP = 5;
var SET = 6;
var ERROR = 7;
var BIGINT = 8;

// ../../node_modules/.pnpm/@ungap+structured-clone@1.3.0/node_modules/@ungap/structured-clone/esm/deserialize.js
var env = typeof self === "object" ? self : globalThis;
var deserializer = ($6, _2) => {
  const as = (out, index4) => {
    $6.set(index4, out);
    return out;
  };
  const unpair = (index4) => {
    if ($6.has(index4))
      return $6.get(index4);
    const [type, value] = _2[index4];
    switch (type) {
      case PRIMITIVE:
      case VOID:
        return as(value, index4);
      case ARRAY: {
        const arr = as([], index4);
        for (const index5 of value)
          arr.push(unpair(index5));
        return arr;
      }
      case OBJECT: {
        const object = as({}, index4);
        for (const [key2, index5] of value)
          object[unpair(key2)] = unpair(index5);
        return object;
      }
      case DATE:
        return as(new Date(value), index4);
      case REGEXP: {
        const { source, flags } = value;
        return as(new RegExp(source, flags), index4);
      }
      case MAP: {
        const map7 = as(/* @__PURE__ */ new Map(), index4);
        for (const [key2, index5] of value)
          map7.set(unpair(key2), unpair(index5));
        return map7;
      }
      case SET: {
        const set = as(/* @__PURE__ */ new Set(), index4);
        for (const index5 of value)
          set.add(unpair(index5));
        return set;
      }
      case ERROR: {
        const { name, message } = value;
        return as(new env[name](message), index4);
      }
      case BIGINT:
        return as(BigInt(value), index4);
      case "BigInt":
        return as(Object(BigInt(value)), index4);
      case "ArrayBuffer":
        return as(new Uint8Array(value).buffer, value);
      case "DataView": {
        const { buffer } = new Uint8Array(value);
        return as(new DataView(buffer), value);
      }
    }
    return as(new env[type](value), index4);
  };
  return unpair;
};
var deserialize = (serialized) => deserializer(/* @__PURE__ */ new Map(), serialized)(0);

// ../../node_modules/.pnpm/@ungap+structured-clone@1.3.0/node_modules/@ungap/structured-clone/esm/serialize.js
var EMPTY = "";
var { toString } = {};
var { keys: keys3 } = Object;
var typeOf = (value) => {
  const type = typeof value;
  if (type !== "object" || !value)
    return [PRIMITIVE, type];
  const asString = toString.call(value).slice(8, -1);
  switch (asString) {
    case "Array":
      return [ARRAY, EMPTY];
    case "Object":
      return [OBJECT, EMPTY];
    case "Date":
      return [DATE, EMPTY];
    case "RegExp":
      return [REGEXP, EMPTY];
    case "Map":
      return [MAP, EMPTY];
    case "Set":
      return [SET, EMPTY];
    case "DataView":
      return [ARRAY, asString];
  }
  if (asString.includes("Array"))
    return [ARRAY, asString];
  if (asString.includes("Error"))
    return [ERROR, asString];
  return [OBJECT, asString];
};
var shouldSkip = ([TYPE, type]) => TYPE === PRIMITIVE && (type === "function" || type === "symbol");
var serializer = (strict, json, $6, _2) => {
  const as = (out, value) => {
    const index4 = _2.push(out) - 1;
    $6.set(value, index4);
    return index4;
  };
  const pair = (value) => {
    if ($6.has(value))
      return $6.get(value);
    let [TYPE, type] = typeOf(value);
    switch (TYPE) {
      case PRIMITIVE: {
        let entry = value;
        switch (type) {
          case "bigint":
            TYPE = BIGINT;
            entry = value.toString();
            break;
          case "function":
          case "symbol":
            if (strict)
              throw new TypeError("unable to serialize " + type);
            entry = null;
            break;
          case "undefined":
            return as([VOID], value);
        }
        return as([TYPE, entry], value);
      }
      case ARRAY: {
        if (type) {
          let spread = value;
          if (type === "DataView") {
            spread = new Uint8Array(value.buffer);
          } else if (type === "ArrayBuffer") {
            spread = new Uint8Array(value);
          }
          return as([type, [...spread]], value);
        }
        const arr = [];
        const index4 = as([TYPE, arr], value);
        for (const entry of value)
          arr.push(pair(entry));
        return index4;
      }
      case OBJECT: {
        if (type) {
          switch (type) {
            case "BigInt":
              return as([type, value.toString()], value);
            case "Boolean":
            case "Number":
            case "String":
              return as([type, value.valueOf()], value);
          }
        }
        if (json && "toJSON" in value)
          return pair(value.toJSON());
        const entries = [];
        const index4 = as([TYPE, entries], value);
        for (const key2 of keys3(value)) {
          if (strict || !shouldSkip(typeOf(value[key2])))
            entries.push([pair(key2), pair(value[key2])]);
        }
        return index4;
      }
      case DATE:
        return as([TYPE, value.toISOString()], value);
      case REGEXP: {
        const { source, flags } = value;
        return as([TYPE, { source, flags }], value);
      }
      case MAP: {
        const entries = [];
        const index4 = as([TYPE, entries], value);
        for (const [key2, entry] of value) {
          if (strict || !(shouldSkip(typeOf(key2)) || shouldSkip(typeOf(entry))))
            entries.push([pair(key2), pair(entry)]);
        }
        return index4;
      }
      case SET: {
        const entries = [];
        const index4 = as([TYPE, entries], value);
        for (const entry of value) {
          if (strict || !shouldSkip(typeOf(entry)))
            entries.push(pair(entry));
        }
        return index4;
      }
    }
    const { message } = value;
    return as([TYPE, { name: type, message }], value);
  };
  return pair;
};
var serialize2 = (value, { json, lossy } = {}) => {
  const _2 = [];
  return serializer(!(json || lossy), !!json, /* @__PURE__ */ new Map(), _2)(value), _2;
};

// ../../node_modules/.pnpm/@ungap+structured-clone@1.3.0/node_modules/@ungap/structured-clone/esm/index.js
var esm_default = typeof structuredClone === "function" ? (
  /* c8 ignore start */
  (any2, options2) => options2 && ("json" in options2 || "lossy" in options2) ? deserialize(serialize2(any2, options2)) : structuredClone(any2)
) : (any2, options2) => deserialize(serialize2(any2, options2));

// ../../node_modules/.pnpm/hast-util-is-element@3.0.0/node_modules/hast-util-is-element/lib/index.js
var isElement = (
  // Note: overloads in JSDoc can’t yet use different `@template`s.
  /**
   * @type {(
   *   (<Condition extends TestFunction>(element: unknown, test: Condition, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element & Predicate<Condition, Element>) &
   *   (<Condition extends string>(element: unknown, test: Condition, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element & {tagName: Condition}) &
   *   ((element?: null | undefined) => false) &
   *   ((element: unknown, test?: null | undefined, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element) &
   *   ((element: unknown, test?: Test, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => boolean)
   * )}
   */
  /**
   * @param {unknown} [element]
   * @param {Test | undefined} [test]
   * @param {number | null | undefined} [index]
   * @param {Parents | null | undefined} [parent]
   * @param {unknown} [context]
   * @returns {boolean}
   */
  // eslint-disable-next-line max-params
  (function(element7, test, index4, parent, context) {
    const check = convertElement(test);
    if (index4 !== null && index4 !== void 0 && (typeof index4 !== "number" || index4 < 0 || index4 === Number.POSITIVE_INFINITY)) {
      throw new Error("Expected positive finite `index`");
    }
    if (parent !== null && parent !== void 0 && (!parent.type || !parent.children)) {
      throw new Error("Expected valid `parent`");
    }
    if ((index4 === null || index4 === void 0) !== (parent === null || parent === void 0)) {
      throw new Error("Expected both `index` and `parent`");
    }
    return looksLikeAnElement(element7) ? check.call(context, element7, index4, parent) : false;
  })
);
var convertElement = (
  // Note: overloads in JSDoc can’t yet use different `@template`s.
  /**
   * @type {(
   *   (<Condition extends TestFunction>(test: Condition) => (element: unknown, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element & Predicate<Condition, Element>) &
   *   (<Condition extends string>(test: Condition) => (element: unknown, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element & {tagName: Condition}) &
   *   ((test?: null | undefined) => (element?: unknown, index?: number | null | undefined, parent?: Parents | null | undefined, context?: unknown) => element is Element) &
   *   ((test?: Test) => Check)
   * )}
   */
  /**
   * @param {Test | null | undefined} [test]
   * @returns {Check}
   */
  (function(test) {
    if (test === null || test === void 0) {
      return element3;
    }
    if (typeof test === "string") {
      return tagNameFactory(test);
    }
    if (typeof test === "object") {
      return anyFactory(test);
    }
    if (typeof test === "function") {
      return castFactory(test);
    }
    throw new Error("Expected function, string, or array as `test`");
  })
);
function anyFactory(tests) {
  const checks2 = [];
  let index4 = -1;
  while (++index4 < tests.length) {
    checks2[index4] = convertElement(tests[index4]);
  }
  return castFactory(any2);
  function any2(...parameters) {
    let index5 = -1;
    while (++index5 < checks2.length) {
      if (checks2[index5].apply(this, parameters)) return true;
    }
    return false;
  }
}
function tagNameFactory(check) {
  return castFactory(tagName);
  function tagName(element7) {
    return element7.tagName === check;
  }
}
function castFactory(testFunction) {
  return check;
  function check(value, index4, parent) {
    return Boolean(
      looksLikeAnElement(value) && testFunction.call(
        this,
        value,
        typeof index4 === "number" ? index4 : void 0,
        parent || void 0
      )
    );
  }
}
function element3(element7) {
  return Boolean(
    element7 && typeof element7 === "object" && "type" in element7 && element7.type === "element" && "tagName" in element7 && typeof element7.tagName === "string"
  );
}
function looksLikeAnElement(value) {
  return value !== null && typeof value === "object" && "type" in value && "tagName" in value;
}

// ../../node_modules/.pnpm/hast-util-embedded@3.0.0/node_modules/hast-util-embedded/lib/index.js
var embedded = convertElement(
  /**
   * @param element
   * @returns {element is {tagName: 'audio' | 'canvas' | 'embed' | 'iframe' | 'img' | 'math' | 'object' | 'picture' | 'svg' | 'video'}}
   */
  function(element7) {
    return element7.tagName === "audio" || element7.tagName === "canvas" || element7.tagName === "embed" || element7.tagName === "iframe" || element7.tagName === "img" || element7.tagName === "math" || element7.tagName === "object" || element7.tagName === "picture" || element7.tagName === "svg" || element7.tagName === "video";
  }
);

// ../../node_modules/.pnpm/hast-util-whitespace@3.0.0/node_modules/hast-util-whitespace/lib/index.js
var re = /[ \t\n\f\r]/g;
function whitespace(thing) {
  return typeof thing === "object" ? thing.type === "text" ? empty2(thing.value) : false : empty2(thing);
}
function empty2(value) {
  return value.replace(re, "") === "";
}

// ../../node_modules/.pnpm/unist-util-is@6.0.1/node_modules/unist-util-is/lib/index.js
var convert = (
  // Note: overloads in JSDoc can’t yet use different `@template`s.
  /**
   * @type {(
   *   (<Condition extends string>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &
   *   (<Condition extends Props>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &
   *   (<Condition extends TestFunction>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &
   *   ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &
   *   ((test?: Test) => Check)
   * )}
   */
  /**
   * @param {Test} [test]
   * @returns {Check}
   */
  (function(test) {
    if (test === null || test === void 0) {
      return ok2;
    }
    if (typeof test === "function") {
      return castFactory2(test);
    }
    if (typeof test === "object") {
      return Array.isArray(test) ? anyFactory2(test) : (
        // Cast because `ReadonlyArray` goes into the above but `isArray`
        // narrows to `Array`.
        propertiesFactory(
          /** @type {Props} */
          test
        )
      );
    }
    if (typeof test === "string") {
      return typeFactory(test);
    }
    throw new Error("Expected function, string, or object as test");
  })
);
function anyFactory2(tests) {
  const checks2 = [];
  let index4 = -1;
  while (++index4 < tests.length) {
    checks2[index4] = convert(tests[index4]);
  }
  return castFactory2(any2);
  function any2(...parameters) {
    let index5 = -1;
    while (++index5 < checks2.length) {
      if (checks2[index5].apply(this, parameters)) return true;
    }
    return false;
  }
}
function propertiesFactory(check) {
  const checkAsRecord = (
    /** @type {Record<string, unknown>} */
    check
  );
  return castFactory2(all9);
  function all9(node2) {
    const nodeAsRecord = (
      /** @type {Record<string, unknown>} */
      /** @type {unknown} */
      node2
    );
    let key2;
    for (key2 in check) {
      if (nodeAsRecord[key2] !== checkAsRecord[key2]) return false;
    }
    return true;
  }
}
function typeFactory(check) {
  return castFactory2(type);
  function type(node2) {
    return node2 && node2.type === check;
  }
}
function castFactory2(testFunction) {
  return check;
  function check(value, index4, parent) {
    return Boolean(
      looksLikeANode(value) && testFunction.call(
        this,
        value,
        typeof index4 === "number" ? index4 : void 0,
        parent || void 0
      )
    );
  }
}
function ok2() {
  return true;
}
function looksLikeANode(value) {
  return value !== null && typeof value === "object" && "type" in value;
}

// ../../node_modules/.pnpm/hast-util-minify-whitespace@1.0.1/node_modules/hast-util-minify-whitespace/lib/block.js
var blocks = [
  "address",
  // Flow content.
  "article",
  // Sections and headings.
  "aside",
  // Sections and headings.
  "blockquote",
  // Flow content.
  "body",
  // Page.
  "br",
  // Contribute whitespace intrinsically.
  "caption",
  // Similar to block.
  "center",
  // Flow content, legacy.
  "col",
  // Similar to block.
  "colgroup",
  // Similar to block.
  "dd",
  // Lists.
  "dialog",
  // Flow content.
  "dir",
  // Lists, legacy.
  "div",
  // Flow content.
  "dl",
  // Lists.
  "dt",
  // Lists.
  "figcaption",
  // Flow content.
  "figure",
  // Flow content.
  "footer",
  // Flow content.
  "form",
  // Flow content.
  "h1",
  // Sections and headings.
  "h2",
  // Sections and headings.
  "h3",
  // Sections and headings.
  "h4",
  // Sections and headings.
  "h5",
  // Sections and headings.
  "h6",
  // Sections and headings.
  "head",
  // Page.
  "header",
  // Flow content.
  "hgroup",
  // Sections and headings.
  "hr",
  // Flow content.
  "html",
  // Page.
  "legend",
  // Flow content.
  "li",
  // Block-like.
  "li",
  // Similar to block.
  "listing",
  // Flow content, legacy
  "main",
  // Flow content.
  "menu",
  // Lists.
  "nav",
  // Sections and headings.
  "ol",
  // Lists.
  "optgroup",
  // Similar to block.
  "option",
  // Similar to block.
  "p",
  // Flow content.
  "plaintext",
  // Flow content, legacy
  "pre",
  // Flow content.
  "section",
  // Sections and headings.
  "summary",
  // Similar to block.
  "table",
  // Similar to block.
  "tbody",
  // Similar to block.
  "td",
  // Block-like.
  "td",
  // Similar to block.
  "tfoot",
  // Similar to block.
  "th",
  // Block-like.
  "th",
  // Similar to block.
  "thead",
  // Similar to block.
  "tr",
  // Similar to block.
  "ul",
  // Lists.
  "wbr",
  // Contribute whitespace intrinsically.
  "xmp"
  // Flow content, legacy
];

// ../../node_modules/.pnpm/hast-util-minify-whitespace@1.0.1/node_modules/hast-util-minify-whitespace/lib/content.js
var content = [
  // Form.
  "button",
  "input",
  "select",
  "textarea"
];

// ../../node_modules/.pnpm/hast-util-minify-whitespace@1.0.1/node_modules/hast-util-minify-whitespace/lib/skippable.js
var skippable = [
  "area",
  "base",
  "basefont",
  "dialog",
  "datalist",
  "head",
  "link",
  "meta",
  "noembed",
  "noframes",
  "param",
  "rp",
  "script",
  "source",
  "style",
  "template",
  "track",
  "title"
];

// ../../node_modules/.pnpm/hast-util-minify-whitespace@1.0.1/node_modules/hast-util-minify-whitespace/lib/index.js
var emptyOptions2 = {};
var ignorableNode = convert(["comment", "doctype"]);
function minifyWhitespace(tree, options2) {
  const settings = options2 || emptyOptions2;
  minify(tree, {
    collapse: collapseFactory(
      settings.newlines ? replaceNewlines2 : replaceWhitespace
    ),
    whitespace: "normal"
  });
}
function minify(node2, state) {
  if ("children" in node2) {
    const settings = { ...state };
    if (node2.type === "root" || blocklike(node2)) {
      settings.before = true;
      settings.after = true;
    }
    settings.whitespace = inferWhiteSpace(node2, state);
    return all3(node2, settings);
  }
  if (node2.type === "text") {
    if (state.whitespace === "normal") {
      return minifyText(node2, state);
    }
    if (state.whitespace === "nowrap") {
      node2.value = state.collapse(node2.value);
    }
  }
  return { ignore: ignorableNode(node2), stripAtStart: false, remove: false };
}
function minifyText(node2, state) {
  const value = state.collapse(node2.value);
  const result = { ignore: false, stripAtStart: false, remove: false };
  let start = 0;
  let end = value.length;
  if (state.before && removable(value.charAt(0))) {
    start++;
  }
  if (start !== end && removable(value.charAt(end - 1))) {
    if (state.after) {
      end--;
    } else {
      result.stripAtStart = true;
    }
  }
  if (start === end) {
    result.remove = true;
  } else {
    node2.value = value.slice(start, end);
  }
  return result;
}
function all3(parent, state) {
  let before = state.before;
  const after = state.after;
  const children = parent.children;
  let length2 = children.length;
  let index4 = -1;
  while (++index4 < length2) {
    const result = minify(children[index4], {
      ...state,
      after: collapsableAfter(children, index4, after),
      before
    });
    if (result.remove) {
      children.splice(index4, 1);
      index4--;
      length2--;
    } else if (!result.ignore) {
      before = result.stripAtStart;
    }
    if (content2(children[index4])) {
      before = false;
    }
  }
  return { ignore: false, stripAtStart: Boolean(before || after), remove: false };
}
function collapsableAfter(nodes, index4, after) {
  while (++index4 < nodes.length) {
    const node2 = nodes[index4];
    let result = inferBoundary(node2);
    if (result === void 0 && "children" in node2 && !skippable2(node2)) {
      result = collapsableAfter(node2.children, -1);
    }
    if (typeof result === "boolean") {
      return result;
    }
  }
  return after;
}
function inferBoundary(node2) {
  if (node2.type === "element") {
    if (content2(node2)) {
      return false;
    }
    if (blocklike(node2)) {
      return true;
    }
  } else if (node2.type === "text") {
    if (!whitespace(node2)) {
      return false;
    }
  } else if (!ignorableNode(node2)) {
    return false;
  }
}
function content2(node2) {
  return embedded(node2) || isElement(node2, content);
}
function blocklike(node2) {
  return isElement(node2, blocks);
}
function skippable2(node2) {
  return Boolean(node2.type === "element" && node2.properties.hidden) || ignorableNode(node2) || isElement(node2, skippable);
}
function removable(character) {
  return character === " " || character === "\n";
}
function replaceNewlines2(value) {
  const match2 = /\r?\n|\r/.exec(value);
  return match2 ? match2[0] : " ";
}
function replaceWhitespace() {
  return " ";
}
function collapseFactory(replace3) {
  return collapse;
  function collapse(value) {
    return String(value).replace(/[\t\n\v\f\r ]+/g, replace3);
  }
}
function inferWhiteSpace(node2, state) {
  if ("tagName" in node2 && node2.properties) {
    switch (node2.tagName) {
      // Whitespace in script/style, while not displayed by CSS as significant,
      // could have some meaning in JS/CSS, so we can’t touch them.
      case "listing":
      case "plaintext":
      case "script":
      case "style":
      case "xmp": {
        return "pre";
      }
      case "nobr": {
        return "nowrap";
      }
      case "pre": {
        return node2.properties.wrap ? "pre-wrap" : "pre";
      }
      case "td":
      case "th": {
        return node2.properties.noWrap ? "nowrap" : state.whitespace;
      }
      case "textarea": {
        return "pre-wrap";
      }
      default:
    }
  }
  return state.whitespace;
}

// ../../node_modules/.pnpm/rehype-minify-whitespace@6.0.2/node_modules/rehype-minify-whitespace/lib/index.js
function rehypeMinifyWhitespace(options2) {
  return function(tree) {
    minifyWhitespace(tree, options2);
  };
}

// ../../node_modules/.pnpm/unist-util-visit-parents@6.0.2/node_modules/unist-util-visit-parents/lib/color.js
function color(d) {
  return d;
}

// ../../node_modules/.pnpm/unist-util-visit-parents@6.0.2/node_modules/unist-util-visit-parents/lib/index.js
var empty3 = [];
var CONTINUE = true;
var EXIT = false;
var SKIP = "skip";
function visitParents(tree, test, visitor, reverse) {
  let check;
  if (typeof test === "function" && typeof visitor !== "function") {
    reverse = visitor;
    visitor = test;
  } else {
    check = test;
  }
  const is2 = convert(check);
  const step = reverse ? -1 : 1;
  factory(tree, void 0, [])();
  function factory(node2, index4, parents) {
    const value = (
      /** @type {Record<string, unknown>} */
      node2 && typeof node2 === "object" ? node2 : {}
    );
    if (typeof value.type === "string") {
      const name = (
        // `hast`
        typeof value.tagName === "string" ? value.tagName : (
          // `xast`
          typeof value.name === "string" ? value.name : void 0
        )
      );
      Object.defineProperty(visit2, "name", {
        value: "node (" + color(node2.type + (name ? "<" + name + ">" : "")) + ")"
      });
    }
    return visit2;
    function visit2() {
      let result = empty3;
      let subresult;
      let offset4;
      let grandparents;
      if (!test || is2(node2, index4, parents[parents.length - 1] || void 0)) {
        result = toResult(visitor(node2, parents));
        if (result[0] === EXIT) {
          return result;
        }
      }
      if ("children" in node2 && node2.children) {
        const nodeAsParent = (
          /** @type {UnistParent} */
          node2
        );
        if (nodeAsParent.children && result[0] !== SKIP) {
          offset4 = (reverse ? nodeAsParent.children.length : -1) + step;
          grandparents = parents.concat(nodeAsParent);
          while (offset4 > -1 && offset4 < nodeAsParent.children.length) {
            const child = nodeAsParent.children[offset4];
            subresult = factory(child, offset4, grandparents)();
            if (subresult[0] === EXIT) {
              return subresult;
            }
            offset4 = typeof subresult[1] === "number" ? subresult[1] : offset4 + step;
          }
        }
      }
      return result;
    }
  }
}
function toResult(value) {
  if (Array.isArray(value)) {
    return value;
  }
  if (typeof value === "number") {
    return [CONTINUE, value];
  }
  return value === null || value === void 0 ? empty3 : [value];
}

// ../../node_modules/.pnpm/unist-util-visit@5.0.0/node_modules/unist-util-visit/lib/index.js
function visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
  let reverse;
  let test;
  let visitor;
  if (typeof testOrVisitor === "function" && typeof visitorOrReverse !== "function") {
    test = void 0;
    visitor = testOrVisitor;
    reverse = visitorOrReverse;
  } else {
    test = testOrVisitor;
    visitor = visitorOrReverse;
    reverse = maybeReverse;
  }
  visitParents(tree, test, overload, reverse);
  function overload(node2, parents) {
    const parent = parents[parents.length - 1];
    const index4 = parent ? parent.children.indexOf(node2) : void 0;
    return visitor(node2, index4, parent);
  }
}

// ../../node_modules/.pnpm/unist-util-position@5.0.0/node_modules/unist-util-position/lib/index.js
var pointEnd = point3("end");
var pointStart = point3("start");
function point3(type) {
  return point5;
  function point5(node2) {
    const point6 = node2 && node2.position && node2.position[type] || {};
    if (typeof point6.line === "number" && point6.line > 0 && typeof point6.column === "number" && point6.column > 0) {
      return {
        line: point6.line,
        column: point6.column,
        offset: typeof point6.offset === "number" && point6.offset > -1 ? point6.offset : void 0
      };
    }
  }
}
function position3(node2) {
  const start = pointStart(node2);
  const end = pointEnd(node2);
  if (start && end) {
    return { start, end };
  }
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/a.js
function a2(state, node2) {
  const properties = node2.properties || {};
  const children = (
    /** @type {Array<PhrasingContent>} */
    state.all(node2)
  );
  const result = {
    type: "link",
    url: state.resolve(String(properties.href || "") || null),
    title: properties.title ? String(properties.title) : null,
    children
  };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/base.js
function base3(state, node2) {
  if (!state.baseFound) {
    state.frozenBaseUrl = String(node2.properties && node2.properties.href || "") || void 0;
    state.baseFound = true;
  }
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/blockquote.js
function blockquote(state, node2) {
  const result = { type: "blockquote", children: state.toFlow(state.all(node2)) };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/br.js
function br(state, node2) {
  const result = { type: "break" };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/unist-util-find-after@5.0.0/node_modules/unist-util-find-after/lib/index.js
var findAfter = (
  // Note: overloads like this are needed to support optional generics.
  /**
   * @type {(
   *   (<Kind extends UnistParent, Check extends Test>(parent: Kind, index: Child<Kind> | number, test: Check) => Matches<Child<Kind>, Check> | undefined) &
   *   (<Kind extends UnistParent>(parent: Kind, index: Child<Kind> | number, test?: null | undefined) => Child<Kind> | undefined)
   * )}
   */
  /**
   * @param {UnistParent} parent
   * @param {UnistNode | number} index
   * @param {Test} [test]
   * @returns {UnistNode | undefined}
   */
  (function(parent, index4, test) {
    const is2 = convert(test);
    if (!parent || !parent.type || !parent.children) {
      throw new Error("Expected parent node");
    }
    if (typeof index4 === "number") {
      if (index4 < 0 || index4 === Number.POSITIVE_INFINITY) {
        throw new Error("Expected positive finite number as index");
      }
    } else {
      index4 = parent.children.indexOf(index4);
      if (index4 < 0) {
        throw new Error("Expected child node or index");
      }
    }
    while (++index4 < parent.children.length) {
      if (is2(parent.children[index4], index4, parent)) {
        return parent.children[index4];
      }
    }
    return void 0;
  })
);

// ../../node_modules/.pnpm/hast-util-to-text@4.0.2/node_modules/hast-util-to-text/lib/index.js
var searchLineFeeds = /\n/g;
var searchTabOrSpaces = /[\t ]+/g;
var br2 = convertElement("br");
var cell = convertElement(isCell);
var p = convertElement("p");
var row = convertElement("tr");
var notRendered = convertElement([
  // List from: <https://html.spec.whatwg.org/multipage/rendering.html#hidden-elements>
  "datalist",
  "head",
  "noembed",
  "noframes",
  "noscript",
  // Act as if we support scripting.
  "rp",
  "script",
  "style",
  "template",
  "title",
  // Hidden attribute.
  hidden,
  // From: <https://html.spec.whatwg.org/multipage/rendering.html#flow-content-3>
  closedDialog
]);
var blockOrCaption = convertElement([
  "address",
  // Flow content
  "article",
  // Sections and headings
  "aside",
  // Sections and headings
  "blockquote",
  // Flow content
  "body",
  // Page
  "caption",
  // `table-caption`
  "center",
  // Flow content (legacy)
  "dd",
  // Lists
  "dialog",
  // Flow content
  "dir",
  // Lists (legacy)
  "dl",
  // Lists
  "dt",
  // Lists
  "div",
  // Flow content
  "figure",
  // Flow content
  "figcaption",
  // Flow content
  "footer",
  // Flow content
  "form,",
  // Flow content
  "h1",
  // Sections and headings
  "h2",
  // Sections and headings
  "h3",
  // Sections and headings
  "h4",
  // Sections and headings
  "h5",
  // Sections and headings
  "h6",
  // Sections and headings
  "header",
  // Flow content
  "hgroup",
  // Sections and headings
  "hr",
  // Flow content
  "html",
  // Page
  "legend",
  // Flow content
  "li",
  // Lists (as `display: list-item`)
  "listing",
  // Flow content (legacy)
  "main",
  // Flow content
  "menu",
  // Lists
  "nav",
  // Sections and headings
  "ol",
  // Lists
  "p",
  // Flow content
  "plaintext",
  // Flow content (legacy)
  "pre",
  // Flow content
  "section",
  // Sections and headings
  "ul",
  // Lists
  "xmp"
  // Flow content (legacy)
]);
function toText(tree, options2) {
  const options_ = options2 || {};
  const children = "children" in tree ? tree.children : [];
  const block = blockOrCaption(tree);
  const whitespace3 = inferWhitespace(tree, {
    whitespace: options_.whitespace || "normal",
    breakBefore: false,
    breakAfter: false
  });
  const results = [];
  if (tree.type === "text" || tree.type === "comment") {
    results.push(
      ...collectText(tree, {
        whitespace: whitespace3,
        breakBefore: true,
        breakAfter: true
      })
    );
  }
  let index4 = -1;
  while (++index4 < children.length) {
    results.push(
      ...renderedTextCollection(
        children[index4],
        // @ts-expect-error: `tree` is a parent if we’re here.
        tree,
        {
          whitespace: whitespace3,
          breakBefore: index4 ? void 0 : block,
          breakAfter: index4 < children.length - 1 ? br2(children[index4 + 1]) : block
        }
      )
    );
  }
  const result = [];
  let count2;
  index4 = -1;
  while (++index4 < results.length) {
    const value = results[index4];
    if (typeof value === "number") {
      if (count2 !== void 0 && value > count2) count2 = value;
    } else if (value) {
      if (count2 !== void 0 && count2 > -1) {
        result.push("\n".repeat(count2) || " ");
      }
      count2 = -1;
      result.push(value);
    }
  }
  return result.join("");
}
function renderedTextCollection(node2, parent, info) {
  if (node2.type === "element") {
    return collectElement(node2, parent, info);
  }
  if (node2.type === "text") {
    return info.whitespace === "normal" ? collectText(node2, info) : collectPreText(node2);
  }
  return [];
}
function collectElement(node2, parent, info) {
  const whitespace3 = inferWhitespace(node2, info);
  const children = node2.children || [];
  let index4 = -1;
  let items = [];
  if (notRendered(node2)) {
    return items;
  }
  let prefix3;
  let suffix;
  if (br2(node2)) {
    suffix = "\n";
  } else if (row(node2) && // @ts-expect-error: something up with types of parents.
  findAfter(parent, node2, row)) {
    suffix = "\n";
  } else if (p(node2)) {
    prefix3 = 2;
    suffix = 2;
  } else if (blockOrCaption(node2)) {
    prefix3 = 1;
    suffix = 1;
  }
  while (++index4 < children.length) {
    items = items.concat(
      renderedTextCollection(children[index4], node2, {
        whitespace: whitespace3,
        breakBefore: index4 ? void 0 : prefix3,
        breakAfter: index4 < children.length - 1 ? br2(children[index4 + 1]) : suffix
      })
    );
  }
  if (cell(node2) && // @ts-expect-error: something up with types of parents.
  findAfter(parent, node2, cell)) {
    items.push("	");
  }
  if (prefix3) items.unshift(prefix3);
  if (suffix) items.push(suffix);
  return items;
}
function collectText(node2, info) {
  const value = String(node2.value);
  const lines = [];
  const result = [];
  let start = 0;
  while (start <= value.length) {
    searchLineFeeds.lastIndex = start;
    const match2 = searchLineFeeds.exec(value);
    const end = match2 && "index" in match2 ? match2.index : value.length;
    lines.push(
      // Any sequence of collapsible spaces and tabs immediately preceding or
      // following a segment break is removed.
      trimAndCollapseSpacesAndTabs(
        // […] ignoring bidi formatting characters (characters with the
        // Bidi_Control property [UAX9]: ALM, LTR, RTL, LRE-RLO, LRI-PDI) as if
        // they were not there.
        value.slice(start, end).replace(/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g, ""),
        start === 0 ? info.breakBefore : true,
        end === value.length ? info.breakAfter : true
      )
    );
    start = end + 1;
  }
  let index4 = -1;
  let join4;
  while (++index4 < lines.length) {
    if (lines[index4].charCodeAt(lines[index4].length - 1) === 8203 || index4 < lines.length - 1 && lines[index4 + 1].charCodeAt(0) === 8203) {
      result.push(lines[index4]);
      join4 = void 0;
    } else if (lines[index4]) {
      if (typeof join4 === "number") result.push(join4);
      result.push(lines[index4]);
      join4 = 0;
    } else if (index4 === 0 || index4 === lines.length - 1) {
      result.push(0);
    }
  }
  return result;
}
function collectPreText(node2) {
  return [String(node2.value)];
}
function trimAndCollapseSpacesAndTabs(value, breakBefore, breakAfter) {
  const result = [];
  let start = 0;
  let end;
  while (start < value.length) {
    searchTabOrSpaces.lastIndex = start;
    const match2 = searchTabOrSpaces.exec(value);
    end = match2 ? match2.index : value.length;
    if (!start && !end && match2 && !breakBefore) {
      result.push("");
    }
    if (start !== end) {
      result.push(value.slice(start, end));
    }
    start = match2 ? end + match2[0].length : end;
  }
  if (start !== end && !breakAfter) {
    result.push("");
  }
  return result.join(" ");
}
function inferWhitespace(node2, info) {
  if (node2.type === "element") {
    const properties = node2.properties || {};
    switch (node2.tagName) {
      case "listing":
      case "plaintext":
      case "xmp": {
        return "pre";
      }
      case "nobr": {
        return "nowrap";
      }
      case "pre": {
        return properties.wrap ? "pre-wrap" : "pre";
      }
      case "td":
      case "th": {
        return properties.noWrap ? "nowrap" : info.whitespace;
      }
      case "textarea": {
        return "pre-wrap";
      }
      default:
    }
  }
  return info.whitespace;
}
function hidden(node2) {
  return Boolean((node2.properties || {}).hidden);
}
function isCell(node2) {
  return node2.tagName === "td" || node2.tagName === "th";
}
function closedDialog(node2) {
  return node2.tagName === "dialog" && !(node2.properties || {}).open;
}

// ../../node_modules/.pnpm/trim-trailing-lines@2.1.0/node_modules/trim-trailing-lines/index.js
function trimTrailingLines(value) {
  const input2 = String(value);
  let end = input2.length;
  while (end > 0) {
    const code5 = input2.codePointAt(end - 1);
    if (code5 !== void 0 && (code5 === 10 || code5 === 13)) {
      end--;
    } else {
      break;
    }
  }
  return input2.slice(0, end);
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/code.js
var prefix2 = "language-";
function code(state, node2) {
  const children = node2.children;
  let index4 = -1;
  let classList;
  let lang;
  if (node2.tagName === "pre") {
    while (++index4 < children.length) {
      const child = children[index4];
      if (child.type === "element" && child.tagName === "code" && child.properties && child.properties.className && Array.isArray(child.properties.className)) {
        classList = child.properties.className;
        break;
      }
    }
  }
  if (classList) {
    index4 = -1;
    while (++index4 < classList.length) {
      if (String(classList[index4]).slice(0, prefix2.length) === prefix2) {
        lang = String(classList[index4]).slice(prefix2.length);
        break;
      }
    }
  }
  const result = {
    type: "code",
    lang: lang || null,
    meta: null,
    value: trimTrailingLines(toText(node2))
  };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/comment.js
function comment(state, node2) {
  const result = {
    type: "html",
    value: "<!--" + node2.value + "-->"
  };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/del.js
function del2(state, node2) {
  const children = (
    /** @type {Array<PhrasingContent>} */
    state.all(node2)
  );
  const result = { type: "delete", children };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/util/list-items-spread.js
function listItemsSpread(children) {
  let index4 = -1;
  if (children.length > 1) {
    while (++index4 < children.length) {
      if (children[index4].spread) {
        return true;
      }
    }
  }
  return false;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/dl.js
function dl(state, node2) {
  const clean = [];
  const groups = [];
  let index4 = -1;
  while (++index4 < node2.children.length) {
    const child = node2.children[index4];
    if (child.type === "element" && child.tagName === "div") {
      clean.push(...child.children);
    } else {
      clean.push(child);
    }
  }
  let group = { definitions: [], titles: [] };
  index4 = -1;
  while (++index4 < clean.length) {
    const child = clean[index4];
    if (child.type === "element" && child.tagName === "dt") {
      const previous3 = clean[index4 - 1];
      if (previous3 && previous3.type === "element" && previous3.tagName === "dd") {
        groups.push(group);
        group = { definitions: [], titles: [] };
      }
      group.titles.push(child);
    } else {
      group.definitions.push(child);
    }
  }
  groups.push(group);
  index4 = -1;
  const content5 = [];
  while (++index4 < groups.length) {
    const result = [
      ...handle(state, groups[index4].titles),
      ...handle(state, groups[index4].definitions)
    ];
    if (result.length > 0) {
      content5.push({
        type: "listItem",
        spread: result.length > 1,
        checked: null,
        children: result
      });
    }
  }
  if (content5.length > 0) {
    const result = {
      type: "list",
      ordered: false,
      start: null,
      spread: listItemsSpread(content5),
      children: content5
    };
    state.patch(node2, result);
    return result;
  }
}
function handle(state, children) {
  const nodes = state.all({ type: "root", children });
  const listItems = state.toSpecificContent(nodes, create8);
  if (listItems.length === 0) {
    return [];
  }
  if (listItems.length === 1) {
    return listItems[0].children;
  }
  return [
    {
      type: "list",
      ordered: false,
      start: null,
      spread: listItemsSpread(listItems),
      children: listItems
    }
  ];
}
function create8() {
  return { type: "listItem", spread: false, checked: null, children: [] };
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/em.js
function em(state, node2) {
  const children = (
    /** @type {Array<PhrasingContent>} */
    state.all(node2)
  );
  const result = { type: "emphasis", children };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/util/drop-surrounding-breaks.js
function dropSurroundingBreaks(nodes) {
  let start = 0;
  let end = nodes.length;
  while (start < end && nodes[start].type === "break") start++;
  while (end > start && nodes[end - 1].type === "break") end--;
  return start === 0 && end === nodes.length ? nodes : nodes.slice(start, end);
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/heading.js
function heading(state, node2) {
  const depth = (
    /** @type {Heading['depth']} */
    /* c8 ignore next */
    Number(node2.tagName.charAt(1)) || 1
  );
  const children = dropSurroundingBreaks(
    /** @type {Array<PhrasingContent>} */
    state.all(node2)
  );
  const result = { type: "heading", depth, children };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/hr.js
function hr(state, node2) {
  const result = { type: "thematicBreak" };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/iframe.js
function iframe(state, node2) {
  const properties = node2.properties || {};
  const source = String(properties.src || "");
  const title = String(properties.title || "");
  if (source && title) {
    const result = {
      type: "link",
      title: null,
      url: state.resolve(source),
      children: [{ type: "text", value: title }]
    };
    state.patch(node2, result);
    return result;
  }
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/img.js
function img(state, node2) {
  const properties = node2.properties || {};
  const result = {
    type: "image",
    url: state.resolve(String(properties.src || "") || null),
    title: properties.title ? String(properties.title) : null,
    alt: properties.alt ? String(properties.alt) : ""
  };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/inline-code.js
function inlineCode(state, node2) {
  const result = { type: "inlineCode", value: toText(node2) };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/util/find-selected-options.js
function findSelectedOptions(node2, explicitProperties) {
  const selectedOptions = [];
  const values2 = [];
  const properties = explicitProperties || node2.properties || {};
  const options2 = findOptions(node2);
  const size5 = Math.min(Number.parseInt(String(properties.size), 10), 0) || (properties.multiple ? 4 : 1);
  let index4 = -1;
  while (++index4 < options2.length) {
    const option2 = options2[index4];
    if (option2 && option2.properties && option2.properties.selected) {
      selectedOptions.push(option2);
    }
  }
  const list7 = selectedOptions.length > 0 ? selectedOptions : options2;
  const max3 = Math.min(list7.length, size5);
  index4 = -1;
  while (++index4 < max3) {
    const option2 = list7[index4];
    const properties2 = option2.properties || {};
    const content5 = toText(option2);
    const label = content5 || String(properties2.label || "");
    const value = String(properties2.value || "") || content5;
    values2.push([value, label === value ? void 0 : label]);
  }
  return values2;
}
function findOptions(node2) {
  const results = [];
  let index4 = -1;
  while (++index4 < node2.children.length) {
    const child = node2.children[index4];
    if ("children" in child && Array.isArray(child.children)) {
      results.push(...findOptions(child));
    }
    if (child.type === "element" && child.tagName === "option" && (!child.properties || !child.properties.disabled)) {
      results.push(child);
    }
  }
  return results;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/input.js
var defaultChecked = "[x]";
var defaultUnchecked = "[ ]";
function input(state, node2) {
  const properties = node2.properties || {};
  const value = String(properties.value || properties.placeholder || "");
  if (properties.disabled || properties.type === "hidden" || properties.type === "file") {
    return;
  }
  if (properties.type === "checkbox" || properties.type === "radio") {
    const result2 = {
      type: "text",
      value: properties.checked ? state.options.checked || defaultChecked : state.options.unchecked || defaultUnchecked
    };
    state.patch(node2, result2);
    return result2;
  }
  if (properties.type === "image") {
    const alt = properties.alt || value;
    if (alt) {
      const result2 = {
        type: "image",
        url: state.resolve(String(properties.src || "") || null),
        title: String(properties.title || "") || null,
        alt: String(alt)
      };
      state.patch(node2, result2);
      return result2;
    }
    return;
  }
  let values2 = [];
  if (value) {
    values2 = [[value, void 0]];
  } else if (
    // `list` is not supported on these types:
    properties.type !== "button" && properties.type !== "file" && properties.type !== "password" && properties.type !== "reset" && properties.type !== "submit" && properties.list
  ) {
    const list7 = String(properties.list);
    const datalist = state.elementById.get(list7);
    if (datalist && datalist.tagName === "datalist") {
      values2 = findSelectedOptions(datalist, properties);
    }
  }
  if (values2.length === 0) {
    return;
  }
  if (properties.type === "password") {
    values2[0] = ["•".repeat(values2[0][0].length), void 0];
  }
  if (properties.type === "email" || properties.type === "url") {
    const results = [];
    let index5 = -1;
    while (++index5 < values2.length) {
      const value2 = state.resolve(values2[index5][0]);
      const result2 = {
        type: "link",
        title: null,
        url: properties.type === "email" ? "mailto:" + value2 : value2,
        children: [{ type: "text", value: values2[index5][1] || value2 }]
      };
      results.push(result2);
      if (index5 !== values2.length - 1) {
        results.push({ type: "text", value: ", " });
      }
    }
    return results;
  }
  const texts = [];
  let index4 = -1;
  while (++index4 < values2.length) {
    texts.push(
      values2[index4][1] ? values2[index4][1] + " (" + values2[index4][0] + ")" : values2[index4][0]
    );
  }
  const result = { type: "text", value: texts.join(", ") };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-has-property@3.0.0/node_modules/hast-util-has-property/lib/index.js
var own2 = {}.hasOwnProperty;
function hasProperty2(node2, name) {
  const value = node2.type === "element" && own2.call(node2.properties, name) && node2.properties[name];
  return value !== null && value !== void 0 && value !== false;
}

// ../../node_modules/.pnpm/hast-util-is-body-ok-link@3.0.1/node_modules/hast-util-is-body-ok-link/lib/index.js
var list = /* @__PURE__ */ new Set(["pingback", "prefetch", "stylesheet"]);
function isBodyOkLink(node2) {
  if (node2.type !== "element" || node2.tagName !== "link") {
    return false;
  }
  if (node2.properties.itemProp) {
    return true;
  }
  const value = node2.properties.rel;
  let index4 = -1;
  if (!Array.isArray(value) || value.length === 0) {
    return false;
  }
  while (++index4 < value.length) {
    if (!list.has(String(value[index4]))) {
      return false;
    }
  }
  return true;
}

// ../../node_modules/.pnpm/hast-util-phrasing@3.0.1/node_modules/hast-util-phrasing/lib/index.js
var basic = convertElement([
  "a",
  "abbr",
  // `area` is in fact only phrasing if it is inside a `map` element.
  // However, since `area`s are required to be inside a `map` element, and it’s
  // a rather involved check, it’s ignored here for now.
  "area",
  "b",
  "bdi",
  "bdo",
  "br",
  "button",
  "cite",
  "code",
  "data",
  "datalist",
  "del",
  "dfn",
  "em",
  "i",
  "input",
  "ins",
  "kbd",
  "keygen",
  "label",
  "map",
  "mark",
  "meter",
  "noscript",
  "output",
  "progress",
  "q",
  "ruby",
  "s",
  "samp",
  "script",
  "select",
  "small",
  "span",
  "strong",
  "sub",
  "sup",
  "template",
  "textarea",
  "time",
  "u",
  "var",
  "wbr"
]);
var meta = convertElement("meta");
function phrasing(value) {
  return Boolean(
    value.type === "text" || basic(value) || embedded(value) || isBodyOkLink(value) || meta(value) && hasProperty2(value, "itemProp")
  );
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/li.js
function li(state, node2) {
  const { rest, checkbox } = extractLeadingCheckbox(node2);
  const checked = checkbox ? Boolean(checkbox.properties.checked) : null;
  const spread = spreadout(rest);
  const children = state.toFlow(state.all(rest));
  const result = { type: "listItem", spread, checked, children };
  state.patch(node2, result);
  return result;
}
function spreadout(node2) {
  let index4 = -1;
  let seenFlow = false;
  while (++index4 < node2.children.length) {
    const child = node2.children[index4];
    if (child.type === "element") {
      if (phrasing(child)) continue;
      if (child.tagName === "p" || seenFlow || spreadout(child)) {
        return true;
      }
      seenFlow = true;
    }
  }
  return false;
}
function extractLeadingCheckbox(node2) {
  const head2 = node2.children[0];
  if (head2 && head2.type === "element" && head2.tagName === "input" && head2.properties && (head2.properties.type === "checkbox" || head2.properties.type === "radio")) {
    const rest = { ...node2, children: node2.children.slice(1) };
    return { checkbox: head2, rest };
  }
  if (head2 && head2.type === "element" && head2.tagName === "p") {
    const { checkbox, rest: restHead } = extractLeadingCheckbox(head2);
    if (checkbox) {
      const rest = { ...node2, children: [restHead, ...node2.children.slice(1)] };
      return { checkbox, rest };
    }
  }
  return { checkbox: void 0, rest: node2 };
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/list.js
function list2(state, node2) {
  const ordered = node2.tagName === "ol";
  const children = state.toSpecificContent(state.all(node2), create9);
  let start = null;
  if (ordered) {
    start = node2.properties && node2.properties.start ? Number.parseInt(String(node2.properties.start), 10) : 1;
  }
  const result = {
    type: "list",
    ordered,
    start,
    spread: listItemsSpread(children),
    children
  };
  state.patch(node2, result);
  return result;
}
function create9() {
  return { type: "listItem", spread: false, checked: null, children: [] };
}

// ../../node_modules/.pnpm/mdast-util-to-string@4.0.0/node_modules/mdast-util-to-string/lib/index.js
var emptyOptions3 = {};
function toString2(value, options2) {
  const settings = options2 || emptyOptions3;
  const includeImageAlt = typeof settings.includeImageAlt === "boolean" ? settings.includeImageAlt : true;
  const includeHtml = typeof settings.includeHtml === "boolean" ? settings.includeHtml : true;
  return one2(value, includeImageAlt, includeHtml);
}
function one2(value, includeImageAlt, includeHtml) {
  if (node(value)) {
    if ("value" in value) {
      return value.type === "html" && !includeHtml ? "" : value.value;
    }
    if (includeImageAlt && "alt" in value && value.alt) {
      return value.alt;
    }
    if ("children" in value) {
      return all4(value.children, includeImageAlt, includeHtml);
    }
  }
  if (Array.isArray(value)) {
    return all4(value, includeImageAlt, includeHtml);
  }
  return "";
}
function all4(values2, includeImageAlt, includeHtml) {
  const result = [];
  let index4 = -1;
  while (++index4 < values2.length) {
    result[index4] = one2(values2[index4], includeImageAlt, includeHtml);
  }
  return result.join("");
}
function node(value) {
  return Boolean(value && typeof value === "object");
}

// ../../node_modules/.pnpm/mdast-util-phrasing@4.1.0/node_modules/mdast-util-phrasing/lib/index.js
var phrasing2 = (
  /** @type {(node?: unknown) => node is Exclude<PhrasingContent, Html>} */
  convert([
    "break",
    "delete",
    "emphasis",
    // To do: next major: removed since footnotes were added to GFM.
    "footnote",
    "footnoteReference",
    "image",
    "imageReference",
    "inlineCode",
    // Enabled by `mdast-util-math`:
    "inlineMath",
    "link",
    "linkReference",
    // Enabled by `mdast-util-mdx`:
    "mdxJsxTextElement",
    // Enabled by `mdast-util-mdx`:
    "mdxTextExpression",
    "strong",
    "text",
    // Enabled by `mdast-util-directive`:
    "textDirective"
  ])
);

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/util/wrap.js
function wrapNeeded(nodes) {
  let index4 = -1;
  while (++index4 < nodes.length) {
    const node2 = nodes[index4];
    if (!phrasing3(node2) || "children" in node2 && wrapNeeded(node2.children)) {
      return true;
    }
  }
  return false;
}
function wrap2(nodes) {
  return runs(nodes, onphrasing, function(d) {
    return d;
  });
  function onphrasing(nodes2) {
    return nodes2.every(function(d) {
      return d.type === "text" ? whitespace(d.value) : false;
    }) ? [] : [{ type: "paragraph", children: dropSurroundingBreaks(nodes2) }];
  }
}
function split2(node2) {
  return runs(node2.children, onphrasing, onnonphrasing);
  function onphrasing(nodes) {
    const newParent = cloneWithoutChildren(node2);
    newParent.children = nodes;
    return [newParent];
  }
  function onnonphrasing(child) {
    if ("children" in child && "children" in node2) {
      const newParent = cloneWithoutChildren(node2);
      const newChild = cloneWithoutChildren(child);
      newParent.children = child.children;
      newChild.children.push(newParent);
      return newChild;
    }
    return { ...child };
  }
}
function runs(nodes, onphrasing, onnonphrasing) {
  const flattened = flatten(nodes);
  const result = [];
  let queue = [];
  let index4 = -1;
  while (++index4 < flattened.length) {
    const node2 = flattened[index4];
    if (phrasing3(node2)) {
      queue.push(node2);
    } else {
      if (queue.length > 0) {
        result.push(...onphrasing(queue));
        queue = [];
      }
      result.push(onnonphrasing(node2));
    }
  }
  if (queue.length > 0) {
    result.push(...onphrasing(queue));
    queue = [];
  }
  return result;
}
function flatten(nodes) {
  const flattened = [];
  let index4 = -1;
  while (++index4 < nodes.length) {
    const node2 = nodes[index4];
    if ((node2.type === "delete" || node2.type === "link") && wrapNeeded(node2.children)) {
      flattened.push(...split2(node2));
    } else {
      flattened.push(node2);
    }
  }
  return flattened;
}
function phrasing3(node2) {
  const tagName = node2.data && node2.data.hName;
  return tagName ? phrasing({ type: "element", tagName, properties: {}, children: [] }) : phrasing2(node2);
}
function cloneWithoutChildren(node2) {
  return esm_default({ ...node2, children: [] });
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/media.js
function media(state, node2) {
  const properties = node2.properties || {};
  const poster = node2.tagName === "video" ? String(properties.poster || "") : "";
  let source = String(properties.src || "");
  let index4 = -1;
  let linkInFallbackContent = false;
  let nodes = state.all(node2);
  const fragment = { type: "root", children: nodes };
  visit(fragment, function(node3) {
    if (node3.type === "link") {
      linkInFallbackContent = true;
      return EXIT;
    }
  });
  if (linkInFallbackContent || wrapNeeded(nodes)) {
    return nodes;
  }
  while (!source && ++index4 < node2.children.length) {
    const child = node2.children[index4];
    if (child.type === "element" && child.tagName === "source" && child.properties) {
      source = String(child.properties.src || "");
    }
  }
  if (poster) {
    const image3 = {
      type: "image",
      title: null,
      url: state.resolve(poster),
      alt: toString2(nodes)
    };
    state.patch(node2, image3);
    nodes = [image3];
  }
  const children = (
    /** @type {Array<PhrasingContent>} */
    nodes
  );
  const result = {
    type: "link",
    title: properties.title ? String(properties.title) : null,
    url: state.resolve(source),
    children
  };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/p.js
function p2(state, node2) {
  const children = dropSurroundingBreaks(
    // Allow potentially “invalid” nodes, they might be unknown.
    // We also support straddling later.
    /** @type {Array<PhrasingContent>} */
    state.all(node2)
  );
  if (children.length > 0) {
    const result = { type: "paragraph", children };
    state.patch(node2, result);
    return result;
  }
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/q.js
var defaultQuotes = ['"'];
function q2(state, node2) {
  const quotes = state.options.quotes || defaultQuotes;
  state.qNesting++;
  const contents = state.all(node2);
  state.qNesting--;
  const quote = quotes[state.qNesting % quotes.length];
  const head2 = contents[0];
  const tail = contents[contents.length - 1];
  const open = quote.charAt(0);
  const close2 = quote.length > 1 ? quote.charAt(1) : quote;
  if (head2 && head2.type === "text") {
    head2.value = open + head2.value;
  } else {
    contents.unshift({ type: "text", value: open });
  }
  if (tail && tail.type === "text") {
    tail.value += close2;
  } else {
    contents.push({ type: "text", value: close2 });
  }
  return contents;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/root.js
function root(state, node2) {
  let children = state.all(node2);
  if (state.options.document || wrapNeeded(children)) {
    children = wrap2(children);
  }
  const result = { type: "root", children };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/select.js
function select(state, node2) {
  const values2 = findSelectedOptions(node2);
  let index4 = -1;
  const results = [];
  while (++index4 < values2.length) {
    const value = values2[index4];
    results.push(value[1] ? value[1] + " (" + value[0] + ")" : value[0]);
  }
  if (results.length > 0) {
    const result = { type: "text", value: results.join(", ") };
    state.patch(node2, result);
    return result;
  }
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/strong.js
function strong(state, node2) {
  const children = (
    /** @type {Array<PhrasingContent>} */
    state.all(node2)
  );
  const result = { type: "strong", children };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/table-cell.js
function tableCell(state, node2) {
  const children = (
    /** @type {Array<PhrasingContent>} */
    state.all(node2)
  );
  const result = { type: "tableCell", children };
  state.patch(node2, result);
  if (node2.properties) {
    const rowSpan = node2.properties.rowSpan;
    const colSpan = node2.properties.colSpan;
    if (rowSpan || colSpan) {
      const data = (
        /** @type {Record<string, unknown>} */
        result.data || (result.data = {})
      );
      if (rowSpan) data.hastUtilToMdastTemporaryRowSpan = rowSpan;
      if (colSpan) data.hastUtilToMdastTemporaryColSpan = colSpan;
    }
  }
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/table-row.js
function tableRow(state, node2) {
  const children = state.toSpecificContent(state.all(node2), create10);
  const result = { type: "tableRow", children };
  state.patch(node2, result);
  return result;
}
function create10() {
  return { type: "tableCell", children: [] };
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/table.js
function table(state, node2) {
  if (state.inTable) {
    const result2 = { type: "text", value: toText(node2) };
    state.patch(node2, result2);
    return result2;
  }
  state.inTable = true;
  const { align, headless } = inspect(node2);
  const rows = state.toSpecificContent(state.all(node2), createRow);
  if (headless) {
    rows.unshift(createRow());
  }
  let rowIndex = -1;
  while (++rowIndex < rows.length) {
    const row2 = rows[rowIndex];
    const cells2 = state.toSpecificContent(row2.children, createCell);
    row2.children = cells2;
  }
  let columns = 1;
  rowIndex = -1;
  while (++rowIndex < rows.length) {
    const cells2 = rows[rowIndex].children;
    let cellIndex = -1;
    while (++cellIndex < cells2.length) {
      const cell2 = cells2[cellIndex];
      if (cell2.data) {
        const data = (
          /** @type {Record<string, unknown>} */
          cell2.data
        );
        const colSpan = Number.parseInt(String(data.hastUtilToMdastTemporaryColSpan), 10) || 1;
        const rowSpan = Number.parseInt(String(data.hastUtilToMdastTemporaryRowSpan), 10) || 1;
        if (colSpan > 1 || rowSpan > 1) {
          let otherRowIndex = rowIndex - 1;
          while (++otherRowIndex < rowIndex + rowSpan) {
            let colIndex = cellIndex - 1;
            while (++colIndex < cellIndex + colSpan) {
              if (!rows[otherRowIndex]) {
                break;
              }
              const newCells = [];
              if (otherRowIndex !== rowIndex || colIndex !== cellIndex) {
                newCells.push({ type: "tableCell", children: [] });
              }
              rows[otherRowIndex].children.splice(colIndex, 0, ...newCells);
            }
          }
        }
        if ("hastUtilToMdastTemporaryColSpan" in cell2.data)
          delete cell2.data.hastUtilToMdastTemporaryColSpan;
        if ("hastUtilToMdastTemporaryRowSpan" in cell2.data)
          delete cell2.data.hastUtilToMdastTemporaryRowSpan;
        if (Object.keys(cell2.data).length === 0) delete cell2.data;
      }
    }
    if (cells2.length > columns) columns = cells2.length;
  }
  rowIndex = -1;
  while (++rowIndex < rows.length) {
    const cells2 = rows[rowIndex].children;
    let cellIndex = cells2.length - 1;
    while (++cellIndex < columns) {
      cells2.push({ type: "tableCell", children: [] });
    }
  }
  let alignIndex = align.length - 1;
  while (++alignIndex < columns) {
    align.push(null);
  }
  state.inTable = false;
  const result = { type: "table", align, children: rows };
  state.patch(node2, result);
  return result;
}
function inspect(node2) {
  const info = { align: [null], headless: true };
  let rowIndex = 0;
  let cellIndex = 0;
  visit(node2, function(child) {
    if (child.type === "element") {
      if (child.tagName === "table" && node2 !== child) {
        return SKIP;
      }
      if ((child.tagName === "th" || child.tagName === "td") && child.properties) {
        if (!info.align[cellIndex]) {
          const value = String(child.properties.align || "") || null;
          if (value === "center" || value === "left" || value === "right" || value === null) {
            info.align[cellIndex] = value;
          }
        }
        if (info.headless && rowIndex < 2 && child.tagName === "th") {
          info.headless = false;
        }
        cellIndex++;
      } else if (child.tagName === "thead") {
        info.headless = false;
      } else if (child.tagName === "tr") {
        rowIndex++;
        cellIndex = 0;
      }
    }
  });
  return info;
}
function createCell() {
  return { type: "tableCell", children: [] };
}
function createRow() {
  return { type: "tableRow", children: [] };
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/text.js
function text2(state, node2) {
  const result = { type: "text", value: node2.value };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/textarea.js
function textarea(state, node2) {
  const result = { type: "text", value: toText(node2) };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/wbr.js
function wbr(state, node2) {
  const result = { type: "text", value: "​" };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/handlers/index.js
var nodeHandlers = {
  comment,
  doctype: ignore,
  root,
  text: text2
};
var handlers2 = {
  // Ignore:
  applet: ignore,
  area: ignore,
  basefont: ignore,
  bgsound: ignore,
  caption: ignore,
  col: ignore,
  colgroup: ignore,
  command: ignore,
  content: ignore,
  datalist: ignore,
  dialog: ignore,
  element: ignore,
  embed: ignore,
  frame: ignore,
  frameset: ignore,
  isindex: ignore,
  keygen: ignore,
  link: ignore,
  math: ignore,
  menu: ignore,
  menuitem: ignore,
  meta: ignore,
  nextid: ignore,
  noembed: ignore,
  noframes: ignore,
  optgroup: ignore,
  option: ignore,
  param: ignore,
  script: ignore,
  shadow: ignore,
  source: ignore,
  spacer: ignore,
  style: ignore,
  svg: ignore,
  template: ignore,
  title: ignore,
  track: ignore,
  // Use children:
  abbr: all5,
  acronym: all5,
  bdi: all5,
  bdo: all5,
  big: all5,
  blink: all5,
  button: all5,
  canvas: all5,
  cite: all5,
  data: all5,
  details: all5,
  dfn: all5,
  font: all5,
  ins: all5,
  label: all5,
  map: all5,
  marquee: all5,
  meter: all5,
  nobr: all5,
  noscript: all5,
  object: all5,
  output: all5,
  progress: all5,
  rb: all5,
  rbc: all5,
  rp: all5,
  rt: all5,
  rtc: all5,
  ruby: all5,
  slot: all5,
  small: all5,
  span: all5,
  sup: all5,
  sub: all5,
  tbody: all5,
  tfoot: all5,
  thead: all5,
  time: all5,
  // Use children as flow.
  address: flow,
  article: flow,
  aside: flow,
  body: flow,
  center: flow,
  div: flow,
  fieldset: flow,
  figcaption: flow,
  figure: flow,
  form: flow,
  footer: flow,
  header: flow,
  hgroup: flow,
  html: flow,
  legend: flow,
  main: flow,
  multicol: flow,
  nav: flow,
  picture: flow,
  section: flow,
  // Handle.
  a: a2,
  audio: media,
  b: strong,
  base: base3,
  blockquote,
  br,
  code: inlineCode,
  dir: list2,
  dl,
  dt: li,
  dd: li,
  del: del2,
  em,
  h1: heading,
  h2: heading,
  h3: heading,
  h4: heading,
  h5: heading,
  h6: heading,
  hr,
  i: em,
  iframe,
  img,
  image: img,
  input,
  kbd: inlineCode,
  li,
  listing: code,
  mark: em,
  ol: list2,
  p: p2,
  plaintext: code,
  pre: code,
  q: q2,
  s: del2,
  samp: inlineCode,
  select,
  strike: del2,
  strong,
  summary: p2,
  table,
  td: tableCell,
  textarea,
  th: tableCell,
  tr: tableRow,
  tt: inlineCode,
  u: em,
  ul: list2,
  var: inlineCode,
  video: media,
  wbr,
  xmp: code
};
function all5(state, node2) {
  return state.all(node2);
}
function flow(state, node2) {
  return state.toFlow(state.all(node2));
}
function ignore() {
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/state.js
var own3 = {}.hasOwnProperty;
function createState(options2) {
  return {
    all: all6,
    baseFound: false,
    elementById: /* @__PURE__ */ new Map(),
    frozenBaseUrl: void 0,
    handlers: { ...handlers2, ...options2.handlers },
    inTable: false,
    nodeHandlers: { ...nodeHandlers, ...options2.nodeHandlers },
    one: one3,
    options: options2,
    patch: patch2,
    qNesting: 0,
    resolve,
    toFlow,
    toSpecificContent
  };
}
function all6(parent) {
  const children = parent.children || [];
  const results = [];
  let index4 = -1;
  while (++index4 < children.length) {
    const child = children[index4];
    const result = (
      /** @type {Array<MdastRootContent> | MdastRootContent | undefined} */
      this.one(child, parent)
    );
    if (Array.isArray(result)) {
      results.push(...result);
    } else if (result) {
      results.push(result);
    }
  }
  return results;
}
function one3(node2, parent) {
  if (node2.type === "element") {
    if (node2.properties && node2.properties.dataMdast === "ignore") {
      return;
    }
    if (own3.call(this.handlers, node2.tagName)) {
      return this.handlers[node2.tagName](this, node2, parent) || void 0;
    }
  } else if (own3.call(this.nodeHandlers, node2.type)) {
    return this.nodeHandlers[node2.type](this, node2, parent) || void 0;
  }
  if ("value" in node2 && typeof node2.value === "string") {
    const result = { type: "text", value: node2.value };
    this.patch(node2, result);
    return result;
  }
  if ("children" in node2) {
    return this.all(node2);
  }
}
function patch2(origin, node2) {
  if (origin.position) node2.position = position3(origin);
}
function resolve(url) {
  const base4 = this.frozenBaseUrl;
  if (url === null || url === void 0) {
    return "";
  }
  if (base4) {
    return String(new URL(url, base4));
  }
  return url;
}
function toFlow(nodes) {
  return wrap2(nodes);
}
function toSpecificContent(nodes, build) {
  const reference = build();
  const results = [];
  let queue = [];
  let index4 = -1;
  while (++index4 < nodes.length) {
    const node2 = nodes[index4];
    if (expectedParent(node2)) {
      if (queue.length > 0) {
        node2.children.unshift(...queue);
        queue = [];
      }
      results.push(node2);
    } else {
      const child = (
        /** @type {ChildType} */
        node2
      );
      queue.push(child);
    }
  }
  if (queue.length > 0) {
    let node2 = results[results.length - 1];
    if (!node2) {
      node2 = build();
      results.push(node2);
    }
    node2.children.push(...queue);
    queue = [];
  }
  return results;
  function expectedParent(node2) {
    return node2.type === reference.type;
  }
}

// ../../node_modules/.pnpm/hast-util-to-mdast@10.1.2/node_modules/hast-util-to-mdast/lib/index.js
var emptyOptions4 = {};
function toMdast(tree, options2) {
  const cleanTree = esm_default(tree);
  const settings = options2 || emptyOptions4;
  const transformWhitespace = rehypeMinifyWhitespace({
    newlines: settings.newlines === true
  });
  const state = createState(settings);
  let mdast;
  transformWhitespace(cleanTree);
  visit(cleanTree, function(node2) {
    if (node2 && node2.type === "element" && node2.properties) {
      const id2 = String(node2.properties.id || "") || void 0;
      if (id2 && !state.elementById.has(id2)) {
        state.elementById.set(id2, node2);
      }
    }
  });
  const result = state.one(cleanTree, void 0);
  if (!result) {
    mdast = { type: "root", children: [] };
  } else if (Array.isArray(result)) {
    const children = (
      /** @type {Array<MdastRootContent>} */
      result
    );
    mdast = { type: "root", children };
  } else {
    mdast = result;
  }
  visit(mdast, function(node2, index4, parent) {
    if (node2.type === "text" && index4 !== void 0 && parent) {
      const previous3 = parent.children[index4 - 1];
      if (previous3 && previous3.type === node2.type) {
        previous3.value += node2.value;
        parent.children.splice(index4, 1);
        if (previous3.position && node2.position) {
          previous3.position.end = node2.position.end;
        }
        return index4 - 1;
      }
      node2.value = node2.value.replace(/[\t ]*(\r?\n|\r)[\t ]*/, "$1");
      if (parent && (parent.type === "heading" || parent.type === "paragraph" || parent.type === "root")) {
        if (!index4) {
          node2.value = node2.value.replace(/^[\t ]+/, "");
        }
        if (index4 === parent.children.length - 1) {
          node2.value = node2.value.replace(/[\t ]+$/, "");
        }
      }
      if (!node2.value) {
        parent.children.splice(index4, 1);
        return index4;
      }
    }
  });
  return mdast;
}

// ../../node_modules/.pnpm/rehype-remark@10.0.1/node_modules/rehype-remark/lib/index.js
var defaults = { document: true };
function rehypeRemark(destination, options2) {
  if (destination && "run" in destination) {
    return async function(tree, file) {
      const mdastTree = toMdast(tree, { ...defaults, ...options2 });
      await destination.run(mdastTree, file);
    };
  }
  return function(tree) {
    return (
      /** @type {MdastRoot} */
      toMdast(tree, { ...defaults, ...destination })
    );
  };
}

// ../../node_modules/.pnpm/ccount@2.0.1/node_modules/ccount/index.js
function ccount(value, character) {
  const source = String(value);
  if (typeof character !== "string") {
    throw new TypeError("Expected character");
  }
  let count2 = 0;
  let index4 = source.indexOf(character);
  while (index4 !== -1) {
    count2++;
    index4 = source.indexOf(character, index4 + character.length);
  }
  return count2;
}

// ../../node_modules/.pnpm/micromark-util-symbol@2.0.1/node_modules/micromark-util-symbol/lib/codes.js
var codes = (
  /** @type {const} */
  {
    carriageReturn: -5,
    lineFeed: -4,
    carriageReturnLineFeed: -3,
    horizontalTab: -2,
    virtualSpace: -1,
    eof: null,
    nul: 0,
    soh: 1,
    stx: 2,
    etx: 3,
    eot: 4,
    enq: 5,
    ack: 6,
    bel: 7,
    bs: 8,
    ht: 9,
    // `\t`
    lf: 10,
    // `\n`
    vt: 11,
    // `\v`
    ff: 12,
    // `\f`
    cr: 13,
    // `\r`
    so: 14,
    si: 15,
    dle: 16,
    dc1: 17,
    dc2: 18,
    dc3: 19,
    dc4: 20,
    nak: 21,
    syn: 22,
    etb: 23,
    can: 24,
    em: 25,
    sub: 26,
    esc: 27,
    fs: 28,
    gs: 29,
    rs: 30,
    us: 31,
    space: 32,
    exclamationMark: 33,
    // `!`
    quotationMark: 34,
    // `"`
    numberSign: 35,
    // `#`
    dollarSign: 36,
    // `$`
    percentSign: 37,
    // `%`
    ampersand: 38,
    // `&`
    apostrophe: 39,
    // `'`
    leftParenthesis: 40,
    // `(`
    rightParenthesis: 41,
    // `)`
    asterisk: 42,
    // `*`
    plusSign: 43,
    // `+`
    comma: 44,
    // `,`
    dash: 45,
    // `-`
    dot: 46,
    // `.`
    slash: 47,
    // `/`
    digit0: 48,
    // `0`
    digit1: 49,
    // `1`
    digit2: 50,
    // `2`
    digit3: 51,
    // `3`
    digit4: 52,
    // `4`
    digit5: 53,
    // `5`
    digit6: 54,
    // `6`
    digit7: 55,
    // `7`
    digit8: 56,
    // `8`
    digit9: 57,
    // `9`
    colon: 58,
    // `:`
    semicolon: 59,
    // `;`
    lessThan: 60,
    // `<`
    equalsTo: 61,
    // `=`
    greaterThan: 62,
    // `>`
    questionMark: 63,
    // `?`
    atSign: 64,
    // `@`
    uppercaseA: 65,
    // `A`
    uppercaseB: 66,
    // `B`
    uppercaseC: 67,
    // `C`
    uppercaseD: 68,
    // `D`
    uppercaseE: 69,
    // `E`
    uppercaseF: 70,
    // `F`
    uppercaseG: 71,
    // `G`
    uppercaseH: 72,
    // `H`
    uppercaseI: 73,
    // `I`
    uppercaseJ: 74,
    // `J`
    uppercaseK: 75,
    // `K`
    uppercaseL: 76,
    // `L`
    uppercaseM: 77,
    // `M`
    uppercaseN: 78,
    // `N`
    uppercaseO: 79,
    // `O`
    uppercaseP: 80,
    // `P`
    uppercaseQ: 81,
    // `Q`
    uppercaseR: 82,
    // `R`
    uppercaseS: 83,
    // `S`
    uppercaseT: 84,
    // `T`
    uppercaseU: 85,
    // `U`
    uppercaseV: 86,
    // `V`
    uppercaseW: 87,
    // `W`
    uppercaseX: 88,
    // `X`
    uppercaseY: 89,
    // `Y`
    uppercaseZ: 90,
    // `Z`
    leftSquareBracket: 91,
    // `[`
    backslash: 92,
    // `\`
    rightSquareBracket: 93,
    // `]`
    caret: 94,
    // `^`
    underscore: 95,
    // `_`
    graveAccent: 96,
    // `` ` ``
    lowercaseA: 97,
    // `a`
    lowercaseB: 98,
    // `b`
    lowercaseC: 99,
    // `c`
    lowercaseD: 100,
    // `d`
    lowercaseE: 101,
    // `e`
    lowercaseF: 102,
    // `f`
    lowercaseG: 103,
    // `g`
    lowercaseH: 104,
    // `h`
    lowercaseI: 105,
    // `i`
    lowercaseJ: 106,
    // `j`
    lowercaseK: 107,
    // `k`
    lowercaseL: 108,
    // `l`
    lowercaseM: 109,
    // `m`
    lowercaseN: 110,
    // `n`
    lowercaseO: 111,
    // `o`
    lowercaseP: 112,
    // `p`
    lowercaseQ: 113,
    // `q`
    lowercaseR: 114,
    // `r`
    lowercaseS: 115,
    // `s`
    lowercaseT: 116,
    // `t`
    lowercaseU: 117,
    // `u`
    lowercaseV: 118,
    // `v`
    lowercaseW: 119,
    // `w`
    lowercaseX: 120,
    // `x`
    lowercaseY: 121,
    // `y`
    lowercaseZ: 122,
    // `z`
    leftCurlyBrace: 123,
    // `{`
    verticalBar: 124,
    // `|`
    rightCurlyBrace: 125,
    // `}`
    tilde: 126,
    // `~`
    del: 127,
    // Unicode Specials block.
    byteOrderMarker: 65279,
    // Unicode Specials block.
    replacementCharacter: 65533
    // `�`
  }
);

// ../../node_modules/.pnpm/micromark-util-symbol@2.0.1/node_modules/micromark-util-symbol/lib/constants.js
var constants = (
  /** @type {const} */
  {
    attentionSideAfter: 2,
    // Symbol to mark an attention sequence as after content: `a*`
    attentionSideBefore: 1,
    // Symbol to mark an attention sequence as before content: `*a`
    atxHeadingOpeningFenceSizeMax: 6,
    // 6 number signs is fine, 7 isn’t.
    autolinkDomainSizeMax: 63,
    // 63 characters is fine, 64 is too many.
    autolinkSchemeSizeMax: 32,
    // 32 characters is fine, 33 is too many.
    cdataOpeningString: "CDATA[",
    // And preceded by `<![`.
    characterGroupPunctuation: 2,
    // Symbol used to indicate a character is punctuation
    characterGroupWhitespace: 1,
    // Symbol used to indicate a character is whitespace
    characterReferenceDecimalSizeMax: 7,
    // `&#9999999;`.
    characterReferenceHexadecimalSizeMax: 6,
    // `&#xff9999;`.
    characterReferenceNamedSizeMax: 31,
    // `&CounterClockwiseContourIntegral;`.
    codeFencedSequenceSizeMin: 3,
    // At least 3 ticks or tildes are needed.
    contentTypeContent: "content",
    contentTypeDocument: "document",
    contentTypeFlow: "flow",
    contentTypeString: "string",
    contentTypeText: "text",
    hardBreakPrefixSizeMin: 2,
    // At least 2 trailing spaces are needed.
    htmlBasic: 6,
    // Symbol for `<div`
    htmlCdata: 5,
    // Symbol for `<![CDATA[]]>`
    htmlComment: 2,
    // Symbol for `<!---->`
    htmlComplete: 7,
    // Symbol for `<x>`
    htmlDeclaration: 4,
    // Symbol for `<!doctype>`
    htmlInstruction: 3,
    // Symbol for `<?php?>`
    htmlRawSizeMax: 8,
    // Length of `textarea`.
    htmlRaw: 1,
    // Symbol for `<script>`
    linkResourceDestinationBalanceMax: 32,
    // See: <https://spec.commonmark.org/0.30/#link-destination>, <https://github.com/remarkjs/react-markdown/issues/658#issuecomment-984345577>
    linkReferenceSizeMax: 999,
    // See: <https://spec.commonmark.org/0.30/#link-label>
    listItemValueSizeMax: 10,
    // See: <https://spec.commonmark.org/0.30/#ordered-list-marker>
    numericBaseDecimal: 10,
    numericBaseHexadecimal: 16,
    tabSize: 4,
    // Tabs have a hard-coded size of 4, per CommonMark.
    thematicBreakMarkerCountMin: 3,
    // At least 3 asterisks, dashes, or underscores are needed.
    v8MaxSafeChunkSize: 1e4
    // V8 (and potentially others) have problems injecting giant arrays into other arrays, hence we operate in chunks.
  }
);

// ../../node_modules/.pnpm/micromark-util-symbol@2.0.1/node_modules/micromark-util-symbol/lib/types.js
var types = (
  /** @type {const} */
  {
    // Generic type for data, such as in a title, a destination, etc.
    data: "data",
    // Generic type for syntactic whitespace (tabs, virtual spaces, spaces).
    // Such as, between a fenced code fence and an info string.
    whitespace: "whitespace",
    // Generic type for line endings (line feed, carriage return, carriage return +
    // line feed).
    lineEnding: "lineEnding",
    // A line ending, but ending a blank line.
    lineEndingBlank: "lineEndingBlank",
    // Generic type for whitespace (tabs, virtual spaces, spaces) at the start of a
    // line.
    linePrefix: "linePrefix",
    // Generic type for whitespace (tabs, virtual spaces, spaces) at the end of a
    // line.
    lineSuffix: "lineSuffix",
    // Whole ATX heading:
    //
    // ```markdown
    // #
    // ## Alpha
    // ### Bravo ###
    // ```
    //
    // Includes `atxHeadingSequence`, `whitespace`, `atxHeadingText`.
    atxHeading: "atxHeading",
    // Sequence of number signs in an ATX heading (`###`).
    atxHeadingSequence: "atxHeadingSequence",
    // Content in an ATX heading (`alpha`).
    // Includes text.
    atxHeadingText: "atxHeadingText",
    // Whole autolink (`<https://example.com>` or `<admin@example.com>`)
    // Includes `autolinkMarker` and `autolinkProtocol` or `autolinkEmail`.
    autolink: "autolink",
    // Email autolink w/o markers (`admin@example.com`)
    autolinkEmail: "autolinkEmail",
    // Marker around an `autolinkProtocol` or `autolinkEmail` (`<` or `>`).
    autolinkMarker: "autolinkMarker",
    // Protocol autolink w/o markers (`https://example.com`)
    autolinkProtocol: "autolinkProtocol",
    // A whole character escape (`\-`).
    // Includes `escapeMarker` and `characterEscapeValue`.
    characterEscape: "characterEscape",
    // The escaped character (`-`).
    characterEscapeValue: "characterEscapeValue",
    // A whole character reference (`&amp;`, `&#8800;`, or `&#x1D306;`).
    // Includes `characterReferenceMarker`, an optional
    // `characterReferenceMarkerNumeric`, in which case an optional
    // `characterReferenceMarkerHexadecimal`, and a `characterReferenceValue`.
    characterReference: "characterReference",
    // The start or end marker (`&` or `;`).
    characterReferenceMarker: "characterReferenceMarker",
    // Mark reference as numeric (`#`).
    characterReferenceMarkerNumeric: "characterReferenceMarkerNumeric",
    // Mark reference as numeric (`x` or `X`).
    characterReferenceMarkerHexadecimal: "characterReferenceMarkerHexadecimal",
    // Value of character reference w/o markers (`amp`, `8800`, or `1D306`).
    characterReferenceValue: "characterReferenceValue",
    // Whole fenced code:
    //
    // ````markdown
    // ```js
    // alert(1)
    // ```
    // ````
    codeFenced: "codeFenced",
    // A fenced code fence, including whitespace, sequence, info, and meta
    // (` ```js `).
    codeFencedFence: "codeFencedFence",
    // Sequence of grave accent or tilde characters (` ``` `) in a fence.
    codeFencedFenceSequence: "codeFencedFenceSequence",
    // Info word (`js`) in a fence.
    // Includes string.
    codeFencedFenceInfo: "codeFencedFenceInfo",
    // Meta words (`highlight="1"`) in a fence.
    // Includes string.
    codeFencedFenceMeta: "codeFencedFenceMeta",
    // A line of code.
    codeFlowValue: "codeFlowValue",
    // Whole indented code:
    //
    // ```markdown
    //     alert(1)
    // ```
    //
    // Includes `lineEnding`, `linePrefix`, and `codeFlowValue`.
    codeIndented: "codeIndented",
    // A text code (``` `alpha` ```).
    // Includes `codeTextSequence`, `codeTextData`, `lineEnding`, and can include
    // `codeTextPadding`.
    codeText: "codeText",
    codeTextData: "codeTextData",
    // A space or line ending right after or before a tick.
    codeTextPadding: "codeTextPadding",
    // A text code fence (` `` `).
    codeTextSequence: "codeTextSequence",
    // Whole content:
    //
    // ```markdown
    // [a]: b
    // c
    // =
    // d
    // ```
    //
    // Includes `paragraph` and `definition`.
    content: "content",
    // Whole definition:
    //
    // ```markdown
    // [micromark]: https://github.com/micromark/micromark
    // ```
    //
    // Includes `definitionLabel`, `definitionMarker`, `whitespace`,
    // `definitionDestination`, and optionally `lineEnding` and `definitionTitle`.
    definition: "definition",
    // Destination of a definition (`https://github.com/micromark/micromark` or
    // `<https://github.com/micromark/micromark>`).
    // Includes `definitionDestinationLiteral` or `definitionDestinationRaw`.
    definitionDestination: "definitionDestination",
    // Enclosed destination of a definition
    // (`<https://github.com/micromark/micromark>`).
    // Includes `definitionDestinationLiteralMarker` and optionally
    // `definitionDestinationString`.
    definitionDestinationLiteral: "definitionDestinationLiteral",
    // Markers of an enclosed definition destination (`<` or `>`).
    definitionDestinationLiteralMarker: "definitionDestinationLiteralMarker",
    // Unenclosed destination of a definition
    // (`https://github.com/micromark/micromark`).
    // Includes `definitionDestinationString`.
    definitionDestinationRaw: "definitionDestinationRaw",
    // Text in an destination (`https://github.com/micromark/micromark`).
    // Includes string.
    definitionDestinationString: "definitionDestinationString",
    // Label of a definition (`[micromark]`).
    // Includes `definitionLabelMarker` and `definitionLabelString`.
    definitionLabel: "definitionLabel",
    // Markers of a definition label (`[` or `]`).
    definitionLabelMarker: "definitionLabelMarker",
    // Value of a definition label (`micromark`).
    // Includes string.
    definitionLabelString: "definitionLabelString",
    // Marker between a label and a destination (`:`).
    definitionMarker: "definitionMarker",
    // Title of a definition (`"x"`, `'y'`, or `(z)`).
    // Includes `definitionTitleMarker` and optionally `definitionTitleString`.
    definitionTitle: "definitionTitle",
    // Marker around a title of a definition (`"`, `'`, `(`, or `)`).
    definitionTitleMarker: "definitionTitleMarker",
    // Data without markers in a title (`z`).
    // Includes string.
    definitionTitleString: "definitionTitleString",
    // Emphasis (`*alpha*`).
    // Includes `emphasisSequence` and `emphasisText`.
    emphasis: "emphasis",
    // Sequence of emphasis markers (`*` or `_`).
    emphasisSequence: "emphasisSequence",
    // Emphasis text (`alpha`).
    // Includes text.
    emphasisText: "emphasisText",
    // The character escape marker (`\`).
    escapeMarker: "escapeMarker",
    // A hard break created with a backslash (`\\n`).
    // Note: does not include the line ending.
    hardBreakEscape: "hardBreakEscape",
    // A hard break created with trailing spaces (`  \n`).
    // Does not include the line ending.
    hardBreakTrailing: "hardBreakTrailing",
    // Flow HTML:
    //
    // ```markdown
    // <div
    // ```
    //
    // Inlcudes `lineEnding`, `htmlFlowData`.
    htmlFlow: "htmlFlow",
    htmlFlowData: "htmlFlowData",
    // HTML in text (the tag in `a <i> b`).
    // Includes `lineEnding`, `htmlTextData`.
    htmlText: "htmlText",
    htmlTextData: "htmlTextData",
    // Whole image (`![alpha](bravo)`, `![alpha][bravo]`, `![alpha][]`, or
    // `![alpha]`).
    // Includes `label` and an optional `resource` or `reference`.
    image: "image",
    // Whole link label (`[*alpha*]`).
    // Includes `labelLink` or `labelImage`, `labelText`, and `labelEnd`.
    label: "label",
    // Text in an label (`*alpha*`).
    // Includes text.
    labelText: "labelText",
    // Start a link label (`[`).
    // Includes a `labelMarker`.
    labelLink: "labelLink",
    // Start an image label (`![`).
    // Includes `labelImageMarker` and `labelMarker`.
    labelImage: "labelImage",
    // Marker of a label (`[` or `]`).
    labelMarker: "labelMarker",
    // Marker to start an image (`!`).
    labelImageMarker: "labelImageMarker",
    // End a label (`]`).
    // Includes `labelMarker`.
    labelEnd: "labelEnd",
    // Whole link (`[alpha](bravo)`, `[alpha][bravo]`, `[alpha][]`, or `[alpha]`).
    // Includes `label` and an optional `resource` or `reference`.
    link: "link",
    // Whole paragraph:
    //
    // ```markdown
    // alpha
    // bravo.
    // ```
    //
    // Includes text.
    paragraph: "paragraph",
    // A reference (`[alpha]` or `[]`).
    // Includes `referenceMarker` and an optional `referenceString`.
    reference: "reference",
    // A reference marker (`[` or `]`).
    referenceMarker: "referenceMarker",
    // Reference text (`alpha`).
    // Includes string.
    referenceString: "referenceString",
    // A resource (`(https://example.com "alpha")`).
    // Includes `resourceMarker`, an optional `resourceDestination` with an optional
    // `whitespace` and `resourceTitle`.
    resource: "resource",
    // A resource destination (`https://example.com`).
    // Includes `resourceDestinationLiteral` or `resourceDestinationRaw`.
    resourceDestination: "resourceDestination",
    // A literal resource destination (`<https://example.com>`).
    // Includes `resourceDestinationLiteralMarker` and optionally
    // `resourceDestinationString`.
    resourceDestinationLiteral: "resourceDestinationLiteral",
    // A resource destination marker (`<` or `>`).
    resourceDestinationLiteralMarker: "resourceDestinationLiteralMarker",
    // A raw resource destination (`https://example.com`).
    // Includes `resourceDestinationString`.
    resourceDestinationRaw: "resourceDestinationRaw",
    // Resource destination text (`https://example.com`).
    // Includes string.
    resourceDestinationString: "resourceDestinationString",
    // A resource marker (`(` or `)`).
    resourceMarker: "resourceMarker",
    // A resource title (`"alpha"`, `'alpha'`, or `(alpha)`).
    // Includes `resourceTitleMarker` and optionally `resourceTitleString`.
    resourceTitle: "resourceTitle",
    // A resource title marker (`"`, `'`, `(`, or `)`).
    resourceTitleMarker: "resourceTitleMarker",
    // Resource destination title (`alpha`).
    // Includes string.
    resourceTitleString: "resourceTitleString",
    // Whole setext heading:
    //
    // ```markdown
    // alpha
    // bravo
    // =====
    // ```
    //
    // Includes `setextHeadingText`, `lineEnding`, `linePrefix`, and
    // `setextHeadingLine`.
    setextHeading: "setextHeading",
    // Content in a setext heading (`alpha\nbravo`).
    // Includes text.
    setextHeadingText: "setextHeadingText",
    // Underline in a setext heading, including whitespace suffix (`==`).
    // Includes `setextHeadingLineSequence`.
    setextHeadingLine: "setextHeadingLine",
    // Sequence of equals or dash characters in underline in a setext heading (`-`).
    setextHeadingLineSequence: "setextHeadingLineSequence",
    // Strong (`**alpha**`).
    // Includes `strongSequence` and `strongText`.
    strong: "strong",
    // Sequence of strong markers (`**` or `__`).
    strongSequence: "strongSequence",
    // Strong text (`alpha`).
    // Includes text.
    strongText: "strongText",
    // Whole thematic break:
    //
    // ```markdown
    // * * *
    // ```
    //
    // Includes `thematicBreakSequence` and `whitespace`.
    thematicBreak: "thematicBreak",
    // A sequence of one or more thematic break markers (`***`).
    thematicBreakSequence: "thematicBreakSequence",
    // Whole block quote:
    //
    // ```markdown
    // > a
    // >
    // > b
    // ```
    //
    // Includes `blockQuotePrefix` and flow.
    blockQuote: "blockQuote",
    // The `>` or `> ` of a block quote.
    blockQuotePrefix: "blockQuotePrefix",
    // The `>` of a block quote prefix.
    blockQuoteMarker: "blockQuoteMarker",
    // The optional ` ` of a block quote prefix.
    blockQuotePrefixWhitespace: "blockQuotePrefixWhitespace",
    // Whole ordered list:
    //
    // ```markdown
    // 1. a
    //    b
    // ```
    //
    // Includes `listItemPrefix`, flow, and optionally  `listItemIndent` on further
    // lines.
    listOrdered: "listOrdered",
    // Whole unordered list:
    //
    // ```markdown
    // - a
    //   b
    // ```
    //
    // Includes `listItemPrefix`, flow, and optionally  `listItemIndent` on further
    // lines.
    listUnordered: "listUnordered",
    // The indent of further list item lines.
    listItemIndent: "listItemIndent",
    // A marker, as in, `*`, `+`, `-`, `.`, or `)`.
    listItemMarker: "listItemMarker",
    // The thing that starts a list item, such as `1. `.
    // Includes `listItemValue` if ordered, `listItemMarker`, and
    // `listItemPrefixWhitespace` (unless followed by a line ending).
    listItemPrefix: "listItemPrefix",
    // The whitespace after a marker.
    listItemPrefixWhitespace: "listItemPrefixWhitespace",
    // The numerical value of an ordered item.
    listItemValue: "listItemValue",
    // Internal types used for subtokenizers, compiled away
    chunkDocument: "chunkDocument",
    chunkContent: "chunkContent",
    chunkFlow: "chunkFlow",
    chunkText: "chunkText",
    chunkString: "chunkString"
  }
);

// ../../node_modules/.pnpm/micromark-util-symbol@2.0.1/node_modules/micromark-util-symbol/lib/values.js
var values = (
  /** @type {const} */
  {
    ht: "	",
    lf: "\n",
    cr: "\r",
    space: " ",
    exclamationMark: "!",
    quotationMark: '"',
    numberSign: "#",
    dollarSign: "$",
    percentSign: "%",
    ampersand: "&",
    apostrophe: "'",
    leftParenthesis: "(",
    rightParenthesis: ")",
    asterisk: "*",
    plusSign: "+",
    comma: ",",
    dash: "-",
    dot: ".",
    slash: "/",
    digit0: "0",
    digit1: "1",
    digit2: "2",
    digit3: "3",
    digit4: "4",
    digit5: "5",
    digit6: "6",
    digit7: "7",
    digit8: "8",
    digit9: "9",
    colon: ":",
    semicolon: ";",
    lessThan: "<",
    equalsTo: "=",
    greaterThan: ">",
    questionMark: "?",
    atSign: "@",
    uppercaseA: "A",
    uppercaseB: "B",
    uppercaseC: "C",
    uppercaseD: "D",
    uppercaseE: "E",
    uppercaseF: "F",
    uppercaseG: "G",
    uppercaseH: "H",
    uppercaseI: "I",
    uppercaseJ: "J",
    uppercaseK: "K",
    uppercaseL: "L",
    uppercaseM: "M",
    uppercaseN: "N",
    uppercaseO: "O",
    uppercaseP: "P",
    uppercaseQ: "Q",
    uppercaseR: "R",
    uppercaseS: "S",
    uppercaseT: "T",
    uppercaseU: "U",
    uppercaseV: "V",
    uppercaseW: "W",
    uppercaseX: "X",
    uppercaseY: "Y",
    uppercaseZ: "Z",
    leftSquareBracket: "[",
    backslash: "\\",
    rightSquareBracket: "]",
    caret: "^",
    underscore: "_",
    graveAccent: "`",
    lowercaseA: "a",
    lowercaseB: "b",
    lowercaseC: "c",
    lowercaseD: "d",
    lowercaseE: "e",
    lowercaseF: "f",
    lowercaseG: "g",
    lowercaseH: "h",
    lowercaseI: "i",
    lowercaseJ: "j",
    lowercaseK: "k",
    lowercaseL: "l",
    lowercaseM: "m",
    lowercaseN: "n",
    lowercaseO: "o",
    lowercaseP: "p",
    lowercaseQ: "q",
    lowercaseR: "r",
    lowercaseS: "s",
    lowercaseT: "t",
    lowercaseU: "u",
    lowercaseV: "v",
    lowercaseW: "w",
    lowercaseX: "x",
    lowercaseY: "y",
    lowercaseZ: "z",
    leftCurlyBrace: "{",
    verticalBar: "|",
    rightCurlyBrace: "}",
    tilde: "~",
    replacementCharacter: "�"
  }
);

// ../../node_modules/.pnpm/micromark-util-character@2.1.1/node_modules/micromark-util-character/dev/index.js
var asciiAlpha = regexCheck(/[A-Za-z]/);
var asciiAlphanumeric = regexCheck(/[\dA-Za-z]/);
var asciiAtext = regexCheck(/[#-'*+\--9=?A-Z^-~]/);
function asciiControl(code5) {
  return (
    // Special whitespace codes (which have negative values), C0 and Control
    // character DEL
    code5 !== null && (code5 < codes.space || code5 === codes.del)
  );
}
var asciiDigit = regexCheck(/\d/);
var asciiHexDigit = regexCheck(/[\dA-Fa-f]/);
var asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/);
function markdownLineEnding(code5) {
  return code5 !== null && code5 < codes.horizontalTab;
}
function markdownLineEndingOrSpace(code5) {
  return code5 !== null && (code5 < codes.nul || code5 === codes.space);
}
function markdownSpace(code5) {
  return code5 === codes.horizontalTab || code5 === codes.virtualSpace || code5 === codes.space;
}
var unicodePunctuation = regexCheck(new RegExp("\\p{P}|\\p{S}", "u"));
var unicodeWhitespace = regexCheck(/\s/);
function regexCheck(regex) {
  return check;
  function check(code5) {
    return code5 !== null && code5 > -1 && regex.test(String.fromCharCode(code5));
  }
}

// ../../node_modules/.pnpm/escape-string-regexp@5.0.0/node_modules/escape-string-regexp/index.js
function escapeStringRegexp(string3) {
  if (typeof string3 !== "string") {
    throw new TypeError("Expected a string");
  }
  return string3.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d");
}

// ../../node_modules/.pnpm/mdast-util-find-and-replace@3.0.2/node_modules/mdast-util-find-and-replace/lib/index.js
function findAndReplace(tree, list7, options2) {
  const settings = options2 || {};
  const ignored = convert(settings.ignore || []);
  const pairs = toPairs(list7);
  let pairIndex = -1;
  while (++pairIndex < pairs.length) {
    visitParents(tree, "text", visitor);
  }
  function visitor(node2, parents) {
    let index4 = -1;
    let grandparent;
    while (++index4 < parents.length) {
      const parent = parents[index4];
      const siblings2 = grandparent ? grandparent.children : void 0;
      if (ignored(
        parent,
        siblings2 ? siblings2.indexOf(parent) : void 0,
        grandparent
      )) {
        return;
      }
      grandparent = parent;
    }
    if (grandparent) {
      return handler(node2, parents);
    }
  }
  function handler(node2, parents) {
    const parent = parents[parents.length - 1];
    const find4 = pairs[pairIndex][0];
    const replace3 = pairs[pairIndex][1];
    let start = 0;
    const siblings2 = parent.children;
    const index4 = siblings2.indexOf(node2);
    let change = false;
    let nodes = [];
    find4.lastIndex = 0;
    let match2 = find4.exec(node2.value);
    while (match2) {
      const position4 = match2.index;
      const matchObject = {
        index: match2.index,
        input: match2.input,
        stack: [...parents, node2]
      };
      let value = replace3(...match2, matchObject);
      if (typeof value === "string") {
        value = value.length > 0 ? { type: "text", value } : void 0;
      }
      if (value === false) {
        find4.lastIndex = position4 + 1;
      } else {
        if (start !== position4) {
          nodes.push({
            type: "text",
            value: node2.value.slice(start, position4)
          });
        }
        if (Array.isArray(value)) {
          nodes.push(...value);
        } else if (value) {
          nodes.push(value);
        }
        start = position4 + match2[0].length;
        change = true;
      }
      if (!find4.global) {
        break;
      }
      match2 = find4.exec(node2.value);
    }
    if (change) {
      if (start < node2.value.length) {
        nodes.push({ type: "text", value: node2.value.slice(start) });
      }
      parent.children.splice(index4, 1, ...nodes);
    } else {
      nodes = [node2];
    }
    return index4 + nodes.length;
  }
}
function toPairs(tupleOrList) {
  const result = [];
  if (!Array.isArray(tupleOrList)) {
    throw new TypeError("Expected find and replace tuple or list of tuples");
  }
  const list7 = !tupleOrList[0] || Array.isArray(tupleOrList[0]) ? tupleOrList : [tupleOrList];
  let index4 = -1;
  while (++index4 < list7.length) {
    const tuple = list7[index4];
    result.push([toExpression(tuple[0]), toFunction(tuple[1])]);
  }
  return result;
}
function toExpression(find4) {
  return typeof find4 === "string" ? new RegExp(escapeStringRegexp(find4), "g") : find4;
}
function toFunction(replace3) {
  return typeof replace3 === "function" ? replace3 : function() {
    return replace3;
  };
}

// ../../node_modules/.pnpm/mdast-util-gfm-autolink-literal@2.0.1/node_modules/mdast-util-gfm-autolink-literal/lib/index.js
var inConstruct = "phrasing";
var notInConstruct = ["autolink", "link", "image", "label"];
function gfmAutolinkLiteralFromMarkdown() {
  return {
    transforms: [transformGfmAutolinkLiterals],
    enter: {
      literalAutolink: enterLiteralAutolink,
      literalAutolinkEmail: enterLiteralAutolinkValue,
      literalAutolinkHttp: enterLiteralAutolinkValue,
      literalAutolinkWww: enterLiteralAutolinkValue
    },
    exit: {
      literalAutolink: exitLiteralAutolink,
      literalAutolinkEmail: exitLiteralAutolinkEmail,
      literalAutolinkHttp: exitLiteralAutolinkHttp,
      literalAutolinkWww: exitLiteralAutolinkWww
    }
  };
}
function gfmAutolinkLiteralToMarkdown() {
  return {
    unsafe: [
      {
        character: "@",
        before: "[+\\-.\\w]",
        after: "[\\-.\\w]",
        inConstruct,
        notInConstruct
      },
      {
        character: ".",
        before: "[Ww]",
        after: "[\\-.\\w]",
        inConstruct,
        notInConstruct
      },
      {
        character: ":",
        before: "[ps]",
        after: "\\/",
        inConstruct,
        notInConstruct
      }
    ]
  };
}
function enterLiteralAutolink(token) {
  this.enter({ type: "link", title: null, url: "", children: [] }, token);
}
function enterLiteralAutolinkValue(token) {
  this.config.enter.autolinkProtocol.call(this, token);
}
function exitLiteralAutolinkHttp(token) {
  this.config.exit.autolinkProtocol.call(this, token);
}
function exitLiteralAutolinkWww(token) {
  this.config.exit.data.call(this, token);
  const node2 = this.stack[this.stack.length - 1];
  ok(node2.type === "link");
  node2.url = "http://" + this.sliceSerialize(token);
}
function exitLiteralAutolinkEmail(token) {
  this.config.exit.autolinkEmail.call(this, token);
}
function exitLiteralAutolink(token) {
  this.exit(token);
}
function transformGfmAutolinkLiterals(tree) {
  findAndReplace(
    tree,
    [
      [/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi, findUrl],
      [new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)", "gu"), findEmail]
    ],
    { ignore: ["link", "linkReference"] }
  );
}
function findUrl(_2, protocol, domain3, path2, match2) {
  let prefix3 = "";
  if (!previous(match2)) {
    return false;
  }
  if (/^w/i.test(protocol)) {
    domain3 = protocol + domain3;
    protocol = "";
    prefix3 = "http://";
  }
  if (!isCorrectDomain(domain3)) {
    return false;
  }
  const parts = splitUrl(domain3 + path2);
  if (!parts[0]) return false;
  const result = {
    type: "link",
    title: null,
    url: prefix3 + protocol + parts[0],
    children: [{ type: "text", value: protocol + parts[0] }]
  };
  if (parts[1]) {
    return [result, { type: "text", value: parts[1] }];
  }
  return result;
}
function findEmail(_2, atext, label, match2) {
  if (
    // Not an expected previous character.
    !previous(match2, true) || // Label ends in not allowed character.
    /[-\d_]$/.test(label)
  ) {
    return false;
  }
  return {
    type: "link",
    title: null,
    url: "mailto:" + atext + "@" + label,
    children: [{ type: "text", value: atext + "@" + label }]
  };
}
function isCorrectDomain(domain3) {
  const parts = domain3.split(".");
  if (parts.length < 2 || parts[parts.length - 1] && (/_/.test(parts[parts.length - 1]) || !/[a-zA-Z\d]/.test(parts[parts.length - 1])) || parts[parts.length - 2] && (/_/.test(parts[parts.length - 2]) || !/[a-zA-Z\d]/.test(parts[parts.length - 2]))) {
    return false;
  }
  return true;
}
function splitUrl(url) {
  const trailExec = /[!"&'),.:;<>?\]}]+$/.exec(url);
  if (!trailExec) {
    return [url, void 0];
  }
  url = url.slice(0, trailExec.index);
  let trail2 = trailExec[0];
  let closingParenIndex = trail2.indexOf(")");
  const openingParens = ccount(url, "(");
  let closingParens = ccount(url, ")");
  while (closingParenIndex !== -1 && openingParens > closingParens) {
    url += trail2.slice(0, closingParenIndex + 1);
    trail2 = trail2.slice(closingParenIndex + 1);
    closingParenIndex = trail2.indexOf(")");
    closingParens++;
  }
  return [url, trail2];
}
function previous(match2, email) {
  const code5 = match2.input.charCodeAt(match2.index - 1);
  return (match2.index === 0 || unicodeWhitespace(code5) || unicodePunctuation(code5)) && // If it’s an email, the previous character should not be a slash.
  (!email || code5 !== 47);
}

// ../../node_modules/.pnpm/micromark-util-normalize-identifier@2.0.1/node_modules/micromark-util-normalize-identifier/dev/index.js
function normalizeIdentifier(value) {
  return value.replace(/[\t\n\r ]+/g, values.space).replace(/^ | $/g, "").toLowerCase().toUpperCase();
}

// ../../node_modules/.pnpm/mdast-util-gfm-footnote@2.1.0/node_modules/mdast-util-gfm-footnote/lib/index.js
footnoteReference.peek = footnoteReferencePeek;
function enterFootnoteCallString() {
  this.buffer();
}
function enterFootnoteCall(token) {
  this.enter({ type: "footnoteReference", identifier: "", label: "" }, token);
}
function enterFootnoteDefinitionLabelString() {
  this.buffer();
}
function enterFootnoteDefinition(token) {
  this.enter(
    { type: "footnoteDefinition", identifier: "", label: "", children: [] },
    token
  );
}
function exitFootnoteCallString(token) {
  const label = this.resume();
  const node2 = this.stack[this.stack.length - 1];
  ok(node2.type === "footnoteReference");
  node2.identifier = normalizeIdentifier(
    this.sliceSerialize(token)
  ).toLowerCase();
  node2.label = label;
}
function exitFootnoteCall(token) {
  this.exit(token);
}
function exitFootnoteDefinitionLabelString(token) {
  const label = this.resume();
  const node2 = this.stack[this.stack.length - 1];
  ok(node2.type === "footnoteDefinition");
  node2.identifier = normalizeIdentifier(
    this.sliceSerialize(token)
  ).toLowerCase();
  node2.label = label;
}
function exitFootnoteDefinition(token) {
  this.exit(token);
}
function footnoteReferencePeek() {
  return "[";
}
function footnoteReference(node2, _2, state, info) {
  const tracker = state.createTracker(info);
  let value = tracker.move("[^");
  const exit3 = state.enter("footnoteReference");
  const subexit = state.enter("reference");
  value += tracker.move(
    state.safe(state.associationId(node2), { after: "]", before: value })
  );
  subexit();
  exit3();
  value += tracker.move("]");
  return value;
}
function gfmFootnoteFromMarkdown() {
  return {
    enter: {
      gfmFootnoteCallString: enterFootnoteCallString,
      gfmFootnoteCall: enterFootnoteCall,
      gfmFootnoteDefinitionLabelString: enterFootnoteDefinitionLabelString,
      gfmFootnoteDefinition: enterFootnoteDefinition
    },
    exit: {
      gfmFootnoteCallString: exitFootnoteCallString,
      gfmFootnoteCall: exitFootnoteCall,
      gfmFootnoteDefinitionLabelString: exitFootnoteDefinitionLabelString,
      gfmFootnoteDefinition: exitFootnoteDefinition
    }
  };
}
function gfmFootnoteToMarkdown(options2) {
  let firstLineBlank = false;
  if (options2 && options2.firstLineBlank) {
    firstLineBlank = true;
  }
  return {
    handlers: { footnoteDefinition, footnoteReference },
    // This is on by default already.
    unsafe: [{ character: "[", inConstruct: ["label", "phrasing", "reference"] }]
  };
  function footnoteDefinition(node2, _2, state, info) {
    const tracker = state.createTracker(info);
    let value = tracker.move("[^");
    const exit3 = state.enter("footnoteDefinition");
    const subexit = state.enter("label");
    value += tracker.move(
      state.safe(state.associationId(node2), { before: value, after: "]" })
    );
    subexit();
    value += tracker.move("]:");
    if (node2.children && node2.children.length > 0) {
      tracker.shift(4);
      value += tracker.move(
        (firstLineBlank ? "\n" : " ") + state.indentLines(
          state.containerFlow(node2, tracker.current()),
          firstLineBlank ? mapAll : mapExceptFirst
        )
      );
    }
    exit3();
    return value;
  }
}
function mapExceptFirst(line, index4, blank) {
  return index4 === 0 ? line : mapAll(line, index4, blank);
}
function mapAll(line, index4, blank) {
  return (blank ? "" : "    ") + line;
}

// ../../node_modules/.pnpm/mdast-util-gfm-strikethrough@2.0.0/node_modules/mdast-util-gfm-strikethrough/lib/index.js
var constructsWithoutStrikethrough = [
  "autolink",
  "destinationLiteral",
  "destinationRaw",
  "reference",
  "titleQuote",
  "titleApostrophe"
];
handleDelete.peek = peekDelete;
function gfmStrikethroughFromMarkdown() {
  return {
    canContainEols: ["delete"],
    enter: { strikethrough: enterStrikethrough },
    exit: { strikethrough: exitStrikethrough }
  };
}
function gfmStrikethroughToMarkdown() {
  return {
    unsafe: [
      {
        character: "~",
        inConstruct: "phrasing",
        notInConstruct: constructsWithoutStrikethrough
      }
    ],
    handlers: { delete: handleDelete }
  };
}
function enterStrikethrough(token) {
  this.enter({ type: "delete", children: [] }, token);
}
function exitStrikethrough(token) {
  this.exit(token);
}
function handleDelete(node2, _2, state, info) {
  const tracker = state.createTracker(info);
  const exit3 = state.enter("strikethrough");
  let value = tracker.move("~~");
  value += state.containerPhrasing(node2, {
    ...tracker.current(),
    before: value,
    after: "~"
  });
  value += tracker.move("~~");
  exit3();
  return value;
}
function peekDelete() {
  return "~";
}

// ../../node_modules/.pnpm/markdown-table@3.0.4/node_modules/markdown-table/index.js
function defaultStringLength(value) {
  return value.length;
}
function markdownTable(table3, options2) {
  const settings = options2 || {};
  const align = (settings.align || []).concat();
  const stringLength = settings.stringLength || defaultStringLength;
  const alignments2 = [];
  const cellMatrix = [];
  const sizeMatrix = [];
  const longestCellByColumn = [];
  let mostCellsPerRow = 0;
  let rowIndex = -1;
  while (++rowIndex < table3.length) {
    const row3 = [];
    const sizes2 = [];
    let columnIndex2 = -1;
    if (table3[rowIndex].length > mostCellsPerRow) {
      mostCellsPerRow = table3[rowIndex].length;
    }
    while (++columnIndex2 < table3[rowIndex].length) {
      const cell2 = serialize3(table3[rowIndex][columnIndex2]);
      if (settings.alignDelimiters !== false) {
        const size5 = stringLength(cell2);
        sizes2[columnIndex2] = size5;
        if (longestCellByColumn[columnIndex2] === void 0 || size5 > longestCellByColumn[columnIndex2]) {
          longestCellByColumn[columnIndex2] = size5;
        }
      }
      row3.push(cell2);
    }
    cellMatrix[rowIndex] = row3;
    sizeMatrix[rowIndex] = sizes2;
  }
  let columnIndex = -1;
  if (typeof align === "object" && "length" in align) {
    while (++columnIndex < mostCellsPerRow) {
      alignments2[columnIndex] = toAlignment(align[columnIndex]);
    }
  } else {
    const code5 = toAlignment(align);
    while (++columnIndex < mostCellsPerRow) {
      alignments2[columnIndex] = code5;
    }
  }
  columnIndex = -1;
  const row2 = [];
  const sizes = [];
  while (++columnIndex < mostCellsPerRow) {
    const code5 = alignments2[columnIndex];
    let before = "";
    let after = "";
    if (code5 === 99) {
      before = ":";
      after = ":";
    } else if (code5 === 108) {
      before = ":";
    } else if (code5 === 114) {
      after = ":";
    }
    let size5 = settings.alignDelimiters === false ? 1 : Math.max(
      1,
      longestCellByColumn[columnIndex] - before.length - after.length
    );
    const cell2 = before + "-".repeat(size5) + after;
    if (settings.alignDelimiters !== false) {
      size5 = before.length + size5 + after.length;
      if (size5 > longestCellByColumn[columnIndex]) {
        longestCellByColumn[columnIndex] = size5;
      }
      sizes[columnIndex] = size5;
    }
    row2[columnIndex] = cell2;
  }
  cellMatrix.splice(1, 0, row2);
  sizeMatrix.splice(1, 0, sizes);
  rowIndex = -1;
  const lines = [];
  while (++rowIndex < cellMatrix.length) {
    const row3 = cellMatrix[rowIndex];
    const sizes2 = sizeMatrix[rowIndex];
    columnIndex = -1;
    const line = [];
    while (++columnIndex < mostCellsPerRow) {
      const cell2 = row3[columnIndex] || "";
      let before = "";
      let after = "";
      if (settings.alignDelimiters !== false) {
        const size5 = longestCellByColumn[columnIndex] - (sizes2[columnIndex] || 0);
        const code5 = alignments2[columnIndex];
        if (code5 === 114) {
          before = " ".repeat(size5);
        } else if (code5 === 99) {
          if (size5 % 2) {
            before = " ".repeat(size5 / 2 + 0.5);
            after = " ".repeat(size5 / 2 - 0.5);
          } else {
            before = " ".repeat(size5 / 2);
            after = before;
          }
        } else {
          after = " ".repeat(size5);
        }
      }
      if (settings.delimiterStart !== false && !columnIndex) {
        line.push("|");
      }
      if (settings.padding !== false && // Don’t add the opening space if we’re not aligning and the cell is
      // empty: there will be a closing space.
      !(settings.alignDelimiters === false && cell2 === "") && (settings.delimiterStart !== false || columnIndex)) {
        line.push(" ");
      }
      if (settings.alignDelimiters !== false) {
        line.push(before);
      }
      line.push(cell2);
      if (settings.alignDelimiters !== false) {
        line.push(after);
      }
      if (settings.padding !== false) {
        line.push(" ");
      }
      if (settings.delimiterEnd !== false || columnIndex !== mostCellsPerRow - 1) {
        line.push("|");
      }
    }
    lines.push(
      settings.delimiterEnd === false ? line.join("").replace(/ +$/, "") : line.join("")
    );
  }
  return lines.join("\n");
}
function serialize3(value) {
  return value === null || value === void 0 ? "" : String(value);
}
function toAlignment(value) {
  const code5 = typeof value === "string" ? value.codePointAt(0) : 0;
  return code5 === 67 || code5 === 99 ? 99 : code5 === 76 || code5 === 108 ? 108 : code5 === 82 || code5 === 114 ? 114 : 0;
}

// ../../node_modules/.pnpm/zwitch@2.0.4/node_modules/zwitch/index.js
var own4 = {}.hasOwnProperty;
function zwitch(key2, options2) {
  const settings = options2 || {};
  function one6(value, ...parameters) {
    let fn4 = one6.invalid;
    const handlers4 = one6.handlers;
    if (value && own4.call(value, key2)) {
      const id2 = String(value[key2]);
      fn4 = own4.call(handlers4, id2) ? handlers4[id2] : one6.unknown;
    }
    if (fn4) {
      return fn4.call(this, value, ...parameters);
    }
  }
  one6.handlers = settings.handlers || {};
  one6.invalid = settings.invalid;
  one6.unknown = settings.unknown;
  return one6;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/configure.js
var own5 = {}.hasOwnProperty;
function configure(base4, extension2) {
  let index4 = -1;
  let key2;
  if (extension2.extensions) {
    while (++index4 < extension2.extensions.length) {
      configure(base4, extension2.extensions[index4]);
    }
  }
  for (key2 in extension2) {
    if (own5.call(extension2, key2)) {
      switch (key2) {
        case "extensions": {
          break;
        }
        /* c8 ignore next 4 */
        case "unsafe": {
          list3(base4[key2], extension2[key2]);
          break;
        }
        case "join": {
          list3(base4[key2], extension2[key2]);
          break;
        }
        case "handlers": {
          map4(base4[key2], extension2[key2]);
          break;
        }
        default: {
          base4.options[key2] = extension2[key2];
        }
      }
    }
  }
  return base4;
}
function list3(left, right) {
  if (right) {
    left.push(...right);
  }
}
function map4(left, right) {
  if (right) {
    Object.assign(left, right);
  }
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/blockquote.js
function blockquote2(node2, _2, state, info) {
  const exit3 = state.enter("blockquote");
  const tracker = state.createTracker(info);
  tracker.move("> ");
  tracker.shift(2);
  const value = state.indentLines(
    state.containerFlow(node2, tracker.current()),
    map5
  );
  exit3();
  return value;
}
function map5(line, _2, blank) {
  return ">" + (blank ? "" : " ") + line;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/pattern-in-scope.js
function patternInScope(stack, pattern) {
  return listInScope(stack, pattern.inConstruct, true) && !listInScope(stack, pattern.notInConstruct, false);
}
function listInScope(stack, list7, none2) {
  if (typeof list7 === "string") {
    list7 = [list7];
  }
  if (!list7 || list7.length === 0) {
    return none2;
  }
  let index4 = -1;
  while (++index4 < list7.length) {
    if (stack.includes(list7[index4])) {
      return true;
    }
  }
  return false;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/break.js
function hardBreak(_2, _1, state, info) {
  let index4 = -1;
  while (++index4 < state.unsafe.length) {
    if (state.unsafe[index4].character === "\n" && patternInScope(state.stack, state.unsafe[index4])) {
      return /[ \t]/.test(info.before) ? "" : " ";
    }
  }
  return "\\\n";
}

// ../../node_modules/.pnpm/longest-streak@3.1.0/node_modules/longest-streak/index.js
function longestStreak(value, substring) {
  const source = String(value);
  let index4 = source.indexOf(substring);
  let expected = index4;
  let count2 = 0;
  let max3 = 0;
  if (typeof substring !== "string") {
    throw new TypeError("Expected substring");
  }
  while (index4 !== -1) {
    if (index4 === expected) {
      if (++count2 > max3) {
        max3 = count2;
      }
    } else {
      count2 = 1;
    }
    expected = index4 + substring.length;
    index4 = source.indexOf(substring, expected);
  }
  return max3;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/format-code-as-indented.js
function formatCodeAsIndented(node2, state) {
  return Boolean(
    state.options.fences === false && node2.value && // If there’s no info…
    !node2.lang && // And there’s a non-whitespace character…
    /[^ \r\n]/.test(node2.value) && // And the value doesn’t start or end in a blank…
    !/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(node2.value)
  );
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/check-fence.js
function checkFence(state) {
  const marker = state.options.fence || "`";
  if (marker !== "`" && marker !== "~") {
    throw new Error(
      "Cannot serialize code with `" + marker + "` for `options.fence`, expected `` ` `` or `~`"
    );
  }
  return marker;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/code.js
function code2(node2, _2, state, info) {
  const marker = checkFence(state);
  const raw2 = node2.value || "";
  const suffix = marker === "`" ? "GraveAccent" : "Tilde";
  if (formatCodeAsIndented(node2, state)) {
    const exit4 = state.enter("codeIndented");
    const value2 = state.indentLines(raw2, map6);
    exit4();
    return value2;
  }
  const tracker = state.createTracker(info);
  const sequence = marker.repeat(Math.max(longestStreak(raw2, marker) + 1, 3));
  const exit3 = state.enter("codeFenced");
  let value = tracker.move(sequence);
  if (node2.lang) {
    const subexit = state.enter(`codeFencedLang${suffix}`);
    value += tracker.move(
      state.safe(node2.lang, {
        before: value,
        after: " ",
        encode: ["`"],
        ...tracker.current()
      })
    );
    subexit();
  }
  if (node2.lang && node2.meta) {
    const subexit = state.enter(`codeFencedMeta${suffix}`);
    value += tracker.move(" ");
    value += tracker.move(
      state.safe(node2.meta, {
        before: value,
        after: "\n",
        encode: ["`"],
        ...tracker.current()
      })
    );
    subexit();
  }
  value += tracker.move("\n");
  if (raw2) {
    value += tracker.move(raw2 + "\n");
  }
  value += tracker.move(sequence);
  exit3();
  return value;
}
function map6(line, _2, blank) {
  return (blank ? "" : "    ") + line;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/check-quote.js
function checkQuote(state) {
  const marker = state.options.quote || '"';
  if (marker !== '"' && marker !== "'") {
    throw new Error(
      "Cannot serialize title with `" + marker + "` for `options.quote`, expected `\"`, or `'`"
    );
  }
  return marker;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/definition.js
function definition(node2, _2, state, info) {
  const quote = checkQuote(state);
  const suffix = quote === '"' ? "Quote" : "Apostrophe";
  const exit3 = state.enter("definition");
  let subexit = state.enter("label");
  const tracker = state.createTracker(info);
  let value = tracker.move("[");
  value += tracker.move(
    state.safe(state.associationId(node2), {
      before: value,
      after: "]",
      ...tracker.current()
    })
  );
  value += tracker.move("]: ");
  subexit();
  if (
    // If there’s no url, or…
    !node2.url || // If there are control characters or whitespace.
    /[\0- \u007F]/.test(node2.url)
  ) {
    subexit = state.enter("destinationLiteral");
    value += tracker.move("<");
    value += tracker.move(
      state.safe(node2.url, { before: value, after: ">", ...tracker.current() })
    );
    value += tracker.move(">");
  } else {
    subexit = state.enter("destinationRaw");
    value += tracker.move(
      state.safe(node2.url, {
        before: value,
        after: node2.title ? " " : "\n",
        ...tracker.current()
      })
    );
  }
  subexit();
  if (node2.title) {
    subexit = state.enter(`title${suffix}`);
    value += tracker.move(" " + quote);
    value += tracker.move(
      state.safe(node2.title, {
        before: value,
        after: quote,
        ...tracker.current()
      })
    );
    value += tracker.move(quote);
    subexit();
  }
  exit3();
  return value;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/check-emphasis.js
function checkEmphasis(state) {
  const marker = state.options.emphasis || "*";
  if (marker !== "*" && marker !== "_") {
    throw new Error(
      "Cannot serialize emphasis with `" + marker + "` for `options.emphasis`, expected `*`, or `_`"
    );
  }
  return marker;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/encode-character-reference.js
function encodeCharacterReference(code5) {
  return "&#x" + code5.toString(16).toUpperCase() + ";";
}

// ../../node_modules/.pnpm/micromark-util-classify-character@2.0.1/node_modules/micromark-util-classify-character/dev/index.js
function classifyCharacter(code5) {
  if (code5 === codes.eof || markdownLineEndingOrSpace(code5) || unicodeWhitespace(code5)) {
    return constants.characterGroupWhitespace;
  }
  if (unicodePunctuation(code5)) {
    return constants.characterGroupPunctuation;
  }
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/encode-info.js
function encodeInfo(outside, inside, marker) {
  const outsideKind = classifyCharacter(outside);
  const insideKind = classifyCharacter(inside);
  if (outsideKind === void 0) {
    return insideKind === void 0 ? (
      // Letter inside:
      // we have to encode *both* letters for `_` as it is looser.
      // it already forms for `*` (and GFMs `~`).
      marker === "_" ? { inside: true, outside: true } : { inside: false, outside: false }
    ) : insideKind === 1 ? (
      // Whitespace inside: encode both (letter, whitespace).
      { inside: true, outside: true }
    ) : (
      // Punctuation inside: encode outer (letter)
      { inside: false, outside: true }
    );
  }
  if (outsideKind === 1) {
    return insideKind === void 0 ? (
      // Letter inside: already forms.
      { inside: false, outside: false }
    ) : insideKind === 1 ? (
      // Whitespace inside: encode both (whitespace).
      { inside: true, outside: true }
    ) : (
      // Punctuation inside: already forms.
      { inside: false, outside: false }
    );
  }
  return insideKind === void 0 ? (
    // Letter inside: already forms.
    { inside: false, outside: false }
  ) : insideKind === 1 ? (
    // Whitespace inside: encode inner (whitespace).
    { inside: true, outside: false }
  ) : (
    // Punctuation inside: already forms.
    { inside: false, outside: false }
  );
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/emphasis.js
emphasis.peek = emphasisPeek;
function emphasis(node2, _2, state, info) {
  const marker = checkEmphasis(state);
  const exit3 = state.enter("emphasis");
  const tracker = state.createTracker(info);
  const before = tracker.move(marker);
  let between2 = tracker.move(
    state.containerPhrasing(node2, {
      after: marker,
      before,
      ...tracker.current()
    })
  );
  const betweenHead = between2.charCodeAt(0);
  const open = encodeInfo(
    info.before.charCodeAt(info.before.length - 1),
    betweenHead,
    marker
  );
  if (open.inside) {
    between2 = encodeCharacterReference(betweenHead) + between2.slice(1);
  }
  const betweenTail = between2.charCodeAt(between2.length - 1);
  const close2 = encodeInfo(info.after.charCodeAt(0), betweenTail, marker);
  if (close2.inside) {
    between2 = between2.slice(0, -1) + encodeCharacterReference(betweenTail);
  }
  const after = tracker.move(marker);
  exit3();
  state.attentionEncodeSurroundingInfo = {
    after: close2.outside,
    before: open.outside
  };
  return before + between2 + after;
}
function emphasisPeek(_2, _1, state) {
  return state.options.emphasis || "*";
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/format-heading-as-setext.js
function formatHeadingAsSetext(node2, state) {
  let literalWithBreak = false;
  visit(node2, function(node3) {
    if ("value" in node3 && /\r?\n|\r/.test(node3.value) || node3.type === "break") {
      literalWithBreak = true;
      return EXIT;
    }
  });
  return Boolean(
    (!node2.depth || node2.depth < 3) && toString2(node2) && (state.options.setext || literalWithBreak)
  );
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/heading.js
function heading2(node2, _2, state, info) {
  const rank = Math.max(Math.min(6, node2.depth || 1), 1);
  const tracker = state.createTracker(info);
  if (formatHeadingAsSetext(node2, state)) {
    const exit4 = state.enter("headingSetext");
    const subexit2 = state.enter("phrasing");
    const value2 = state.containerPhrasing(node2, {
      ...tracker.current(),
      before: "\n",
      after: "\n"
    });
    subexit2();
    exit4();
    return value2 + "\n" + (rank === 1 ? "=" : "-").repeat(
      // The whole size…
      value2.length - // Minus the position of the character after the last EOL (or
      // 0 if there is none)…
      (Math.max(value2.lastIndexOf("\r"), value2.lastIndexOf("\n")) + 1)
    );
  }
  const sequence = "#".repeat(rank);
  const exit3 = state.enter("headingAtx");
  const subexit = state.enter("phrasing");
  tracker.move(sequence + " ");
  let value = state.containerPhrasing(node2, {
    before: "# ",
    after: "\n",
    ...tracker.current()
  });
  if (/^[\t ]/.test(value)) {
    value = encodeCharacterReference(value.charCodeAt(0)) + value.slice(1);
  }
  value = value ? sequence + " " + value : sequence;
  if (state.options.closeAtx) {
    value += " " + sequence;
  }
  subexit();
  exit3();
  return value;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/html.js
html3.peek = htmlPeek;
function html3(node2) {
  return node2.value || "";
}
function htmlPeek() {
  return "<";
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/image.js
image.peek = imagePeek;
function image(node2, _2, state, info) {
  const quote = checkQuote(state);
  const suffix = quote === '"' ? "Quote" : "Apostrophe";
  const exit3 = state.enter("image");
  let subexit = state.enter("label");
  const tracker = state.createTracker(info);
  let value = tracker.move("![");
  value += tracker.move(
    state.safe(node2.alt, { before: value, after: "]", ...tracker.current() })
  );
  value += tracker.move("](");
  subexit();
  if (
    // If there’s no url but there is a title…
    !node2.url && node2.title || // If there are control characters or whitespace.
    /[\0- \u007F]/.test(node2.url)
  ) {
    subexit = state.enter("destinationLiteral");
    value += tracker.move("<");
    value += tracker.move(
      state.safe(node2.url, { before: value, after: ">", ...tracker.current() })
    );
    value += tracker.move(">");
  } else {
    subexit = state.enter("destinationRaw");
    value += tracker.move(
      state.safe(node2.url, {
        before: value,
        after: node2.title ? " " : ")",
        ...tracker.current()
      })
    );
  }
  subexit();
  if (node2.title) {
    subexit = state.enter(`title${suffix}`);
    value += tracker.move(" " + quote);
    value += tracker.move(
      state.safe(node2.title, {
        before: value,
        after: quote,
        ...tracker.current()
      })
    );
    value += tracker.move(quote);
    subexit();
  }
  value += tracker.move(")");
  exit3();
  return value;
}
function imagePeek() {
  return "!";
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/image-reference.js
imageReference.peek = imageReferencePeek;
function imageReference(node2, _2, state, info) {
  const type = node2.referenceType;
  const exit3 = state.enter("imageReference");
  let subexit = state.enter("label");
  const tracker = state.createTracker(info);
  let value = tracker.move("![");
  const alt = state.safe(node2.alt, {
    before: value,
    after: "]",
    ...tracker.current()
  });
  value += tracker.move(alt + "][");
  subexit();
  const stack = state.stack;
  state.stack = [];
  subexit = state.enter("reference");
  const reference = state.safe(state.associationId(node2), {
    before: value,
    after: "]",
    ...tracker.current()
  });
  subexit();
  state.stack = stack;
  exit3();
  if (type === "full" || !alt || alt !== reference) {
    value += tracker.move(reference + "]");
  } else if (type === "shortcut") {
    value = value.slice(0, -1);
  } else {
    value += tracker.move("]");
  }
  return value;
}
function imageReferencePeek() {
  return "!";
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/inline-code.js
inlineCode2.peek = inlineCodePeek;
function inlineCode2(node2, _2, state) {
  let value = node2.value || "";
  let sequence = "`";
  let index4 = -1;
  while (new RegExp("(^|[^`])" + sequence + "([^`]|$)").test(value)) {
    sequence += "`";
  }
  if (/[^ \r\n]/.test(value) && (/^[ \r\n]/.test(value) && /[ \r\n]$/.test(value) || /^`|`$/.test(value))) {
    value = " " + value + " ";
  }
  while (++index4 < state.unsafe.length) {
    const pattern = state.unsafe[index4];
    const expression = state.compilePattern(pattern);
    let match2;
    if (!pattern.atBreak) continue;
    while (match2 = expression.exec(value)) {
      let position4 = match2.index;
      if (value.charCodeAt(position4) === 10 && value.charCodeAt(position4 - 1) === 13) {
        position4--;
      }
      value = value.slice(0, position4) + " " + value.slice(match2.index + 1);
    }
  }
  return sequence + value + sequence;
}
function inlineCodePeek() {
  return "`";
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/format-link-as-autolink.js
function formatLinkAsAutolink(node2, state) {
  const raw2 = toString2(node2);
  return Boolean(
    !state.options.resourceLink && // If there’s a url…
    node2.url && // And there’s a no title…
    !node2.title && // And the content of `node` is a single text node…
    node2.children && node2.children.length === 1 && node2.children[0].type === "text" && // And if the url is the same as the content…
    (raw2 === node2.url || "mailto:" + raw2 === node2.url) && // And that starts w/ a protocol…
    /^[a-z][a-z+.-]+:/i.test(node2.url) && // And that doesn’t contain ASCII control codes (character escapes and
    // references don’t work), space, or angle brackets…
    !/[\0- <>\u007F]/.test(node2.url)
  );
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/link.js
link.peek = linkPeek;
function link(node2, _2, state, info) {
  const quote = checkQuote(state);
  const suffix = quote === '"' ? "Quote" : "Apostrophe";
  const tracker = state.createTracker(info);
  let exit3;
  let subexit;
  if (formatLinkAsAutolink(node2, state)) {
    const stack = state.stack;
    state.stack = [];
    exit3 = state.enter("autolink");
    let value2 = tracker.move("<");
    value2 += tracker.move(
      state.containerPhrasing(node2, {
        before: value2,
        after: ">",
        ...tracker.current()
      })
    );
    value2 += tracker.move(">");
    exit3();
    state.stack = stack;
    return value2;
  }
  exit3 = state.enter("link");
  subexit = state.enter("label");
  let value = tracker.move("[");
  value += tracker.move(
    state.containerPhrasing(node2, {
      before: value,
      after: "](",
      ...tracker.current()
    })
  );
  value += tracker.move("](");
  subexit();
  if (
    // If there’s no url but there is a title…
    !node2.url && node2.title || // If there are control characters or whitespace.
    /[\0- \u007F]/.test(node2.url)
  ) {
    subexit = state.enter("destinationLiteral");
    value += tracker.move("<");
    value += tracker.move(
      state.safe(node2.url, { before: value, after: ">", ...tracker.current() })
    );
    value += tracker.move(">");
  } else {
    subexit = state.enter("destinationRaw");
    value += tracker.move(
      state.safe(node2.url, {
        before: value,
        after: node2.title ? " " : ")",
        ...tracker.current()
      })
    );
  }
  subexit();
  if (node2.title) {
    subexit = state.enter(`title${suffix}`);
    value += tracker.move(" " + quote);
    value += tracker.move(
      state.safe(node2.title, {
        before: value,
        after: quote,
        ...tracker.current()
      })
    );
    value += tracker.move(quote);
    subexit();
  }
  value += tracker.move(")");
  exit3();
  return value;
}
function linkPeek(node2, _2, state) {
  return formatLinkAsAutolink(node2, state) ? "<" : "[";
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/link-reference.js
linkReference.peek = linkReferencePeek;
function linkReference(node2, _2, state, info) {
  const type = node2.referenceType;
  const exit3 = state.enter("linkReference");
  let subexit = state.enter("label");
  const tracker = state.createTracker(info);
  let value = tracker.move("[");
  const text10 = state.containerPhrasing(node2, {
    before: value,
    after: "]",
    ...tracker.current()
  });
  value += tracker.move(text10 + "][");
  subexit();
  const stack = state.stack;
  state.stack = [];
  subexit = state.enter("reference");
  const reference = state.safe(state.associationId(node2), {
    before: value,
    after: "]",
    ...tracker.current()
  });
  subexit();
  state.stack = stack;
  exit3();
  if (type === "full" || !text10 || text10 !== reference) {
    value += tracker.move(reference + "]");
  } else if (type === "shortcut") {
    value = value.slice(0, -1);
  } else {
    value += tracker.move("]");
  }
  return value;
}
function linkReferencePeek() {
  return "[";
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/check-bullet.js
function checkBullet(state) {
  const marker = state.options.bullet || "*";
  if (marker !== "*" && marker !== "+" && marker !== "-") {
    throw new Error(
      "Cannot serialize items with `" + marker + "` for `options.bullet`, expected `*`, `+`, or `-`"
    );
  }
  return marker;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/check-bullet-other.js
function checkBulletOther(state) {
  const bullet = checkBullet(state);
  const bulletOther = state.options.bulletOther;
  if (!bulletOther) {
    return bullet === "*" ? "-" : "*";
  }
  if (bulletOther !== "*" && bulletOther !== "+" && bulletOther !== "-") {
    throw new Error(
      "Cannot serialize items with `" + bulletOther + "` for `options.bulletOther`, expected `*`, `+`, or `-`"
    );
  }
  if (bulletOther === bullet) {
    throw new Error(
      "Expected `bullet` (`" + bullet + "`) and `bulletOther` (`" + bulletOther + "`) to be different"
    );
  }
  return bulletOther;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/check-bullet-ordered.js
function checkBulletOrdered(state) {
  const marker = state.options.bulletOrdered || ".";
  if (marker !== "." && marker !== ")") {
    throw new Error(
      "Cannot serialize items with `" + marker + "` for `options.bulletOrdered`, expected `.` or `)`"
    );
  }
  return marker;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/check-rule.js
function checkRule(state) {
  const marker = state.options.rule || "*";
  if (marker !== "*" && marker !== "-" && marker !== "_") {
    throw new Error(
      "Cannot serialize rules with `" + marker + "` for `options.rule`, expected `*`, `-`, or `_`"
    );
  }
  return marker;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/list.js
function list4(node2, parent, state, info) {
  const exit3 = state.enter("list");
  const bulletCurrent = state.bulletCurrent;
  let bullet = node2.ordered ? checkBulletOrdered(state) : checkBullet(state);
  const bulletOther = node2.ordered ? bullet === "." ? ")" : "." : checkBulletOther(state);
  let useDifferentMarker = parent && state.bulletLastUsed ? bullet === state.bulletLastUsed : false;
  if (!node2.ordered) {
    const firstListItem = node2.children ? node2.children[0] : void 0;
    if (
      // Bullet could be used as a thematic break marker:
      (bullet === "*" || bullet === "-") && // Empty first list item:
      firstListItem && (!firstListItem.children || !firstListItem.children[0]) && // Directly in two other list items:
      state.stack[state.stack.length - 1] === "list" && state.stack[state.stack.length - 2] === "listItem" && state.stack[state.stack.length - 3] === "list" && state.stack[state.stack.length - 4] === "listItem" && // That are each the first child.
      state.indexStack[state.indexStack.length - 1] === 0 && state.indexStack[state.indexStack.length - 2] === 0 && state.indexStack[state.indexStack.length - 3] === 0
    ) {
      useDifferentMarker = true;
    }
    if (checkRule(state) === bullet && firstListItem) {
      let index4 = -1;
      while (++index4 < node2.children.length) {
        const item = node2.children[index4];
        if (item && item.type === "listItem" && item.children && item.children[0] && item.children[0].type === "thematicBreak") {
          useDifferentMarker = true;
          break;
        }
      }
    }
  }
  if (useDifferentMarker) {
    bullet = bulletOther;
  }
  state.bulletCurrent = bullet;
  const value = state.containerFlow(node2, info);
  state.bulletLastUsed = bullet;
  state.bulletCurrent = bulletCurrent;
  exit3();
  return value;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/check-list-item-indent.js
function checkListItemIndent(state) {
  const style3 = state.options.listItemIndent || "one";
  if (style3 !== "tab" && style3 !== "one" && style3 !== "mixed") {
    throw new Error(
      "Cannot serialize items with `" + style3 + "` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`"
    );
  }
  return style3;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/list-item.js
function listItem(node2, parent, state, info) {
  const listItemIndent = checkListItemIndent(state);
  let bullet = state.bulletCurrent || checkBullet(state);
  if (parent && parent.type === "list" && parent.ordered) {
    bullet = (typeof parent.start === "number" && parent.start > -1 ? parent.start : 1) + (state.options.incrementListMarker === false ? 0 : parent.children.indexOf(node2)) + bullet;
  }
  let size5 = bullet.length + 1;
  if (listItemIndent === "tab" || listItemIndent === "mixed" && (parent && parent.type === "list" && parent.spread || node2.spread)) {
    size5 = Math.ceil(size5 / 4) * 4;
  }
  const tracker = state.createTracker(info);
  tracker.move(bullet + " ".repeat(size5 - bullet.length));
  tracker.shift(size5);
  const exit3 = state.enter("listItem");
  const value = state.indentLines(
    state.containerFlow(node2, tracker.current()),
    map7
  );
  exit3();
  return value;
  function map7(line, index4, blank) {
    if (index4) {
      return (blank ? "" : " ".repeat(size5)) + line;
    }
    return (blank ? bullet : bullet + " ".repeat(size5 - bullet.length)) + line;
  }
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/paragraph.js
function paragraph(node2, _2, state, info) {
  const exit3 = state.enter("paragraph");
  const subexit = state.enter("phrasing");
  const value = state.containerPhrasing(node2, info);
  subexit();
  exit3();
  return value;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/root.js
function root2(node2, _2, state, info) {
  const hasPhrasing = node2.children.some(function(d) {
    return phrasing2(d);
  });
  const container = hasPhrasing ? state.containerPhrasing : state.containerFlow;
  return container.call(state, node2, info);
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/check-strong.js
function checkStrong(state) {
  const marker = state.options.strong || "*";
  if (marker !== "*" && marker !== "_") {
    throw new Error(
      "Cannot serialize strong with `" + marker + "` for `options.strong`, expected `*`, or `_`"
    );
  }
  return marker;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/strong.js
strong2.peek = strongPeek;
function strong2(node2, _2, state, info) {
  const marker = checkStrong(state);
  const exit3 = state.enter("strong");
  const tracker = state.createTracker(info);
  const before = tracker.move(marker + marker);
  let between2 = tracker.move(
    state.containerPhrasing(node2, {
      after: marker,
      before,
      ...tracker.current()
    })
  );
  const betweenHead = between2.charCodeAt(0);
  const open = encodeInfo(
    info.before.charCodeAt(info.before.length - 1),
    betweenHead,
    marker
  );
  if (open.inside) {
    between2 = encodeCharacterReference(betweenHead) + between2.slice(1);
  }
  const betweenTail = between2.charCodeAt(between2.length - 1);
  const close2 = encodeInfo(info.after.charCodeAt(0), betweenTail, marker);
  if (close2.inside) {
    between2 = between2.slice(0, -1) + encodeCharacterReference(betweenTail);
  }
  const after = tracker.move(marker + marker);
  exit3();
  state.attentionEncodeSurroundingInfo = {
    after: close2.outside,
    before: open.outside
  };
  return before + between2 + after;
}
function strongPeek(_2, _1, state) {
  return state.options.strong || "*";
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/text.js
function text3(node2, _2, state, info) {
  return state.safe(node2.value, info);
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/check-rule-repetition.js
function checkRuleRepetition(state) {
  const repetition = state.options.ruleRepetition || 3;
  if (repetition < 3) {
    throw new Error(
      "Cannot serialize rules with repetition `" + repetition + "` for `options.ruleRepetition`, expected `3` or more"
    );
  }
  return repetition;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/thematic-break.js
function thematicBreak(_2, _1, state) {
  const value = (checkRule(state) + (state.options.ruleSpaces ? " " : "")).repeat(checkRuleRepetition(state));
  return state.options.ruleSpaces ? value.slice(0, -1) : value;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/handle/index.js
var handle2 = {
  blockquote: blockquote2,
  break: hardBreak,
  code: code2,
  definition,
  emphasis,
  hardBreak,
  heading: heading2,
  html: html3,
  image,
  imageReference,
  inlineCode: inlineCode2,
  link,
  linkReference,
  list: list4,
  listItem,
  paragraph,
  root: root2,
  strong: strong2,
  text: text3,
  thematicBreak
};

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/join.js
var join3 = [joinDefaults];
function joinDefaults(left, right, parent, state) {
  if (right.type === "code" && formatCodeAsIndented(right, state) && (left.type === "list" || left.type === right.type && formatCodeAsIndented(left, state))) {
    return false;
  }
  if ("spread" in parent && typeof parent.spread === "boolean") {
    if (left.type === "paragraph" && // Two paragraphs.
    (left.type === right.type || right.type === "definition" || // Paragraph followed by a setext heading.
    right.type === "heading" && formatHeadingAsSetext(right, state))) {
      return;
    }
    return parent.spread ? 1 : 0;
  }
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/unsafe.js
var fullPhrasingSpans = [
  "autolink",
  "destinationLiteral",
  "destinationRaw",
  "reference",
  "titleQuote",
  "titleApostrophe"
];
var unsafe = [
  { character: "	", after: "[\\r\\n]", inConstruct: "phrasing" },
  { character: "	", before: "[\\r\\n]", inConstruct: "phrasing" },
  {
    character: "	",
    inConstruct: ["codeFencedLangGraveAccent", "codeFencedLangTilde"]
  },
  {
    character: "\r",
    inConstruct: [
      "codeFencedLangGraveAccent",
      "codeFencedLangTilde",
      "codeFencedMetaGraveAccent",
      "codeFencedMetaTilde",
      "destinationLiteral",
      "headingAtx"
    ]
  },
  {
    character: "\n",
    inConstruct: [
      "codeFencedLangGraveAccent",
      "codeFencedLangTilde",
      "codeFencedMetaGraveAccent",
      "codeFencedMetaTilde",
      "destinationLiteral",
      "headingAtx"
    ]
  },
  { character: " ", after: "[\\r\\n]", inConstruct: "phrasing" },
  { character: " ", before: "[\\r\\n]", inConstruct: "phrasing" },
  {
    character: " ",
    inConstruct: ["codeFencedLangGraveAccent", "codeFencedLangTilde"]
  },
  // An exclamation mark can start an image, if it is followed by a link or
  // a link reference.
  {
    character: "!",
    after: "\\[",
    inConstruct: "phrasing",
    notInConstruct: fullPhrasingSpans
  },
  // A quote can break out of a title.
  { character: '"', inConstruct: "titleQuote" },
  // A number sign could start an ATX heading if it starts a line.
  { atBreak: true, character: "#" },
  { character: "#", inConstruct: "headingAtx", after: "(?:[\r\n]|$)" },
  // Dollar sign and percentage are not used in markdown.
  // An ampersand could start a character reference.
  { character: "&", after: "[#A-Za-z]", inConstruct: "phrasing" },
  // An apostrophe can break out of a title.
  { character: "'", inConstruct: "titleApostrophe" },
  // A left paren could break out of a destination raw.
  { character: "(", inConstruct: "destinationRaw" },
  // A left paren followed by `]` could make something into a link or image.
  {
    before: "\\]",
    character: "(",
    inConstruct: "phrasing",
    notInConstruct: fullPhrasingSpans
  },
  // A right paren could start a list item or break out of a destination
  // raw.
  { atBreak: true, before: "\\d+", character: ")" },
  { character: ")", inConstruct: "destinationRaw" },
  // An asterisk can start thematic breaks, list items, emphasis, strong.
  { atBreak: true, character: "*", after: "(?:[ 	\r\n*])" },
  { character: "*", inConstruct: "phrasing", notInConstruct: fullPhrasingSpans },
  // A plus sign could start a list item.
  { atBreak: true, character: "+", after: "(?:[ 	\r\n])" },
  // A dash can start thematic breaks, list items, and setext heading
  // underlines.
  { atBreak: true, character: "-", after: "(?:[ 	\r\n-])" },
  // A dot could start a list item.
  { atBreak: true, before: "\\d+", character: ".", after: "(?:[ 	\r\n]|$)" },
  // Slash, colon, and semicolon are not used in markdown for constructs.
  // A less than can start html (flow or text) or an autolink.
  // HTML could start with an exclamation mark (declaration, cdata, comment),
  // slash (closing tag), question mark (instruction), or a letter (tag).
  // An autolink also starts with a letter.
  // Finally, it could break out of a destination literal.
  { atBreak: true, character: "<", after: "[!/?A-Za-z]" },
  {
    character: "<",
    after: "[!/?A-Za-z]",
    inConstruct: "phrasing",
    notInConstruct: fullPhrasingSpans
  },
  { character: "<", inConstruct: "destinationLiteral" },
  // An equals to can start setext heading underlines.
  { atBreak: true, character: "=" },
  // A greater than can start block quotes and it can break out of a
  // destination literal.
  { atBreak: true, character: ">" },
  { character: ">", inConstruct: "destinationLiteral" },
  // Question mark and at sign are not used in markdown for constructs.
  // A left bracket can start definitions, references, labels,
  { atBreak: true, character: "[" },
  { character: "[", inConstruct: "phrasing", notInConstruct: fullPhrasingSpans },
  { character: "[", inConstruct: ["label", "reference"] },
  // A backslash can start an escape (when followed by punctuation) or a
  // hard break (when followed by an eol).
  // Note: typical escapes are handled in `safe`!
  { character: "\\", after: "[\\r\\n]", inConstruct: "phrasing" },
  // A right bracket can exit labels.
  { character: "]", inConstruct: ["label", "reference"] },
  // Caret is not used in markdown for constructs.
  // An underscore can start emphasis, strong, or a thematic break.
  { atBreak: true, character: "_" },
  { character: "_", inConstruct: "phrasing", notInConstruct: fullPhrasingSpans },
  // A grave accent can start code (fenced or text), or it can break out of
  // a grave accent code fence.
  { atBreak: true, character: "`" },
  {
    character: "`",
    inConstruct: ["codeFencedLangGraveAccent", "codeFencedMetaGraveAccent"]
  },
  { character: "`", inConstruct: "phrasing", notInConstruct: fullPhrasingSpans },
  // Left brace, vertical bar, right brace are not used in markdown for
  // constructs.
  // A tilde can start code (fenced).
  { atBreak: true, character: "~" }
];

// ../../node_modules/.pnpm/decode-named-character-reference@1.2.0/node_modules/decode-named-character-reference/index.dom.js
var element4 = document.createElement("i");
function decodeNamedCharacterReference(value) {
  const characterReference2 = "&" + value + ";";
  element4.innerHTML = characterReference2;
  const character = element4.textContent;
  if (
    // @ts-expect-error: TypeScript is wrong that `textContent` on elements can
    // yield `null`.
    character.charCodeAt(character.length - 1) === 59 && value !== "semi"
  ) {
    return false;
  }
  return character === characterReference2 ? false : character;
}

// ../../node_modules/.pnpm/micromark-util-decode-numeric-character-reference@2.0.2/node_modules/micromark-util-decode-numeric-character-reference/dev/index.js
function decodeNumericCharacterReference(value, base4) {
  const code5 = Number.parseInt(value, base4);
  if (
    // C0 except for HT, LF, FF, CR, space.
    code5 < codes.ht || code5 === codes.vt || code5 > codes.cr && code5 < codes.space || // Control character (DEL) of C0, and C1 controls.
    code5 > codes.tilde && code5 < 160 || // Lone high surrogates and low surrogates.
    code5 > 55295 && code5 < 57344 || // Noncharacters.
    code5 > 64975 && code5 < 65008 || /* eslint-disable no-bitwise */
    (code5 & 65535) === 65535 || (code5 & 65535) === 65534 || /* eslint-enable no-bitwise */
    // Out of range
    code5 > 1114111
  ) {
    return values.replacementCharacter;
  }
  return String.fromCodePoint(code5);
}

// ../../node_modules/.pnpm/micromark-util-decode-string@2.0.1/node_modules/micromark-util-decode-string/dev/index.js
var characterEscapeOrReference = /\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;
function decodeString(value) {
  return value.replace(characterEscapeOrReference, decode);
}
function decode($0, $1, $22) {
  if ($1) {
    return $1;
  }
  const head2 = $22.charCodeAt(0);
  if (head2 === codes.numberSign) {
    const head3 = $22.charCodeAt(1);
    const hex = head3 === codes.lowercaseX || head3 === codes.uppercaseX;
    return decodeNumericCharacterReference(
      $22.slice(hex ? 2 : 1),
      hex ? constants.numericBaseHexadecimal : constants.numericBaseDecimal
    );
  }
  return decodeNamedCharacterReference($22) || $0;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/association.js
function association(node2) {
  if (node2.label || !node2.identifier) {
    return node2.label || "";
  }
  return decodeString(node2.identifier);
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/compile-pattern.js
function compilePattern(pattern) {
  if (!pattern._compiled) {
    const before = (pattern.atBreak ? "[\\r\\n][\\t ]*" : "") + (pattern.before ? "(?:" + pattern.before + ")" : "");
    pattern._compiled = new RegExp(
      (before ? "(" + before + ")" : "") + (/[|\\{}()[\]^$+*?.-]/.test(pattern.character) ? "\\" : "") + pattern.character + (pattern.after ? "(?:" + pattern.after + ")" : ""),
      "g"
    );
  }
  return pattern._compiled;
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/container-phrasing.js
function containerPhrasing(parent, state, info) {
  const indexStack = state.indexStack;
  const children = parent.children || [];
  const results = [];
  let index4 = -1;
  let before = info.before;
  let encodeAfter;
  indexStack.push(-1);
  let tracker = state.createTracker(info);
  while (++index4 < children.length) {
    const child = children[index4];
    let after;
    indexStack[indexStack.length - 1] = index4;
    if (index4 + 1 < children.length) {
      let handle4 = state.handle.handlers[children[index4 + 1].type];
      if (handle4 && handle4.peek) handle4 = handle4.peek;
      after = handle4 ? handle4(children[index4 + 1], parent, state, {
        before: "",
        after: "",
        ...tracker.current()
      }).charAt(0) : "";
    } else {
      after = info.after;
    }
    if (results.length > 0 && (before === "\r" || before === "\n") && child.type === "html") {
      results[results.length - 1] = results[results.length - 1].replace(
        /(\r?\n|\r)$/,
        " "
      );
      before = " ";
      tracker = state.createTracker(info);
      tracker.move(results.join(""));
    }
    let value = state.handle(child, parent, state, {
      ...tracker.current(),
      after,
      before
    });
    if (encodeAfter && encodeAfter === value.slice(0, 1)) {
      value = encodeCharacterReference(encodeAfter.charCodeAt(0)) + value.slice(1);
    }
    const encodingInfo = state.attentionEncodeSurroundingInfo;
    state.attentionEncodeSurroundingInfo = void 0;
    encodeAfter = void 0;
    if (encodingInfo) {
      if (results.length > 0 && encodingInfo.before && before === results[results.length - 1].slice(-1)) {
        results[results.length - 1] = results[results.length - 1].slice(0, -1) + encodeCharacterReference(before.charCodeAt(0));
      }
      if (encodingInfo.after) encodeAfter = after;
    }
    tracker.move(value);
    results.push(value);
    before = value.slice(-1);
  }
  indexStack.pop();
  return results.join("");
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/container-flow.js
function containerFlow(parent, state, info) {
  const indexStack = state.indexStack;
  const children = parent.children || [];
  const tracker = state.createTracker(info);
  const results = [];
  let index4 = -1;
  indexStack.push(-1);
  while (++index4 < children.length) {
    const child = children[index4];
    indexStack[indexStack.length - 1] = index4;
    results.push(
      tracker.move(
        state.handle(child, parent, state, {
          before: "\n",
          after: "\n",
          ...tracker.current()
        })
      )
    );
    if (child.type !== "list") {
      state.bulletLastUsed = void 0;
    }
    if (index4 < children.length - 1) {
      results.push(
        tracker.move(between(child, children[index4 + 1], parent, state))
      );
    }
  }
  indexStack.pop();
  return results.join("");
}
function between(left, right, parent, state) {
  let index4 = state.join.length;
  while (index4--) {
    const result = state.join[index4](left, right, parent, state);
    if (result === true || result === 1) {
      break;
    }
    if (typeof result === "number") {
      return "\n".repeat(1 + result);
    }
    if (result === false) {
      return "\n\n<!---->\n\n";
    }
  }
  return "\n\n";
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/indent-lines.js
var eol = /\r?\n|\r/g;
function indentLines(value, map7) {
  const result = [];
  let start = 0;
  let line = 0;
  let match2;
  while (match2 = eol.exec(value)) {
    one6(value.slice(start, match2.index));
    result.push(match2[0]);
    start = match2.index + match2[0].length;
    line++;
  }
  one6(value.slice(start));
  return result.join("");
  function one6(value2) {
    result.push(map7(value2, line, !value2));
  }
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/safe.js
function safe(state, input2, config) {
  const value = (config.before || "") + (input2 || "") + (config.after || "");
  const positions = [];
  const result = [];
  const infos = {};
  let index4 = -1;
  while (++index4 < state.unsafe.length) {
    const pattern = state.unsafe[index4];
    if (!patternInScope(state.stack, pattern)) {
      continue;
    }
    const expression = state.compilePattern(pattern);
    let match2;
    while (match2 = expression.exec(value)) {
      const before = "before" in pattern || Boolean(pattern.atBreak);
      const after = "after" in pattern;
      const position4 = match2.index + (before ? match2[1].length : 0);
      if (positions.includes(position4)) {
        if (infos[position4].before && !before) {
          infos[position4].before = false;
        }
        if (infos[position4].after && !after) {
          infos[position4].after = false;
        }
      } else {
        positions.push(position4);
        infos[position4] = { before, after };
      }
    }
  }
  positions.sort(numerical);
  let start = config.before ? config.before.length : 0;
  const end = value.length - (config.after ? config.after.length : 0);
  index4 = -1;
  while (++index4 < positions.length) {
    const position4 = positions[index4];
    if (position4 < start || position4 >= end) {
      continue;
    }
    if (position4 + 1 < end && positions[index4 + 1] === position4 + 1 && infos[position4].after && !infos[position4 + 1].before && !infos[position4 + 1].after || positions[index4 - 1] === position4 - 1 && infos[position4].before && !infos[position4 - 1].before && !infos[position4 - 1].after) {
      continue;
    }
    if (start !== position4) {
      result.push(escapeBackslashes(value.slice(start, position4), "\\"));
    }
    start = position4;
    if (/[!-/:-@[-`{-~]/.test(value.charAt(position4)) && (!config.encode || !config.encode.includes(value.charAt(position4)))) {
      result.push("\\");
    } else {
      result.push(encodeCharacterReference(value.charCodeAt(position4)));
      start++;
    }
  }
  result.push(escapeBackslashes(value.slice(start, end), config.after));
  return result.join("");
}
function numerical(a3, b4) {
  return a3 - b4;
}
function escapeBackslashes(value, after) {
  const expression = /\\(?=[!-/:-@[-`{-~])/g;
  const positions = [];
  const results = [];
  const whole = value + after;
  let index4 = -1;
  let start = 0;
  let match2;
  while (match2 = expression.exec(whole)) {
    positions.push(match2.index);
  }
  while (++index4 < positions.length) {
    if (start !== positions[index4]) {
      results.push(value.slice(start, positions[index4]));
    }
    results.push("\\");
    start = positions[index4];
  }
  results.push(value.slice(start));
  return results.join("");
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/util/track.js
function track(config) {
  const options2 = config || {};
  const now = options2.now || {};
  let lineShift = options2.lineShift || 0;
  let line = now.line || 1;
  let column = now.column || 1;
  return { move, current, shift: shift5 };
  function current() {
    return { now: { line, column }, lineShift };
  }
  function shift5(value) {
    lineShift += value;
  }
  function move(input2) {
    const value = input2 || "";
    const chunks = value.split(/\r?\n|\r/g);
    const tail = chunks[chunks.length - 1];
    line += chunks.length - 1;
    column = chunks.length === 1 ? column + tail.length : 1 + tail.length + lineShift;
    return value;
  }
}

// ../../node_modules/.pnpm/mdast-util-to-markdown@2.1.2/node_modules/mdast-util-to-markdown/lib/index.js
function toMarkdown(tree, options2) {
  const settings = options2 || {};
  const state = {
    associationId: association,
    containerPhrasing: containerPhrasingBound,
    containerFlow: containerFlowBound,
    createTracker: track,
    compilePattern,
    enter: enter2,
    // @ts-expect-error: GFM / frontmatter are typed in `mdast` but not defined
    // here.
    handlers: { ...handle2 },
    // @ts-expect-error: add `handle` in a second.
    handle: void 0,
    indentLines,
    indexStack: [],
    join: [...join3],
    options: {},
    safe: safeBound,
    stack: [],
    unsafe: [...unsafe]
  };
  configure(state, settings);
  if (state.options.tightDefinitions) {
    state.join.push(joinDefinition);
  }
  state.handle = zwitch("type", {
    invalid,
    unknown,
    handlers: state.handlers
  });
  let result = state.handle(tree, void 0, state, {
    before: "\n",
    after: "\n",
    now: { line: 1, column: 1 },
    lineShift: 0
  });
  if (result && result.charCodeAt(result.length - 1) !== 10 && result.charCodeAt(result.length - 1) !== 13) {
    result += "\n";
  }
  return result;
  function enter2(name) {
    state.stack.push(name);
    return exit3;
    function exit3() {
      state.stack.pop();
    }
  }
}
function invalid(value) {
  throw new Error("Cannot handle value `" + value + "`, expected node");
}
function unknown(value) {
  const node2 = (
    /** @type {Nodes} */
    value
  );
  throw new Error("Cannot handle unknown node `" + node2.type + "`");
}
function joinDefinition(left, right) {
  if (left.type === "definition" && left.type === right.type) {
    return 0;
  }
}
function containerPhrasingBound(parent, info) {
  return containerPhrasing(parent, this, info);
}
function containerFlowBound(parent, info) {
  return containerFlow(parent, this, info);
}
function safeBound(value, config) {
  return safe(this, value, config);
}

// ../../node_modules/.pnpm/mdast-util-gfm-table@2.0.0/node_modules/mdast-util-gfm-table/lib/index.js
function gfmTableFromMarkdown() {
  return {
    enter: {
      table: enterTable,
      tableData: enterCell,
      tableHeader: enterCell,
      tableRow: enterRow
    },
    exit: {
      codeText: exitCodeText,
      table: exitTable,
      tableData: exit,
      tableHeader: exit,
      tableRow: exit
    }
  };
}
function enterTable(token) {
  const align = token._align;
  ok(align, "expected `_align` on table");
  this.enter(
    {
      type: "table",
      align: align.map(function(d) {
        return d === "none" ? null : d;
      }),
      children: []
    },
    token
  );
  this.data.inTable = true;
}
function exitTable(token) {
  this.exit(token);
  this.data.inTable = void 0;
}
function enterRow(token) {
  this.enter({ type: "tableRow", children: [] }, token);
}
function exit(token) {
  this.exit(token);
}
function enterCell(token) {
  this.enter({ type: "tableCell", children: [] }, token);
}
function exitCodeText(token) {
  let value = this.resume();
  if (this.data.inTable) {
    value = value.replace(/\\([\\|])/g, replace2);
  }
  const node2 = this.stack[this.stack.length - 1];
  ok(node2.type === "inlineCode");
  node2.value = value;
  this.exit(token);
}
function replace2($0, $1) {
  return $1 === "|" ? $1 : $0;
}
function gfmTableToMarkdown(options2) {
  const settings = options2 || {};
  const padding = settings.tableCellPadding;
  const alignDelimiters = settings.tablePipeAlign;
  const stringLength = settings.stringLength;
  const around = padding ? " " : "|";
  return {
    unsafe: [
      { character: "\r", inConstruct: "tableCell" },
      { character: "\n", inConstruct: "tableCell" },
      // A pipe, when followed by a tab or space (padding), or a dash or colon
      // (unpadded delimiter row), could result in a table.
      { atBreak: true, character: "|", after: "[	 :-]" },
      // A pipe in a cell must be encoded.
      { character: "|", inConstruct: "tableCell" },
      // A colon must be followed by a dash, in which case it could start a
      // delimiter row.
      { atBreak: true, character: ":", after: "-" },
      // A delimiter row can also start with a dash, when followed by more
      // dashes, a colon, or a pipe.
      // This is a stricter version than the built in check for lists, thematic
      // breaks, and setex heading underlines though:
      // <https://github.com/syntax-tree/mdast-util-to-markdown/blob/51a2038/lib/unsafe.js#L57>
      { atBreak: true, character: "-", after: "[:|-]" }
    ],
    handlers: {
      inlineCode: inlineCodeWithTable,
      table: handleTable,
      tableCell: handleTableCell,
      tableRow: handleTableRow
    }
  };
  function handleTable(node2, _2, state, info) {
    return serializeData(handleTableAsData(node2, state, info), node2.align);
  }
  function handleTableRow(node2, _2, state, info) {
    const row2 = handleTableRowAsData(node2, state, info);
    const value = serializeData([row2]);
    return value.slice(0, value.indexOf("\n"));
  }
  function handleTableCell(node2, _2, state, info) {
    const exit3 = state.enter("tableCell");
    const subexit = state.enter("phrasing");
    const value = state.containerPhrasing(node2, {
      ...info,
      before: around,
      after: around
    });
    subexit();
    exit3();
    return value;
  }
  function serializeData(matrix, align) {
    return markdownTable(matrix, {
      align,
      // @ts-expect-error: `markdown-table` types should support `null`.
      alignDelimiters,
      // @ts-expect-error: `markdown-table` types should support `null`.
      padding,
      // @ts-expect-error: `markdown-table` types should support `null`.
      stringLength
    });
  }
  function handleTableAsData(node2, state, info) {
    const children = node2.children;
    let index4 = -1;
    const result = [];
    const subexit = state.enter("table");
    while (++index4 < children.length) {
      result[index4] = handleTableRowAsData(children[index4], state, info);
    }
    subexit();
    return result;
  }
  function handleTableRowAsData(node2, state, info) {
    const children = node2.children;
    let index4 = -1;
    const result = [];
    const subexit = state.enter("tableRow");
    while (++index4 < children.length) {
      result[index4] = handleTableCell(children[index4], node2, state, info);
    }
    subexit();
    return result;
  }
  function inlineCodeWithTable(node2, parent, state) {
    let value = handle2.inlineCode(node2, parent, state);
    if (state.stack.includes("tableCell")) {
      value = value.replace(/\|/g, "\\$&");
    }
    return value;
  }
}

// ../../node_modules/.pnpm/mdast-util-gfm-task-list-item@2.0.0/node_modules/mdast-util-gfm-task-list-item/lib/index.js
function gfmTaskListItemFromMarkdown() {
  return {
    exit: {
      taskListCheckValueChecked: exitCheck,
      taskListCheckValueUnchecked: exitCheck,
      paragraph: exitParagraphWithTaskListItem
    }
  };
}
function gfmTaskListItemToMarkdown() {
  return {
    unsafe: [{ atBreak: true, character: "-", after: "[:|-]" }],
    handlers: { listItem: listItemWithTaskListItem }
  };
}
function exitCheck(token) {
  const node2 = this.stack[this.stack.length - 2];
  ok(node2.type === "listItem");
  node2.checked = token.type === "taskListCheckValueChecked";
}
function exitParagraphWithTaskListItem(token) {
  const parent = this.stack[this.stack.length - 2];
  if (parent && parent.type === "listItem" && typeof parent.checked === "boolean") {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2.type === "paragraph");
    const head2 = node2.children[0];
    if (head2 && head2.type === "text") {
      const siblings2 = parent.children;
      let index4 = -1;
      let firstParaghraph;
      while (++index4 < siblings2.length) {
        const sibling = siblings2[index4];
        if (sibling.type === "paragraph") {
          firstParaghraph = sibling;
          break;
        }
      }
      if (firstParaghraph === node2) {
        head2.value = head2.value.slice(1);
        if (head2.value.length === 0) {
          node2.children.shift();
        } else if (node2.position && head2.position && typeof head2.position.start.offset === "number") {
          head2.position.start.column++;
          head2.position.start.offset++;
          node2.position.start = Object.assign({}, head2.position.start);
        }
      }
    }
  }
  this.exit(token);
}
function listItemWithTaskListItem(node2, parent, state, info) {
  const head2 = node2.children[0];
  const checkable = typeof node2.checked === "boolean" && head2 && head2.type === "paragraph";
  const checkbox = "[" + (node2.checked ? "x" : " ") + "] ";
  const tracker = state.createTracker(info);
  if (checkable) {
    tracker.move(checkbox);
  }
  let value = handle2.listItem(node2, parent, state, {
    ...info,
    ...tracker.current()
  });
  if (checkable) {
    value = value.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/, check);
  }
  return value;
  function check($0) {
    return $0 + checkbox;
  }
}

// ../../node_modules/.pnpm/mdast-util-gfm@3.1.0/node_modules/mdast-util-gfm/lib/index.js
function gfmFromMarkdown() {
  return [
    gfmAutolinkLiteralFromMarkdown(),
    gfmFootnoteFromMarkdown(),
    gfmStrikethroughFromMarkdown(),
    gfmTableFromMarkdown(),
    gfmTaskListItemFromMarkdown()
  ];
}
function gfmToMarkdown(options2) {
  return {
    extensions: [
      gfmAutolinkLiteralToMarkdown(),
      gfmFootnoteToMarkdown(options2),
      gfmStrikethroughToMarkdown(),
      gfmTableToMarkdown(options2),
      gfmTaskListItemToMarkdown()
    ]
  };
}

// ../../node_modules/.pnpm/micromark-util-chunked@2.0.1/node_modules/micromark-util-chunked/dev/index.js
function splice(list7, start, remove, items) {
  const end = list7.length;
  let chunkStart = 0;
  let parameters;
  if (start < 0) {
    start = -start > end ? 0 : end + start;
  } else {
    start = start > end ? end : start;
  }
  remove = remove > 0 ? remove : 0;
  if (items.length < constants.v8MaxSafeChunkSize) {
    parameters = Array.from(items);
    parameters.unshift(start, remove);
    list7.splice(...parameters);
  } else {
    if (remove) list7.splice(start, remove);
    while (chunkStart < items.length) {
      parameters = items.slice(
        chunkStart,
        chunkStart + constants.v8MaxSafeChunkSize
      );
      parameters.unshift(start, 0);
      list7.splice(...parameters);
      chunkStart += constants.v8MaxSafeChunkSize;
      start += constants.v8MaxSafeChunkSize;
    }
  }
}
function push(list7, items) {
  if (list7.length > 0) {
    splice(list7, list7.length, 0, items);
    return list7;
  }
  return items;
}

// ../../node_modules/.pnpm/micromark-util-combine-extensions@2.0.1/node_modules/micromark-util-combine-extensions/index.js
var hasOwnProperty = {}.hasOwnProperty;
function combineExtensions(extensions) {
  const all9 = {};
  let index4 = -1;
  while (++index4 < extensions.length) {
    syntaxExtension(all9, extensions[index4]);
  }
  return all9;
}
function syntaxExtension(all9, extension2) {
  let hook;
  for (hook in extension2) {
    const maybe = hasOwnProperty.call(all9, hook) ? all9[hook] : void 0;
    const left = maybe || (all9[hook] = {});
    const right = extension2[hook];
    let code5;
    if (right) {
      for (code5 in right) {
        if (!hasOwnProperty.call(left, code5)) left[code5] = [];
        const value = right[code5];
        constructs(
          // @ts-expect-error Looks like a list.
          left[code5],
          Array.isArray(value) ? value : value ? [value] : []
        );
      }
    }
  }
}
function constructs(existing, list7) {
  let index4 = -1;
  const before = [];
  while (++index4 < list7.length) {
    ;
    (list7[index4].add === "after" ? existing : before).push(list7[index4]);
  }
  splice(existing, 0, 0, before);
}

// ../../node_modules/.pnpm/micromark-extension-gfm-autolink-literal@2.1.0/node_modules/micromark-extension-gfm-autolink-literal/dev/lib/syntax.js
var wwwPrefix = { tokenize: tokenizeWwwPrefix, partial: true };
var domain = { tokenize: tokenizeDomain, partial: true };
var path = { tokenize: tokenizePath, partial: true };
var trail = { tokenize: tokenizeTrail, partial: true };
var emailDomainDotTrail = {
  tokenize: tokenizeEmailDomainDotTrail,
  partial: true
};
var wwwAutolink = {
  name: "wwwAutolink",
  tokenize: tokenizeWwwAutolink,
  previous: previousWww
};
var protocolAutolink = {
  name: "protocolAutolink",
  tokenize: tokenizeProtocolAutolink,
  previous: previousProtocol
};
var emailAutolink = {
  name: "emailAutolink",
  tokenize: tokenizeEmailAutolink,
  previous: previousEmail
};
var text4 = {};
function gfmAutolinkLiteral() {
  return { text: text4 };
}
var code3 = codes.digit0;
while (code3 < codes.leftCurlyBrace) {
  text4[code3] = emailAutolink;
  code3++;
  if (code3 === codes.colon) code3 = codes.uppercaseA;
  else if (code3 === codes.leftSquareBracket) code3 = codes.lowercaseA;
}
text4[codes.plusSign] = emailAutolink;
text4[codes.dash] = emailAutolink;
text4[codes.dot] = emailAutolink;
text4[codes.underscore] = emailAutolink;
text4[codes.uppercaseH] = [emailAutolink, protocolAutolink];
text4[codes.lowercaseH] = [emailAutolink, protocolAutolink];
text4[codes.uppercaseW] = [emailAutolink, wwwAutolink];
text4[codes.lowercaseW] = [emailAutolink, wwwAutolink];
function tokenizeEmailAutolink(effects, ok3, nok) {
  const self2 = this;
  let dot;
  let data;
  return start;
  function start(code5) {
    if (!gfmAtext(code5) || !previousEmail.call(self2, self2.previous) || previousUnbalanced(self2.events)) {
      return nok(code5);
    }
    effects.enter("literalAutolink");
    effects.enter("literalAutolinkEmail");
    return atext(code5);
  }
  function atext(code5) {
    if (gfmAtext(code5)) {
      effects.consume(code5);
      return atext;
    }
    if (code5 === codes.atSign) {
      effects.consume(code5);
      return emailDomain;
    }
    return nok(code5);
  }
  function emailDomain(code5) {
    if (code5 === codes.dot) {
      return effects.check(
        emailDomainDotTrail,
        emailDomainAfter,
        emailDomainDot
      )(code5);
    }
    if (code5 === codes.dash || code5 === codes.underscore || asciiAlphanumeric(code5)) {
      data = true;
      effects.consume(code5);
      return emailDomain;
    }
    return emailDomainAfter(code5);
  }
  function emailDomainDot(code5) {
    effects.consume(code5);
    dot = true;
    return emailDomain;
  }
  function emailDomainAfter(code5) {
    if (data && dot && asciiAlpha(self2.previous)) {
      effects.exit("literalAutolinkEmail");
      effects.exit("literalAutolink");
      return ok3(code5);
    }
    return nok(code5);
  }
}
function tokenizeWwwAutolink(effects, ok3, nok) {
  const self2 = this;
  return wwwStart;
  function wwwStart(code5) {
    if (code5 !== codes.uppercaseW && code5 !== codes.lowercaseW || !previousWww.call(self2, self2.previous) || previousUnbalanced(self2.events)) {
      return nok(code5);
    }
    effects.enter("literalAutolink");
    effects.enter("literalAutolinkWww");
    return effects.check(
      wwwPrefix,
      effects.attempt(domain, effects.attempt(path, wwwAfter), nok),
      nok
    )(code5);
  }
  function wwwAfter(code5) {
    effects.exit("literalAutolinkWww");
    effects.exit("literalAutolink");
    return ok3(code5);
  }
}
function tokenizeProtocolAutolink(effects, ok3, nok) {
  const self2 = this;
  let buffer = "";
  let seen = false;
  return protocolStart;
  function protocolStart(code5) {
    if ((code5 === codes.uppercaseH || code5 === codes.lowercaseH) && previousProtocol.call(self2, self2.previous) && !previousUnbalanced(self2.events)) {
      effects.enter("literalAutolink");
      effects.enter("literalAutolinkHttp");
      buffer += String.fromCodePoint(code5);
      effects.consume(code5);
      return protocolPrefixInside;
    }
    return nok(code5);
  }
  function protocolPrefixInside(code5) {
    if (asciiAlpha(code5) && buffer.length < 5) {
      buffer += String.fromCodePoint(code5);
      effects.consume(code5);
      return protocolPrefixInside;
    }
    if (code5 === codes.colon) {
      const protocol = buffer.toLowerCase();
      if (protocol === "http" || protocol === "https") {
        effects.consume(code5);
        return protocolSlashesInside;
      }
    }
    return nok(code5);
  }
  function protocolSlashesInside(code5) {
    if (code5 === codes.slash) {
      effects.consume(code5);
      if (seen) {
        return afterProtocol;
      }
      seen = true;
      return protocolSlashesInside;
    }
    return nok(code5);
  }
  function afterProtocol(code5) {
    return code5 === codes.eof || asciiControl(code5) || markdownLineEndingOrSpace(code5) || unicodeWhitespace(code5) || unicodePunctuation(code5) ? nok(code5) : effects.attempt(domain, effects.attempt(path, protocolAfter), nok)(code5);
  }
  function protocolAfter(code5) {
    effects.exit("literalAutolinkHttp");
    effects.exit("literalAutolink");
    return ok3(code5);
  }
}
function tokenizeWwwPrefix(effects, ok3, nok) {
  let size5 = 0;
  return wwwPrefixInside;
  function wwwPrefixInside(code5) {
    if ((code5 === codes.uppercaseW || code5 === codes.lowercaseW) && size5 < 3) {
      size5++;
      effects.consume(code5);
      return wwwPrefixInside;
    }
    if (code5 === codes.dot && size5 === 3) {
      effects.consume(code5);
      return wwwPrefixAfter;
    }
    return nok(code5);
  }
  function wwwPrefixAfter(code5) {
    return code5 === codes.eof ? nok(code5) : ok3(code5);
  }
}
function tokenizeDomain(effects, ok3, nok) {
  let underscoreInLastSegment;
  let underscoreInLastLastSegment;
  let seen;
  return domainInside;
  function domainInside(code5) {
    if (code5 === codes.dot || code5 === codes.underscore) {
      return effects.check(trail, domainAfter, domainAtPunctuation)(code5);
    }
    if (code5 === codes.eof || markdownLineEndingOrSpace(code5) || unicodeWhitespace(code5) || code5 !== codes.dash && unicodePunctuation(code5)) {
      return domainAfter(code5);
    }
    seen = true;
    effects.consume(code5);
    return domainInside;
  }
  function domainAtPunctuation(code5) {
    if (code5 === codes.underscore) {
      underscoreInLastSegment = true;
    } else {
      underscoreInLastLastSegment = underscoreInLastSegment;
      underscoreInLastSegment = void 0;
    }
    effects.consume(code5);
    return domainInside;
  }
  function domainAfter(code5) {
    if (underscoreInLastLastSegment || underscoreInLastSegment || !seen) {
      return nok(code5);
    }
    return ok3(code5);
  }
}
function tokenizePath(effects, ok3) {
  let sizeOpen = 0;
  let sizeClose = 0;
  return pathInside;
  function pathInside(code5) {
    if (code5 === codes.leftParenthesis) {
      sizeOpen++;
      effects.consume(code5);
      return pathInside;
    }
    if (code5 === codes.rightParenthesis && sizeClose < sizeOpen) {
      return pathAtPunctuation(code5);
    }
    if (code5 === codes.exclamationMark || code5 === codes.quotationMark || code5 === codes.ampersand || code5 === codes.apostrophe || code5 === codes.rightParenthesis || code5 === codes.asterisk || code5 === codes.comma || code5 === codes.dot || code5 === codes.colon || code5 === codes.semicolon || code5 === codes.lessThan || code5 === codes.questionMark || code5 === codes.rightSquareBracket || code5 === codes.underscore || code5 === codes.tilde) {
      return effects.check(trail, ok3, pathAtPunctuation)(code5);
    }
    if (code5 === codes.eof || markdownLineEndingOrSpace(code5) || unicodeWhitespace(code5)) {
      return ok3(code5);
    }
    effects.consume(code5);
    return pathInside;
  }
  function pathAtPunctuation(code5) {
    if (code5 === codes.rightParenthesis) {
      sizeClose++;
    }
    effects.consume(code5);
    return pathInside;
  }
}
function tokenizeTrail(effects, ok3, nok) {
  return trail2;
  function trail2(code5) {
    if (code5 === codes.exclamationMark || code5 === codes.quotationMark || code5 === codes.apostrophe || code5 === codes.rightParenthesis || code5 === codes.asterisk || code5 === codes.comma || code5 === codes.dot || code5 === codes.colon || code5 === codes.semicolon || code5 === codes.questionMark || code5 === codes.underscore || code5 === codes.tilde) {
      effects.consume(code5);
      return trail2;
    }
    if (code5 === codes.ampersand) {
      effects.consume(code5);
      return trailCharacterReferenceStart;
    }
    if (code5 === codes.rightSquareBracket) {
      effects.consume(code5);
      return trailBracketAfter;
    }
    if (
      // `<` is an end.
      code5 === codes.lessThan || // So is whitespace.
      code5 === codes.eof || markdownLineEndingOrSpace(code5) || unicodeWhitespace(code5)
    ) {
      return ok3(code5);
    }
    return nok(code5);
  }
  function trailBracketAfter(code5) {
    if (code5 === codes.eof || code5 === codes.leftParenthesis || code5 === codes.leftSquareBracket || markdownLineEndingOrSpace(code5) || unicodeWhitespace(code5)) {
      return ok3(code5);
    }
    return trail2(code5);
  }
  function trailCharacterReferenceStart(code5) {
    return asciiAlpha(code5) ? trailCharacterReferenceInside(code5) : nok(code5);
  }
  function trailCharacterReferenceInside(code5) {
    if (code5 === codes.semicolon) {
      effects.consume(code5);
      return trail2;
    }
    if (asciiAlpha(code5)) {
      effects.consume(code5);
      return trailCharacterReferenceInside;
    }
    return nok(code5);
  }
}
function tokenizeEmailDomainDotTrail(effects, ok3, nok) {
  return start;
  function start(code5) {
    effects.consume(code5);
    return after;
  }
  function after(code5) {
    return asciiAlphanumeric(code5) ? nok(code5) : ok3(code5);
  }
}
function previousWww(code5) {
  return code5 === codes.eof || code5 === codes.leftParenthesis || code5 === codes.asterisk || code5 === codes.underscore || code5 === codes.leftSquareBracket || code5 === codes.rightSquareBracket || code5 === codes.tilde || markdownLineEndingOrSpace(code5);
}
function previousProtocol(code5) {
  return !asciiAlpha(code5);
}
function previousEmail(code5) {
  return !(code5 === codes.slash || gfmAtext(code5));
}
function gfmAtext(code5) {
  return code5 === codes.plusSign || code5 === codes.dash || code5 === codes.dot || code5 === codes.underscore || asciiAlphanumeric(code5);
}
function previousUnbalanced(events) {
  let index4 = events.length;
  let result = false;
  while (index4--) {
    const token = events[index4][1];
    if ((token.type === "labelLink" || token.type === "labelImage") && !token._balanced) {
      result = true;
      break;
    }
    if (token._gfmAutolinkLiteralWalkedInto) {
      result = false;
      break;
    }
  }
  if (events.length > 0 && !result) {
    events[events.length - 1][1]._gfmAutolinkLiteralWalkedInto = true;
  }
  return result;
}

// ../../node_modules/.pnpm/micromark-util-sanitize-uri@2.0.1/node_modules/micromark-util-sanitize-uri/dev/index.js
function normalizeUri(value) {
  const result = [];
  let index4 = -1;
  let start = 0;
  let skip = 0;
  while (++index4 < value.length) {
    const code5 = value.charCodeAt(index4);
    let replace3 = "";
    if (code5 === codes.percentSign && asciiAlphanumeric(value.charCodeAt(index4 + 1)) && asciiAlphanumeric(value.charCodeAt(index4 + 2))) {
      skip = 2;
    } else if (code5 < 128) {
      if (!/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(code5))) {
        replace3 = String.fromCharCode(code5);
      }
    } else if (code5 > 55295 && code5 < 57344) {
      const next2 = value.charCodeAt(index4 + 1);
      if (code5 < 56320 && next2 > 56319 && next2 < 57344) {
        replace3 = String.fromCharCode(code5, next2);
        skip = 1;
      } else {
        replace3 = values.replacementCharacter;
      }
    } else {
      replace3 = String.fromCharCode(code5);
    }
    if (replace3) {
      result.push(value.slice(start, index4), encodeURIComponent(replace3));
      start = index4 + skip + 1;
      replace3 = "";
    }
    if (skip) {
      index4 += skip;
      skip = 0;
    }
  }
  return result.join("") + value.slice(start);
}

// ../../node_modules/.pnpm/micromark-util-resolve-all@2.0.1/node_modules/micromark-util-resolve-all/index.js
function resolveAll(constructs2, events, context) {
  const called = [];
  let index4 = -1;
  while (++index4 < constructs2.length) {
    const resolve2 = constructs2[index4].resolveAll;
    if (resolve2 && !called.includes(resolve2)) {
      events = resolve2(events, context);
      called.push(resolve2);
    }
  }
  return events;
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/attention.js
var attention = {
  name: "attention",
  resolveAll: resolveAllAttention,
  tokenize: tokenizeAttention
};
function resolveAllAttention(events, context) {
  let index4 = -1;
  let open;
  let group;
  let text10;
  let openingSequence;
  let closingSequence;
  let use;
  let nextEvents;
  let offset4;
  while (++index4 < events.length) {
    if (events[index4][0] === "enter" && events[index4][1].type === "attentionSequence" && events[index4][1]._close) {
      open = index4;
      while (open--) {
        if (events[open][0] === "exit" && events[open][1].type === "attentionSequence" && events[open][1]._open && // If the markers are the same:
        context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index4][1]).charCodeAt(0)) {
          if ((events[open][1]._close || events[index4][1]._open) && (events[index4][1].end.offset - events[index4][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index4][1].end.offset - events[index4][1].start.offset) % 3)) {
            continue;
          }
          use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index4][1].end.offset - events[index4][1].start.offset > 1 ? 2 : 1;
          const start = { ...events[open][1].end };
          const end = { ...events[index4][1].start };
          movePoint(start, -use);
          movePoint(end, use);
          openingSequence = {
            type: use > 1 ? types.strongSequence : types.emphasisSequence,
            start,
            end: { ...events[open][1].end }
          };
          closingSequence = {
            type: use > 1 ? types.strongSequence : types.emphasisSequence,
            start: { ...events[index4][1].start },
            end
          };
          text10 = {
            type: use > 1 ? types.strongText : types.emphasisText,
            start: { ...events[open][1].end },
            end: { ...events[index4][1].start }
          };
          group = {
            type: use > 1 ? types.strong : types.emphasis,
            start: { ...openingSequence.start },
            end: { ...closingSequence.end }
          };
          events[open][1].end = { ...openingSequence.start };
          events[index4][1].start = { ...closingSequence.end };
          nextEvents = [];
          if (events[open][1].end.offset - events[open][1].start.offset) {
            nextEvents = push(nextEvents, [
              ["enter", events[open][1], context],
              ["exit", events[open][1], context]
            ]);
          }
          nextEvents = push(nextEvents, [
            ["enter", group, context],
            ["enter", openingSequence, context],
            ["exit", openingSequence, context],
            ["enter", text10, context]
          ]);
          ok(
            context.parser.constructs.insideSpan.null,
            "expected `insideSpan` to be populated"
          );
          nextEvents = push(
            nextEvents,
            resolveAll(
              context.parser.constructs.insideSpan.null,
              events.slice(open + 1, index4),
              context
            )
          );
          nextEvents = push(nextEvents, [
            ["exit", text10, context],
            ["enter", closingSequence, context],
            ["exit", closingSequence, context],
            ["exit", group, context]
          ]);
          if (events[index4][1].end.offset - events[index4][1].start.offset) {
            offset4 = 2;
            nextEvents = push(nextEvents, [
              ["enter", events[index4][1], context],
              ["exit", events[index4][1], context]
            ]);
          } else {
            offset4 = 0;
          }
          splice(events, open - 1, index4 - open + 3, nextEvents);
          index4 = open + nextEvents.length - offset4 - 2;
          break;
        }
      }
    }
  }
  index4 = -1;
  while (++index4 < events.length) {
    if (events[index4][1].type === "attentionSequence") {
      events[index4][1].type = "data";
    }
  }
  return events;
}
function tokenizeAttention(effects, ok3) {
  const attentionMarkers2 = this.parser.constructs.attentionMarkers.null;
  const previous3 = this.previous;
  const before = classifyCharacter(previous3);
  let marker;
  return start;
  function start(code5) {
    ok(
      code5 === codes.asterisk || code5 === codes.underscore,
      "expected asterisk or underscore"
    );
    marker = code5;
    effects.enter("attentionSequence");
    return inside(code5);
  }
  function inside(code5) {
    if (code5 === marker) {
      effects.consume(code5);
      return inside;
    }
    const token = effects.exit("attentionSequence");
    const after = classifyCharacter(code5);
    ok(attentionMarkers2, "expected `attentionMarkers` to be populated");
    const open = !after || after === constants.characterGroupPunctuation && before || attentionMarkers2.includes(code5);
    const close2 = !before || before === constants.characterGroupPunctuation && after || attentionMarkers2.includes(previous3);
    token._open = Boolean(
      marker === codes.asterisk ? open : open && (before || !close2)
    );
    token._close = Boolean(
      marker === codes.asterisk ? close2 : close2 && (after || !open)
    );
    return ok3(code5);
  }
}
function movePoint(point5, offset4) {
  point5.column += offset4;
  point5.offset += offset4;
  point5._bufferIndex += offset4;
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/autolink.js
var autolink = { name: "autolink", tokenize: tokenizeAutolink };
function tokenizeAutolink(effects, ok3, nok) {
  let size5 = 0;
  return start;
  function start(code5) {
    ok(code5 === codes.lessThan, "expected `<`");
    effects.enter(types.autolink);
    effects.enter(types.autolinkMarker);
    effects.consume(code5);
    effects.exit(types.autolinkMarker);
    effects.enter(types.autolinkProtocol);
    return open;
  }
  function open(code5) {
    if (asciiAlpha(code5)) {
      effects.consume(code5);
      return schemeOrEmailAtext;
    }
    if (code5 === codes.atSign) {
      return nok(code5);
    }
    return emailAtext(code5);
  }
  function schemeOrEmailAtext(code5) {
    if (code5 === codes.plusSign || code5 === codes.dash || code5 === codes.dot || asciiAlphanumeric(code5)) {
      size5 = 1;
      return schemeInsideOrEmailAtext(code5);
    }
    return emailAtext(code5);
  }
  function schemeInsideOrEmailAtext(code5) {
    if (code5 === codes.colon) {
      effects.consume(code5);
      size5 = 0;
      return urlInside;
    }
    if ((code5 === codes.plusSign || code5 === codes.dash || code5 === codes.dot || asciiAlphanumeric(code5)) && size5++ < constants.autolinkSchemeSizeMax) {
      effects.consume(code5);
      return schemeInsideOrEmailAtext;
    }
    size5 = 0;
    return emailAtext(code5);
  }
  function urlInside(code5) {
    if (code5 === codes.greaterThan) {
      effects.exit(types.autolinkProtocol);
      effects.enter(types.autolinkMarker);
      effects.consume(code5);
      effects.exit(types.autolinkMarker);
      effects.exit(types.autolink);
      return ok3;
    }
    if (code5 === codes.eof || code5 === codes.space || code5 === codes.lessThan || asciiControl(code5)) {
      return nok(code5);
    }
    effects.consume(code5);
    return urlInside;
  }
  function emailAtext(code5) {
    if (code5 === codes.atSign) {
      effects.consume(code5);
      return emailAtSignOrDot;
    }
    if (asciiAtext(code5)) {
      effects.consume(code5);
      return emailAtext;
    }
    return nok(code5);
  }
  function emailAtSignOrDot(code5) {
    return asciiAlphanumeric(code5) ? emailLabel(code5) : nok(code5);
  }
  function emailLabel(code5) {
    if (code5 === codes.dot) {
      effects.consume(code5);
      size5 = 0;
      return emailAtSignOrDot;
    }
    if (code5 === codes.greaterThan) {
      effects.exit(types.autolinkProtocol).type = types.autolinkEmail;
      effects.enter(types.autolinkMarker);
      effects.consume(code5);
      effects.exit(types.autolinkMarker);
      effects.exit(types.autolink);
      return ok3;
    }
    return emailValue(code5);
  }
  function emailValue(code5) {
    if ((code5 === codes.dash || asciiAlphanumeric(code5)) && size5++ < constants.autolinkDomainSizeMax) {
      const next2 = code5 === codes.dash ? emailValue : emailLabel;
      effects.consume(code5);
      return next2;
    }
    return nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-factory-space@2.0.1/node_modules/micromark-factory-space/dev/index.js
function factorySpace(effects, ok3, type, max3) {
  const limit = max3 ? max3 - 1 : Number.POSITIVE_INFINITY;
  let size5 = 0;
  return start;
  function start(code5) {
    if (markdownSpace(code5)) {
      effects.enter(type);
      return prefix3(code5);
    }
    return ok3(code5);
  }
  function prefix3(code5) {
    if (markdownSpace(code5) && size5++ < limit) {
      effects.consume(code5);
      return prefix3;
    }
    effects.exit(type);
    return ok3(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/blank-line.js
var blankLine = { partial: true, tokenize: tokenizeBlankLine };
function tokenizeBlankLine(effects, ok3, nok) {
  return start;
  function start(code5) {
    return markdownSpace(code5) ? factorySpace(effects, after, types.linePrefix)(code5) : after(code5);
  }
  function after(code5) {
    return code5 === codes.eof || markdownLineEnding(code5) ? ok3(code5) : nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/block-quote.js
var blockQuote = {
  continuation: { tokenize: tokenizeBlockQuoteContinuation },
  exit: exit2,
  name: "blockQuote",
  tokenize: tokenizeBlockQuoteStart
};
function tokenizeBlockQuoteStart(effects, ok3, nok) {
  const self2 = this;
  return start;
  function start(code5) {
    if (code5 === codes.greaterThan) {
      const state = self2.containerState;
      ok(state, "expected `containerState` to be defined in container");
      if (!state.open) {
        effects.enter(types.blockQuote, { _container: true });
        state.open = true;
      }
      effects.enter(types.blockQuotePrefix);
      effects.enter(types.blockQuoteMarker);
      effects.consume(code5);
      effects.exit(types.blockQuoteMarker);
      return after;
    }
    return nok(code5);
  }
  function after(code5) {
    if (markdownSpace(code5)) {
      effects.enter(types.blockQuotePrefixWhitespace);
      effects.consume(code5);
      effects.exit(types.blockQuotePrefixWhitespace);
      effects.exit(types.blockQuotePrefix);
      return ok3;
    }
    effects.exit(types.blockQuotePrefix);
    return ok3(code5);
  }
}
function tokenizeBlockQuoteContinuation(effects, ok3, nok) {
  const self2 = this;
  return contStart;
  function contStart(code5) {
    if (markdownSpace(code5)) {
      ok(
        self2.parser.constructs.disable.null,
        "expected `disable.null` to be populated"
      );
      return factorySpace(
        effects,
        contBefore,
        types.linePrefix,
        self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : constants.tabSize
      )(code5);
    }
    return contBefore(code5);
  }
  function contBefore(code5) {
    return effects.attempt(blockQuote, ok3, nok)(code5);
  }
}
function exit2(effects) {
  effects.exit(types.blockQuote);
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/character-escape.js
var characterEscape = {
  name: "characterEscape",
  tokenize: tokenizeCharacterEscape
};
function tokenizeCharacterEscape(effects, ok3, nok) {
  return start;
  function start(code5) {
    ok(code5 === codes.backslash, "expected `\\`");
    effects.enter(types.characterEscape);
    effects.enter(types.escapeMarker);
    effects.consume(code5);
    effects.exit(types.escapeMarker);
    return inside;
  }
  function inside(code5) {
    if (asciiPunctuation(code5)) {
      effects.enter(types.characterEscapeValue);
      effects.consume(code5);
      effects.exit(types.characterEscapeValue);
      effects.exit(types.characterEscape);
      return ok3;
    }
    return nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/character-reference.js
var characterReference = {
  name: "characterReference",
  tokenize: tokenizeCharacterReference
};
function tokenizeCharacterReference(effects, ok3, nok) {
  const self2 = this;
  let size5 = 0;
  let max3;
  let test;
  return start;
  function start(code5) {
    ok(code5 === codes.ampersand, "expected `&`");
    effects.enter(types.characterReference);
    effects.enter(types.characterReferenceMarker);
    effects.consume(code5);
    effects.exit(types.characterReferenceMarker);
    return open;
  }
  function open(code5) {
    if (code5 === codes.numberSign) {
      effects.enter(types.characterReferenceMarkerNumeric);
      effects.consume(code5);
      effects.exit(types.characterReferenceMarkerNumeric);
      return numeric2;
    }
    effects.enter(types.characterReferenceValue);
    max3 = constants.characterReferenceNamedSizeMax;
    test = asciiAlphanumeric;
    return value(code5);
  }
  function numeric2(code5) {
    if (code5 === codes.uppercaseX || code5 === codes.lowercaseX) {
      effects.enter(types.characterReferenceMarkerHexadecimal);
      effects.consume(code5);
      effects.exit(types.characterReferenceMarkerHexadecimal);
      effects.enter(types.characterReferenceValue);
      max3 = constants.characterReferenceHexadecimalSizeMax;
      test = asciiHexDigit;
      return value;
    }
    effects.enter(types.characterReferenceValue);
    max3 = constants.characterReferenceDecimalSizeMax;
    test = asciiDigit;
    return value(code5);
  }
  function value(code5) {
    if (code5 === codes.semicolon && size5) {
      const token = effects.exit(types.characterReferenceValue);
      if (test === asciiAlphanumeric && !decodeNamedCharacterReference(self2.sliceSerialize(token))) {
        return nok(code5);
      }
      effects.enter(types.characterReferenceMarker);
      effects.consume(code5);
      effects.exit(types.characterReferenceMarker);
      effects.exit(types.characterReference);
      return ok3;
    }
    if (test(code5) && size5++ < max3) {
      effects.consume(code5);
      return value;
    }
    return nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/code-fenced.js
var nonLazyContinuation = {
  partial: true,
  tokenize: tokenizeNonLazyContinuation
};
var codeFenced = {
  concrete: true,
  name: "codeFenced",
  tokenize: tokenizeCodeFenced
};
function tokenizeCodeFenced(effects, ok3, nok) {
  const self2 = this;
  const closeStart = { partial: true, tokenize: tokenizeCloseStart };
  let initialPrefix = 0;
  let sizeOpen = 0;
  let marker;
  return start;
  function start(code5) {
    return beforeSequenceOpen(code5);
  }
  function beforeSequenceOpen(code5) {
    ok(
      code5 === codes.graveAccent || code5 === codes.tilde,
      "expected `` ` `` or `~`"
    );
    const tail = self2.events[self2.events.length - 1];
    initialPrefix = tail && tail[1].type === types.linePrefix ? tail[2].sliceSerialize(tail[1], true).length : 0;
    marker = code5;
    effects.enter(types.codeFenced);
    effects.enter(types.codeFencedFence);
    effects.enter(types.codeFencedFenceSequence);
    return sequenceOpen(code5);
  }
  function sequenceOpen(code5) {
    if (code5 === marker) {
      sizeOpen++;
      effects.consume(code5);
      return sequenceOpen;
    }
    if (sizeOpen < constants.codeFencedSequenceSizeMin) {
      return nok(code5);
    }
    effects.exit(types.codeFencedFenceSequence);
    return markdownSpace(code5) ? factorySpace(effects, infoBefore, types.whitespace)(code5) : infoBefore(code5);
  }
  function infoBefore(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.codeFencedFence);
      return self2.interrupt ? ok3(code5) : effects.check(nonLazyContinuation, atNonLazyBreak, after)(code5);
    }
    effects.enter(types.codeFencedFenceInfo);
    effects.enter(types.chunkString, { contentType: constants.contentTypeString });
    return info(code5);
  }
  function info(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.chunkString);
      effects.exit(types.codeFencedFenceInfo);
      return infoBefore(code5);
    }
    if (markdownSpace(code5)) {
      effects.exit(types.chunkString);
      effects.exit(types.codeFencedFenceInfo);
      return factorySpace(effects, metaBefore, types.whitespace)(code5);
    }
    if (code5 === codes.graveAccent && code5 === marker) {
      return nok(code5);
    }
    effects.consume(code5);
    return info;
  }
  function metaBefore(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      return infoBefore(code5);
    }
    effects.enter(types.codeFencedFenceMeta);
    effects.enter(types.chunkString, { contentType: constants.contentTypeString });
    return meta2(code5);
  }
  function meta2(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.chunkString);
      effects.exit(types.codeFencedFenceMeta);
      return infoBefore(code5);
    }
    if (code5 === codes.graveAccent && code5 === marker) {
      return nok(code5);
    }
    effects.consume(code5);
    return meta2;
  }
  function atNonLazyBreak(code5) {
    ok(markdownLineEnding(code5), "expected eol");
    return effects.attempt(closeStart, after, contentBefore)(code5);
  }
  function contentBefore(code5) {
    ok(markdownLineEnding(code5), "expected eol");
    effects.enter(types.lineEnding);
    effects.consume(code5);
    effects.exit(types.lineEnding);
    return contentStart;
  }
  function contentStart(code5) {
    return initialPrefix > 0 && markdownSpace(code5) ? factorySpace(
      effects,
      beforeContentChunk,
      types.linePrefix,
      initialPrefix + 1
    )(code5) : beforeContentChunk(code5);
  }
  function beforeContentChunk(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      return effects.check(nonLazyContinuation, atNonLazyBreak, after)(code5);
    }
    effects.enter(types.codeFlowValue);
    return contentChunk(code5);
  }
  function contentChunk(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.codeFlowValue);
      return beforeContentChunk(code5);
    }
    effects.consume(code5);
    return contentChunk;
  }
  function after(code5) {
    effects.exit(types.codeFenced);
    return ok3(code5);
  }
  function tokenizeCloseStart(effects2, ok4, nok2) {
    let size5 = 0;
    return startBefore;
    function startBefore(code5) {
      ok(markdownLineEnding(code5), "expected eol");
      effects2.enter(types.lineEnding);
      effects2.consume(code5);
      effects2.exit(types.lineEnding);
      return start2;
    }
    function start2(code5) {
      ok(
        self2.parser.constructs.disable.null,
        "expected `disable.null` to be populated"
      );
      effects2.enter(types.codeFencedFence);
      return markdownSpace(code5) ? factorySpace(
        effects2,
        beforeSequenceClose,
        types.linePrefix,
        self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : constants.tabSize
      )(code5) : beforeSequenceClose(code5);
    }
    function beforeSequenceClose(code5) {
      if (code5 === marker) {
        effects2.enter(types.codeFencedFenceSequence);
        return sequenceClose(code5);
      }
      return nok2(code5);
    }
    function sequenceClose(code5) {
      if (code5 === marker) {
        size5++;
        effects2.consume(code5);
        return sequenceClose;
      }
      if (size5 >= sizeOpen) {
        effects2.exit(types.codeFencedFenceSequence);
        return markdownSpace(code5) ? factorySpace(effects2, sequenceCloseAfter, types.whitespace)(code5) : sequenceCloseAfter(code5);
      }
      return nok2(code5);
    }
    function sequenceCloseAfter(code5) {
      if (code5 === codes.eof || markdownLineEnding(code5)) {
        effects2.exit(types.codeFencedFence);
        return ok4(code5);
      }
      return nok2(code5);
    }
  }
}
function tokenizeNonLazyContinuation(effects, ok3, nok) {
  const self2 = this;
  return start;
  function start(code5) {
    if (code5 === codes.eof) {
      return nok(code5);
    }
    ok(markdownLineEnding(code5), "expected eol");
    effects.enter(types.lineEnding);
    effects.consume(code5);
    effects.exit(types.lineEnding);
    return lineStart;
  }
  function lineStart(code5) {
    return self2.parser.lazy[self2.now().line] ? nok(code5) : ok3(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/code-indented.js
var codeIndented = {
  name: "codeIndented",
  tokenize: tokenizeCodeIndented
};
var furtherStart = { partial: true, tokenize: tokenizeFurtherStart };
function tokenizeCodeIndented(effects, ok3, nok) {
  const self2 = this;
  return start;
  function start(code5) {
    ok(markdownSpace(code5));
    effects.enter(types.codeIndented);
    return factorySpace(
      effects,
      afterPrefix,
      types.linePrefix,
      constants.tabSize + 1
    )(code5);
  }
  function afterPrefix(code5) {
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === types.linePrefix && tail[2].sliceSerialize(tail[1], true).length >= constants.tabSize ? atBreak(code5) : nok(code5);
  }
  function atBreak(code5) {
    if (code5 === codes.eof) {
      return after(code5);
    }
    if (markdownLineEnding(code5)) {
      return effects.attempt(furtherStart, atBreak, after)(code5);
    }
    effects.enter(types.codeFlowValue);
    return inside(code5);
  }
  function inside(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.codeFlowValue);
      return atBreak(code5);
    }
    effects.consume(code5);
    return inside;
  }
  function after(code5) {
    effects.exit(types.codeIndented);
    return ok3(code5);
  }
}
function tokenizeFurtherStart(effects, ok3, nok) {
  const self2 = this;
  return furtherStart2;
  function furtherStart2(code5) {
    if (self2.parser.lazy[self2.now().line]) {
      return nok(code5);
    }
    if (markdownLineEnding(code5)) {
      effects.enter(types.lineEnding);
      effects.consume(code5);
      effects.exit(types.lineEnding);
      return furtherStart2;
    }
    return factorySpace(
      effects,
      afterPrefix,
      types.linePrefix,
      constants.tabSize + 1
    )(code5);
  }
  function afterPrefix(code5) {
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === types.linePrefix && tail[2].sliceSerialize(tail[1], true).length >= constants.tabSize ? ok3(code5) : markdownLineEnding(code5) ? furtherStart2(code5) : nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/code-text.js
var codeText = {
  name: "codeText",
  previous: previous2,
  resolve: resolveCodeText,
  tokenize: tokenizeCodeText
};
function resolveCodeText(events) {
  let tailExitIndex = events.length - 4;
  let headEnterIndex = 3;
  let index4;
  let enter2;
  if ((events[headEnterIndex][1].type === types.lineEnding || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === types.lineEnding || events[tailExitIndex][1].type === "space")) {
    index4 = headEnterIndex;
    while (++index4 < tailExitIndex) {
      if (events[index4][1].type === types.codeTextData) {
        events[headEnterIndex][1].type = types.codeTextPadding;
        events[tailExitIndex][1].type = types.codeTextPadding;
        headEnterIndex += 2;
        tailExitIndex -= 2;
        break;
      }
    }
  }
  index4 = headEnterIndex - 1;
  tailExitIndex++;
  while (++index4 <= tailExitIndex) {
    if (enter2 === void 0) {
      if (index4 !== tailExitIndex && events[index4][1].type !== types.lineEnding) {
        enter2 = index4;
      }
    } else if (index4 === tailExitIndex || events[index4][1].type === types.lineEnding) {
      events[enter2][1].type = types.codeTextData;
      if (index4 !== enter2 + 2) {
        events[enter2][1].end = events[index4 - 1][1].end;
        events.splice(enter2 + 2, index4 - enter2 - 2);
        tailExitIndex -= index4 - enter2 - 2;
        index4 = enter2 + 2;
      }
      enter2 = void 0;
    }
  }
  return events;
}
function previous2(code5) {
  return code5 !== codes.graveAccent || this.events[this.events.length - 1][1].type === types.characterEscape;
}
function tokenizeCodeText(effects, ok3, nok) {
  const self2 = this;
  let sizeOpen = 0;
  let size5;
  let token;
  return start;
  function start(code5) {
    ok(code5 === codes.graveAccent, "expected `` ` ``");
    ok(previous2.call(self2, self2.previous), "expected correct previous");
    effects.enter(types.codeText);
    effects.enter(types.codeTextSequence);
    return sequenceOpen(code5);
  }
  function sequenceOpen(code5) {
    if (code5 === codes.graveAccent) {
      effects.consume(code5);
      sizeOpen++;
      return sequenceOpen;
    }
    effects.exit(types.codeTextSequence);
    return between2(code5);
  }
  function between2(code5) {
    if (code5 === codes.eof) {
      return nok(code5);
    }
    if (code5 === codes.space) {
      effects.enter("space");
      effects.consume(code5);
      effects.exit("space");
      return between2;
    }
    if (code5 === codes.graveAccent) {
      token = effects.enter(types.codeTextSequence);
      size5 = 0;
      return sequenceClose(code5);
    }
    if (markdownLineEnding(code5)) {
      effects.enter(types.lineEnding);
      effects.consume(code5);
      effects.exit(types.lineEnding);
      return between2;
    }
    effects.enter(types.codeTextData);
    return data(code5);
  }
  function data(code5) {
    if (code5 === codes.eof || code5 === codes.space || code5 === codes.graveAccent || markdownLineEnding(code5)) {
      effects.exit(types.codeTextData);
      return between2(code5);
    }
    effects.consume(code5);
    return data;
  }
  function sequenceClose(code5) {
    if (code5 === codes.graveAccent) {
      effects.consume(code5);
      size5++;
      return sequenceClose;
    }
    if (size5 === sizeOpen) {
      effects.exit(types.codeTextSequence);
      effects.exit(types.codeText);
      return ok3(code5);
    }
    token.type = types.codeTextData;
    return data(code5);
  }
}

// ../../node_modules/.pnpm/micromark-util-subtokenize@2.1.0/node_modules/micromark-util-subtokenize/dev/lib/splice-buffer.js
var SpliceBuffer = class {
  /**
   * @param {ReadonlyArray<T> | null | undefined} [initial]
   *   Initial items (optional).
   * @returns
   *   Splice buffer.
   */
  constructor(initial) {
    this.left = initial ? [...initial] : [];
    this.right = [];
  }
  /**
   * Array access;
   * does not move the cursor.
   *
   * @param {number} index
   *   Index.
   * @return {T}
   *   Item.
   */
  get(index4) {
    if (index4 < 0 || index4 >= this.left.length + this.right.length) {
      throw new RangeError(
        "Cannot access index `" + index4 + "` in a splice buffer of size `" + (this.left.length + this.right.length) + "`"
      );
    }
    if (index4 < this.left.length) return this.left[index4];
    return this.right[this.right.length - index4 + this.left.length - 1];
  }
  /**
   * The length of the splice buffer, one greater than the largest index in the
   * array.
   */
  get length() {
    return this.left.length + this.right.length;
  }
  /**
   * Remove and return `list[0]`;
   * moves the cursor to `0`.
   *
   * @returns {T | undefined}
   *   Item, optional.
   */
  shift() {
    this.setCursor(0);
    return this.right.pop();
  }
  /**
   * Slice the buffer to get an array;
   * does not move the cursor.
   *
   * @param {number} start
   *   Start.
   * @param {number | null | undefined} [end]
   *   End (optional).
   * @returns {Array<T>}
   *   Array of items.
   */
  slice(start, end) {
    const stop = end === null || end === void 0 ? Number.POSITIVE_INFINITY : end;
    if (stop < this.left.length) {
      return this.left.slice(start, stop);
    }
    if (start > this.left.length) {
      return this.right.slice(
        this.right.length - stop + this.left.length,
        this.right.length - start + this.left.length
      ).reverse();
    }
    return this.left.slice(start).concat(
      this.right.slice(this.right.length - stop + this.left.length).reverse()
    );
  }
  /**
   * Mimics the behavior of Array.prototype.splice() except for the change of
   * interface necessary to avoid segfaults when patching in very large arrays.
   *
   * This operation moves cursor is moved to `start` and results in the cursor
   * placed after any inserted items.
   *
   * @param {number} start
   *   Start;
   *   zero-based index at which to start changing the array;
   *   negative numbers count backwards from the end of the array and values
   *   that are out-of bounds are clamped to the appropriate end of the array.
   * @param {number | null | undefined} [deleteCount=0]
   *   Delete count (default: `0`);
   *   maximum number of elements to delete, starting from start.
   * @param {Array<T> | null | undefined} [items=[]]
   *   Items to include in place of the deleted items (default: `[]`).
   * @return {Array<T>}
   *   Any removed items.
   */
  splice(start, deleteCount, items) {
    const count2 = deleteCount || 0;
    this.setCursor(Math.trunc(start));
    const removed = this.right.splice(
      this.right.length - count2,
      Number.POSITIVE_INFINITY
    );
    if (items) chunkedPush(this.left, items);
    return removed.reverse();
  }
  /**
   * Remove and return the highest-numbered item in the array, so
   * `list[list.length - 1]`;
   * Moves the cursor to `length`.
   *
   * @returns {T | undefined}
   *   Item, optional.
   */
  pop() {
    this.setCursor(Number.POSITIVE_INFINITY);
    return this.left.pop();
  }
  /**
   * Inserts a single item to the high-numbered side of the array;
   * moves the cursor to `length`.
   *
   * @param {T} item
   *   Item.
   * @returns {undefined}
   *   Nothing.
   */
  push(item) {
    this.setCursor(Number.POSITIVE_INFINITY);
    this.left.push(item);
  }
  /**
   * Inserts many items to the high-numbered side of the array.
   * Moves the cursor to `length`.
   *
   * @param {Array<T>} items
   *   Items.
   * @returns {undefined}
   *   Nothing.
   */
  pushMany(items) {
    this.setCursor(Number.POSITIVE_INFINITY);
    chunkedPush(this.left, items);
  }
  /**
   * Inserts a single item to the low-numbered side of the array;
   * Moves the cursor to `0`.
   *
   * @param {T} item
   *   Item.
   * @returns {undefined}
   *   Nothing.
   */
  unshift(item) {
    this.setCursor(0);
    this.right.push(item);
  }
  /**
   * Inserts many items to the low-numbered side of the array;
   * moves the cursor to `0`.
   *
   * @param {Array<T>} items
   *   Items.
   * @returns {undefined}
   *   Nothing.
   */
  unshiftMany(items) {
    this.setCursor(0);
    chunkedPush(this.right, items.reverse());
  }
  /**
   * Move the cursor to a specific position in the array. Requires
   * time proportional to the distance moved.
   *
   * If `n < 0`, the cursor will end up at the beginning.
   * If `n > length`, the cursor will end up at the end.
   *
   * @param {number} n
   *   Position.
   * @return {undefined}
   *   Nothing.
   */
  setCursor(n) {
    if (n === this.left.length || n > this.left.length && this.right.length === 0 || n < 0 && this.left.length === 0)
      return;
    if (n < this.left.length) {
      const removed = this.left.splice(n, Number.POSITIVE_INFINITY);
      chunkedPush(this.right, removed.reverse());
    } else {
      const removed = this.right.splice(
        this.left.length + this.right.length - n,
        Number.POSITIVE_INFINITY
      );
      chunkedPush(this.left, removed.reverse());
    }
  }
};
function chunkedPush(list7, right) {
  let chunkStart = 0;
  if (right.length < constants.v8MaxSafeChunkSize) {
    list7.push(...right);
  } else {
    while (chunkStart < right.length) {
      list7.push(
        ...right.slice(chunkStart, chunkStart + constants.v8MaxSafeChunkSize)
      );
      chunkStart += constants.v8MaxSafeChunkSize;
    }
  }
}

// ../../node_modules/.pnpm/micromark-util-subtokenize@2.1.0/node_modules/micromark-util-subtokenize/dev/index.js
function subtokenize(eventsArray) {
  const jumps = {};
  let index4 = -1;
  let event;
  let lineIndex;
  let otherIndex;
  let otherEvent;
  let parameters;
  let subevents;
  let more;
  const events = new SpliceBuffer(eventsArray);
  while (++index4 < events.length) {
    while (index4 in jumps) {
      index4 = jumps[index4];
    }
    event = events.get(index4);
    if (index4 && event[1].type === types.chunkFlow && events.get(index4 - 1)[1].type === types.listItemPrefix) {
      ok(event[1]._tokenizer, "expected `_tokenizer` on subtokens");
      subevents = event[1]._tokenizer.events;
      otherIndex = 0;
      if (otherIndex < subevents.length && subevents[otherIndex][1].type === types.lineEndingBlank) {
        otherIndex += 2;
      }
      if (otherIndex < subevents.length && subevents[otherIndex][1].type === types.content) {
        while (++otherIndex < subevents.length) {
          if (subevents[otherIndex][1].type === types.content) {
            break;
          }
          if (subevents[otherIndex][1].type === types.chunkText) {
            subevents[otherIndex][1]._isInFirstContentOfListItem = true;
            otherIndex++;
          }
        }
      }
    }
    if (event[0] === "enter") {
      if (event[1].contentType) {
        Object.assign(jumps, subcontent(events, index4));
        index4 = jumps[index4];
        more = true;
      }
    } else if (event[1]._container) {
      otherIndex = index4;
      lineIndex = void 0;
      while (otherIndex--) {
        otherEvent = events.get(otherIndex);
        if (otherEvent[1].type === types.lineEnding || otherEvent[1].type === types.lineEndingBlank) {
          if (otherEvent[0] === "enter") {
            if (lineIndex) {
              events.get(lineIndex)[1].type = types.lineEndingBlank;
            }
            otherEvent[1].type = types.lineEnding;
            lineIndex = otherIndex;
          }
        } else if (otherEvent[1].type === types.linePrefix || otherEvent[1].type === types.listItemIndent) {
        } else {
          break;
        }
      }
      if (lineIndex) {
        event[1].end = { ...events.get(lineIndex)[1].start };
        parameters = events.slice(lineIndex, index4);
        parameters.unshift(event);
        events.splice(lineIndex, index4 - lineIndex + 1, parameters);
      }
    }
  }
  splice(eventsArray, 0, Number.POSITIVE_INFINITY, events.slice(0));
  return !more;
}
function subcontent(events, eventIndex) {
  const token = events.get(eventIndex)[1];
  const context = events.get(eventIndex)[2];
  let startPosition = eventIndex - 1;
  const startPositions = [];
  ok(token.contentType, "expected `contentType` on subtokens");
  let tokenizer = token._tokenizer;
  if (!tokenizer) {
    tokenizer = context.parser[token.contentType](token.start);
    if (token._contentTypeTextTrailing) {
      tokenizer._contentTypeTextTrailing = true;
    }
  }
  const childEvents = tokenizer.events;
  const jumps = [];
  const gaps = {};
  let stream;
  let previous3;
  let index4 = -1;
  let current = token;
  let adjust = 0;
  let start = 0;
  const breaks = [start];
  while (current) {
    while (events.get(++startPosition)[1] !== current) {
    }
    ok(
      !previous3 || current.previous === previous3,
      "expected previous to match"
    );
    ok(!previous3 || previous3.next === current, "expected next to match");
    startPositions.push(startPosition);
    if (!current._tokenizer) {
      stream = context.sliceStream(current);
      if (!current.next) {
        stream.push(codes.eof);
      }
      if (previous3) {
        tokenizer.defineSkip(current.start);
      }
      if (current._isInFirstContentOfListItem) {
        tokenizer._gfmTasklistFirstContentOfListItem = true;
      }
      tokenizer.write(stream);
      if (current._isInFirstContentOfListItem) {
        tokenizer._gfmTasklistFirstContentOfListItem = void 0;
      }
    }
    previous3 = current;
    current = current.next;
  }
  current = token;
  while (++index4 < childEvents.length) {
    if (
      // Find a void token that includes a break.
      childEvents[index4][0] === "exit" && childEvents[index4 - 1][0] === "enter" && childEvents[index4][1].type === childEvents[index4 - 1][1].type && childEvents[index4][1].start.line !== childEvents[index4][1].end.line
    ) {
      ok(current, "expected a current token");
      start = index4 + 1;
      breaks.push(start);
      current._tokenizer = void 0;
      current.previous = void 0;
      current = current.next;
    }
  }
  tokenizer.events = [];
  if (current) {
    current._tokenizer = void 0;
    current.previous = void 0;
    ok(!current.next, "expected no next token");
  } else {
    breaks.pop();
  }
  index4 = breaks.length;
  while (index4--) {
    const slice2 = childEvents.slice(breaks[index4], breaks[index4 + 1]);
    const start2 = startPositions.pop();
    ok(start2 !== void 0, "expected a start position when splicing");
    jumps.push([start2, start2 + slice2.length - 1]);
    events.splice(start2, 2, slice2);
  }
  jumps.reverse();
  index4 = -1;
  while (++index4 < jumps.length) {
    gaps[adjust + jumps[index4][0]] = adjust + jumps[index4][1];
    adjust += jumps[index4][1] - jumps[index4][0] - 1;
  }
  return gaps;
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/content.js
var content3 = { resolve: resolveContent, tokenize: tokenizeContent };
var continuationConstruct = { partial: true, tokenize: tokenizeContinuation };
function resolveContent(events) {
  subtokenize(events);
  return events;
}
function tokenizeContent(effects, ok3) {
  let previous3;
  return chunkStart;
  function chunkStart(code5) {
    ok(
      code5 !== codes.eof && !markdownLineEnding(code5),
      "expected no eof or eol"
    );
    effects.enter(types.content);
    previous3 = effects.enter(types.chunkContent, {
      contentType: constants.contentTypeContent
    });
    return chunkInside(code5);
  }
  function chunkInside(code5) {
    if (code5 === codes.eof) {
      return contentEnd(code5);
    }
    if (markdownLineEnding(code5)) {
      return effects.check(
        continuationConstruct,
        contentContinue,
        contentEnd
      )(code5);
    }
    effects.consume(code5);
    return chunkInside;
  }
  function contentEnd(code5) {
    effects.exit(types.chunkContent);
    effects.exit(types.content);
    return ok3(code5);
  }
  function contentContinue(code5) {
    ok(markdownLineEnding(code5), "expected eol");
    effects.consume(code5);
    effects.exit(types.chunkContent);
    ok(previous3, "expected previous token");
    previous3.next = effects.enter(types.chunkContent, {
      contentType: constants.contentTypeContent,
      previous: previous3
    });
    previous3 = previous3.next;
    return chunkInside;
  }
}
function tokenizeContinuation(effects, ok3, nok) {
  const self2 = this;
  return startLookahead;
  function startLookahead(code5) {
    ok(markdownLineEnding(code5), "expected a line ending");
    effects.exit(types.chunkContent);
    effects.enter(types.lineEnding);
    effects.consume(code5);
    effects.exit(types.lineEnding);
    return factorySpace(effects, prefixed, types.linePrefix);
  }
  function prefixed(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      return nok(code5);
    }
    ok(
      self2.parser.constructs.disable.null,
      "expected `disable.null` to be populated"
    );
    const tail = self2.events[self2.events.length - 1];
    if (!self2.parser.constructs.disable.null.includes("codeIndented") && tail && tail[1].type === types.linePrefix && tail[2].sliceSerialize(tail[1], true).length >= constants.tabSize) {
      return ok3(code5);
    }
    return effects.interrupt(self2.parser.constructs.flow, nok, ok3)(code5);
  }
}

// ../../node_modules/.pnpm/micromark-factory-destination@2.0.1/node_modules/micromark-factory-destination/dev/index.js
function factoryDestination(effects, ok3, nok, type, literalType, literalMarkerType, rawType, stringType, max3) {
  const limit = max3 || Number.POSITIVE_INFINITY;
  let balance = 0;
  return start;
  function start(code5) {
    if (code5 === codes.lessThan) {
      effects.enter(type);
      effects.enter(literalType);
      effects.enter(literalMarkerType);
      effects.consume(code5);
      effects.exit(literalMarkerType);
      return enclosedBefore;
    }
    if (code5 === codes.eof || code5 === codes.space || code5 === codes.rightParenthesis || asciiControl(code5)) {
      return nok(code5);
    }
    effects.enter(type);
    effects.enter(rawType);
    effects.enter(stringType);
    effects.enter(types.chunkString, { contentType: constants.contentTypeString });
    return raw2(code5);
  }
  function enclosedBefore(code5) {
    if (code5 === codes.greaterThan) {
      effects.enter(literalMarkerType);
      effects.consume(code5);
      effects.exit(literalMarkerType);
      effects.exit(literalType);
      effects.exit(type);
      return ok3;
    }
    effects.enter(stringType);
    effects.enter(types.chunkString, { contentType: constants.contentTypeString });
    return enclosed(code5);
  }
  function enclosed(code5) {
    if (code5 === codes.greaterThan) {
      effects.exit(types.chunkString);
      effects.exit(stringType);
      return enclosedBefore(code5);
    }
    if (code5 === codes.eof || code5 === codes.lessThan || markdownLineEnding(code5)) {
      return nok(code5);
    }
    effects.consume(code5);
    return code5 === codes.backslash ? enclosedEscape : enclosed;
  }
  function enclosedEscape(code5) {
    if (code5 === codes.lessThan || code5 === codes.greaterThan || code5 === codes.backslash) {
      effects.consume(code5);
      return enclosed;
    }
    return enclosed(code5);
  }
  function raw2(code5) {
    if (!balance && (code5 === codes.eof || code5 === codes.rightParenthesis || markdownLineEndingOrSpace(code5))) {
      effects.exit(types.chunkString);
      effects.exit(stringType);
      effects.exit(rawType);
      effects.exit(type);
      return ok3(code5);
    }
    if (balance < limit && code5 === codes.leftParenthesis) {
      effects.consume(code5);
      balance++;
      return raw2;
    }
    if (code5 === codes.rightParenthesis) {
      effects.consume(code5);
      balance--;
      return raw2;
    }
    if (code5 === codes.eof || code5 === codes.space || code5 === codes.leftParenthesis || asciiControl(code5)) {
      return nok(code5);
    }
    effects.consume(code5);
    return code5 === codes.backslash ? rawEscape : raw2;
  }
  function rawEscape(code5) {
    if (code5 === codes.leftParenthesis || code5 === codes.rightParenthesis || code5 === codes.backslash) {
      effects.consume(code5);
      return raw2;
    }
    return raw2(code5);
  }
}

// ../../node_modules/.pnpm/micromark-factory-label@2.0.1/node_modules/micromark-factory-label/dev/index.js
function factoryLabel(effects, ok3, nok, type, markerType, stringType) {
  const self2 = this;
  let size5 = 0;
  let seen;
  return start;
  function start(code5) {
    ok(code5 === codes.leftSquareBracket, "expected `[`");
    effects.enter(type);
    effects.enter(markerType);
    effects.consume(code5);
    effects.exit(markerType);
    effects.enter(stringType);
    return atBreak;
  }
  function atBreak(code5) {
    if (size5 > constants.linkReferenceSizeMax || code5 === codes.eof || code5 === codes.leftSquareBracket || code5 === codes.rightSquareBracket && !seen || // To do: remove in the future once we’ve switched from
    // `micromark-extension-footnote` to `micromark-extension-gfm-footnote`,
    // which doesn’t need this.
    // Hidden footnotes hook.
    /* c8 ignore next 3 */
    code5 === codes.caret && !size5 && "_hiddenFootnoteSupport" in self2.parser.constructs) {
      return nok(code5);
    }
    if (code5 === codes.rightSquareBracket) {
      effects.exit(stringType);
      effects.enter(markerType);
      effects.consume(code5);
      effects.exit(markerType);
      effects.exit(type);
      return ok3;
    }
    if (markdownLineEnding(code5)) {
      effects.enter(types.lineEnding);
      effects.consume(code5);
      effects.exit(types.lineEnding);
      return atBreak;
    }
    effects.enter(types.chunkString, { contentType: constants.contentTypeString });
    return labelInside(code5);
  }
  function labelInside(code5) {
    if (code5 === codes.eof || code5 === codes.leftSquareBracket || code5 === codes.rightSquareBracket || markdownLineEnding(code5) || size5++ > constants.linkReferenceSizeMax) {
      effects.exit(types.chunkString);
      return atBreak(code5);
    }
    effects.consume(code5);
    if (!seen) seen = !markdownSpace(code5);
    return code5 === codes.backslash ? labelEscape : labelInside;
  }
  function labelEscape(code5) {
    if (code5 === codes.leftSquareBracket || code5 === codes.backslash || code5 === codes.rightSquareBracket) {
      effects.consume(code5);
      size5++;
      return labelInside;
    }
    return labelInside(code5);
  }
}

// ../../node_modules/.pnpm/micromark-factory-title@2.0.1/node_modules/micromark-factory-title/dev/index.js
function factoryTitle(effects, ok3, nok, type, markerType, stringType) {
  let marker;
  return start;
  function start(code5) {
    if (code5 === codes.quotationMark || code5 === codes.apostrophe || code5 === codes.leftParenthesis) {
      effects.enter(type);
      effects.enter(markerType);
      effects.consume(code5);
      effects.exit(markerType);
      marker = code5 === codes.leftParenthesis ? codes.rightParenthesis : code5;
      return begin;
    }
    return nok(code5);
  }
  function begin(code5) {
    if (code5 === marker) {
      effects.enter(markerType);
      effects.consume(code5);
      effects.exit(markerType);
      effects.exit(type);
      return ok3;
    }
    effects.enter(stringType);
    return atBreak(code5);
  }
  function atBreak(code5) {
    if (code5 === marker) {
      effects.exit(stringType);
      return begin(marker);
    }
    if (code5 === codes.eof) {
      return nok(code5);
    }
    if (markdownLineEnding(code5)) {
      effects.enter(types.lineEnding);
      effects.consume(code5);
      effects.exit(types.lineEnding);
      return factorySpace(effects, atBreak, types.linePrefix);
    }
    effects.enter(types.chunkString, { contentType: constants.contentTypeString });
    return inside(code5);
  }
  function inside(code5) {
    if (code5 === marker || code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.chunkString);
      return atBreak(code5);
    }
    effects.consume(code5);
    return code5 === codes.backslash ? escape2 : inside;
  }
  function escape2(code5) {
    if (code5 === marker || code5 === codes.backslash) {
      effects.consume(code5);
      return inside;
    }
    return inside(code5);
  }
}

// ../../node_modules/.pnpm/micromark-factory-whitespace@2.0.1/node_modules/micromark-factory-whitespace/dev/index.js
function factoryWhitespace(effects, ok3) {
  let seen;
  return start;
  function start(code5) {
    if (markdownLineEnding(code5)) {
      effects.enter(types.lineEnding);
      effects.consume(code5);
      effects.exit(types.lineEnding);
      seen = true;
      return start;
    }
    if (markdownSpace(code5)) {
      return factorySpace(
        effects,
        start,
        seen ? types.linePrefix : types.lineSuffix
      )(code5);
    }
    return ok3(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/definition.js
var definition2 = { name: "definition", tokenize: tokenizeDefinition };
var titleBefore = { partial: true, tokenize: tokenizeTitleBefore };
function tokenizeDefinition(effects, ok3, nok) {
  const self2 = this;
  let identifier;
  return start;
  function start(code5) {
    effects.enter(types.definition);
    return before(code5);
  }
  function before(code5) {
    ok(code5 === codes.leftSquareBracket, "expected `[`");
    return factoryLabel.call(
      self2,
      effects,
      labelAfter,
      // Note: we don’t need to reset the way `markdown-rs` does.
      nok,
      types.definitionLabel,
      types.definitionLabelMarker,
      types.definitionLabelString
    )(code5);
  }
  function labelAfter(code5) {
    identifier = normalizeIdentifier(
      self2.sliceSerialize(self2.events[self2.events.length - 1][1]).slice(1, -1)
    );
    if (code5 === codes.colon) {
      effects.enter(types.definitionMarker);
      effects.consume(code5);
      effects.exit(types.definitionMarker);
      return markerAfter;
    }
    return nok(code5);
  }
  function markerAfter(code5) {
    return markdownLineEndingOrSpace(code5) ? factoryWhitespace(effects, destinationBefore)(code5) : destinationBefore(code5);
  }
  function destinationBefore(code5) {
    return factoryDestination(
      effects,
      destinationAfter,
      // Note: we don’t need to reset the way `markdown-rs` does.
      nok,
      types.definitionDestination,
      types.definitionDestinationLiteral,
      types.definitionDestinationLiteralMarker,
      types.definitionDestinationRaw,
      types.definitionDestinationString
    )(code5);
  }
  function destinationAfter(code5) {
    return effects.attempt(titleBefore, after, after)(code5);
  }
  function after(code5) {
    return markdownSpace(code5) ? factorySpace(effects, afterWhitespace, types.whitespace)(code5) : afterWhitespace(code5);
  }
  function afterWhitespace(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.definition);
      self2.parser.defined.push(identifier);
      return ok3(code5);
    }
    return nok(code5);
  }
}
function tokenizeTitleBefore(effects, ok3, nok) {
  return titleBefore2;
  function titleBefore2(code5) {
    return markdownLineEndingOrSpace(code5) ? factoryWhitespace(effects, beforeMarker)(code5) : nok(code5);
  }
  function beforeMarker(code5) {
    return factoryTitle(
      effects,
      titleAfter,
      nok,
      types.definitionTitle,
      types.definitionTitleMarker,
      types.definitionTitleString
    )(code5);
  }
  function titleAfter(code5) {
    return markdownSpace(code5) ? factorySpace(
      effects,
      titleAfterOptionalWhitespace,
      types.whitespace
    )(code5) : titleAfterOptionalWhitespace(code5);
  }
  function titleAfterOptionalWhitespace(code5) {
    return code5 === codes.eof || markdownLineEnding(code5) ? ok3(code5) : nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/hard-break-escape.js
var hardBreakEscape = {
  name: "hardBreakEscape",
  tokenize: tokenizeHardBreakEscape
};
function tokenizeHardBreakEscape(effects, ok3, nok) {
  return start;
  function start(code5) {
    ok(code5 === codes.backslash, "expected `\\`");
    effects.enter(types.hardBreakEscape);
    effects.consume(code5);
    return after;
  }
  function after(code5) {
    if (markdownLineEnding(code5)) {
      effects.exit(types.hardBreakEscape);
      return ok3(code5);
    }
    return nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/heading-atx.js
var headingAtx = {
  name: "headingAtx",
  resolve: resolveHeadingAtx,
  tokenize: tokenizeHeadingAtx
};
function resolveHeadingAtx(events, context) {
  let contentEnd = events.length - 2;
  let contentStart = 3;
  let content5;
  let text10;
  if (events[contentStart][1].type === types.whitespace) {
    contentStart += 2;
  }
  if (contentEnd - 2 > contentStart && events[contentEnd][1].type === types.whitespace) {
    contentEnd -= 2;
  }
  if (events[contentEnd][1].type === types.atxHeadingSequence && (contentStart === contentEnd - 1 || contentEnd - 4 > contentStart && events[contentEnd - 2][1].type === types.whitespace)) {
    contentEnd -= contentStart + 1 === contentEnd ? 2 : 4;
  }
  if (contentEnd > contentStart) {
    content5 = {
      type: types.atxHeadingText,
      start: events[contentStart][1].start,
      end: events[contentEnd][1].end
    };
    text10 = {
      type: types.chunkText,
      start: events[contentStart][1].start,
      end: events[contentEnd][1].end,
      contentType: constants.contentTypeText
    };
    splice(events, contentStart, contentEnd - contentStart + 1, [
      ["enter", content5, context],
      ["enter", text10, context],
      ["exit", text10, context],
      ["exit", content5, context]
    ]);
  }
  return events;
}
function tokenizeHeadingAtx(effects, ok3, nok) {
  let size5 = 0;
  return start;
  function start(code5) {
    effects.enter(types.atxHeading);
    return before(code5);
  }
  function before(code5) {
    ok(code5 === codes.numberSign, "expected `#`");
    effects.enter(types.atxHeadingSequence);
    return sequenceOpen(code5);
  }
  function sequenceOpen(code5) {
    if (code5 === codes.numberSign && size5++ < constants.atxHeadingOpeningFenceSizeMax) {
      effects.consume(code5);
      return sequenceOpen;
    }
    if (code5 === codes.eof || markdownLineEndingOrSpace(code5)) {
      effects.exit(types.atxHeadingSequence);
      return atBreak(code5);
    }
    return nok(code5);
  }
  function atBreak(code5) {
    if (code5 === codes.numberSign) {
      effects.enter(types.atxHeadingSequence);
      return sequenceFurther(code5);
    }
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.atxHeading);
      return ok3(code5);
    }
    if (markdownSpace(code5)) {
      return factorySpace(effects, atBreak, types.whitespace)(code5);
    }
    effects.enter(types.atxHeadingText);
    return data(code5);
  }
  function sequenceFurther(code5) {
    if (code5 === codes.numberSign) {
      effects.consume(code5);
      return sequenceFurther;
    }
    effects.exit(types.atxHeadingSequence);
    return atBreak(code5);
  }
  function data(code5) {
    if (code5 === codes.eof || code5 === codes.numberSign || markdownLineEndingOrSpace(code5)) {
      effects.exit(types.atxHeadingText);
      return atBreak(code5);
    }
    effects.consume(code5);
    return data;
  }
}

// ../../node_modules/.pnpm/micromark-util-html-tag-name@2.0.1/node_modules/micromark-util-html-tag-name/index.js
var htmlBlockNames = [
  "address",
  "article",
  "aside",
  "base",
  "basefont",
  "blockquote",
  "body",
  "caption",
  "center",
  "col",
  "colgroup",
  "dd",
  "details",
  "dialog",
  "dir",
  "div",
  "dl",
  "dt",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "frame",
  "frameset",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "head",
  "header",
  "hr",
  "html",
  "iframe",
  "legend",
  "li",
  "link",
  "main",
  "menu",
  "menuitem",
  "nav",
  "noframes",
  "ol",
  "optgroup",
  "option",
  "p",
  "param",
  "search",
  "section",
  "summary",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "title",
  "tr",
  "track",
  "ul"
];
var htmlRawNames = ["pre", "script", "style", "textarea"];

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/html-flow.js
var htmlFlow = {
  concrete: true,
  name: "htmlFlow",
  resolveTo: resolveToHtmlFlow,
  tokenize: tokenizeHtmlFlow
};
var blankLineBefore = { partial: true, tokenize: tokenizeBlankLineBefore };
var nonLazyContinuationStart = {
  partial: true,
  tokenize: tokenizeNonLazyContinuationStart
};
function resolveToHtmlFlow(events) {
  let index4 = events.length;
  while (index4--) {
    if (events[index4][0] === "enter" && events[index4][1].type === types.htmlFlow) {
      break;
    }
  }
  if (index4 > 1 && events[index4 - 2][1].type === types.linePrefix) {
    events[index4][1].start = events[index4 - 2][1].start;
    events[index4 + 1][1].start = events[index4 - 2][1].start;
    events.splice(index4 - 2, 2);
  }
  return events;
}
function tokenizeHtmlFlow(effects, ok3, nok) {
  const self2 = this;
  let marker;
  let closingTag;
  let buffer;
  let index4;
  let markerB;
  return start;
  function start(code5) {
    return before(code5);
  }
  function before(code5) {
    ok(code5 === codes.lessThan, "expected `<`");
    effects.enter(types.htmlFlow);
    effects.enter(types.htmlFlowData);
    effects.consume(code5);
    return open;
  }
  function open(code5) {
    if (code5 === codes.exclamationMark) {
      effects.consume(code5);
      return declarationOpen;
    }
    if (code5 === codes.slash) {
      effects.consume(code5);
      closingTag = true;
      return tagCloseStart;
    }
    if (code5 === codes.questionMark) {
      effects.consume(code5);
      marker = constants.htmlInstruction;
      return self2.interrupt ? ok3 : continuationDeclarationInside;
    }
    if (asciiAlpha(code5)) {
      ok(code5 !== null);
      effects.consume(code5);
      buffer = String.fromCharCode(code5);
      return tagName;
    }
    return nok(code5);
  }
  function declarationOpen(code5) {
    if (code5 === codes.dash) {
      effects.consume(code5);
      marker = constants.htmlComment;
      return commentOpenInside;
    }
    if (code5 === codes.leftSquareBracket) {
      effects.consume(code5);
      marker = constants.htmlCdata;
      index4 = 0;
      return cdataOpenInside;
    }
    if (asciiAlpha(code5)) {
      effects.consume(code5);
      marker = constants.htmlDeclaration;
      return self2.interrupt ? ok3 : continuationDeclarationInside;
    }
    return nok(code5);
  }
  function commentOpenInside(code5) {
    if (code5 === codes.dash) {
      effects.consume(code5);
      return self2.interrupt ? ok3 : continuationDeclarationInside;
    }
    return nok(code5);
  }
  function cdataOpenInside(code5) {
    const value = constants.cdataOpeningString;
    if (code5 === value.charCodeAt(index4++)) {
      effects.consume(code5);
      if (index4 === value.length) {
        return self2.interrupt ? ok3 : continuation;
      }
      return cdataOpenInside;
    }
    return nok(code5);
  }
  function tagCloseStart(code5) {
    if (asciiAlpha(code5)) {
      ok(code5 !== null);
      effects.consume(code5);
      buffer = String.fromCharCode(code5);
      return tagName;
    }
    return nok(code5);
  }
  function tagName(code5) {
    if (code5 === codes.eof || code5 === codes.slash || code5 === codes.greaterThan || markdownLineEndingOrSpace(code5)) {
      const slash = code5 === codes.slash;
      const name = buffer.toLowerCase();
      if (!slash && !closingTag && htmlRawNames.includes(name)) {
        marker = constants.htmlRaw;
        return self2.interrupt ? ok3(code5) : continuation(code5);
      }
      if (htmlBlockNames.includes(buffer.toLowerCase())) {
        marker = constants.htmlBasic;
        if (slash) {
          effects.consume(code5);
          return basicSelfClosing;
        }
        return self2.interrupt ? ok3(code5) : continuation(code5);
      }
      marker = constants.htmlComplete;
      return self2.interrupt && !self2.parser.lazy[self2.now().line] ? nok(code5) : closingTag ? completeClosingTagAfter(code5) : completeAttributeNameBefore(code5);
    }
    if (code5 === codes.dash || asciiAlphanumeric(code5)) {
      effects.consume(code5);
      buffer += String.fromCharCode(code5);
      return tagName;
    }
    return nok(code5);
  }
  function basicSelfClosing(code5) {
    if (code5 === codes.greaterThan) {
      effects.consume(code5);
      return self2.interrupt ? ok3 : continuation;
    }
    return nok(code5);
  }
  function completeClosingTagAfter(code5) {
    if (markdownSpace(code5)) {
      effects.consume(code5);
      return completeClosingTagAfter;
    }
    return completeEnd(code5);
  }
  function completeAttributeNameBefore(code5) {
    if (code5 === codes.slash) {
      effects.consume(code5);
      return completeEnd;
    }
    if (code5 === codes.colon || code5 === codes.underscore || asciiAlpha(code5)) {
      effects.consume(code5);
      return completeAttributeName;
    }
    if (markdownSpace(code5)) {
      effects.consume(code5);
      return completeAttributeNameBefore;
    }
    return completeEnd(code5);
  }
  function completeAttributeName(code5) {
    if (code5 === codes.dash || code5 === codes.dot || code5 === codes.colon || code5 === codes.underscore || asciiAlphanumeric(code5)) {
      effects.consume(code5);
      return completeAttributeName;
    }
    return completeAttributeNameAfter(code5);
  }
  function completeAttributeNameAfter(code5) {
    if (code5 === codes.equalsTo) {
      effects.consume(code5);
      return completeAttributeValueBefore;
    }
    if (markdownSpace(code5)) {
      effects.consume(code5);
      return completeAttributeNameAfter;
    }
    return completeAttributeNameBefore(code5);
  }
  function completeAttributeValueBefore(code5) {
    if (code5 === codes.eof || code5 === codes.lessThan || code5 === codes.equalsTo || code5 === codes.greaterThan || code5 === codes.graveAccent) {
      return nok(code5);
    }
    if (code5 === codes.quotationMark || code5 === codes.apostrophe) {
      effects.consume(code5);
      markerB = code5;
      return completeAttributeValueQuoted;
    }
    if (markdownSpace(code5)) {
      effects.consume(code5);
      return completeAttributeValueBefore;
    }
    return completeAttributeValueUnquoted(code5);
  }
  function completeAttributeValueQuoted(code5) {
    if (code5 === markerB) {
      effects.consume(code5);
      markerB = null;
      return completeAttributeValueQuotedAfter;
    }
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      return nok(code5);
    }
    effects.consume(code5);
    return completeAttributeValueQuoted;
  }
  function completeAttributeValueUnquoted(code5) {
    if (code5 === codes.eof || code5 === codes.quotationMark || code5 === codes.apostrophe || code5 === codes.slash || code5 === codes.lessThan || code5 === codes.equalsTo || code5 === codes.greaterThan || code5 === codes.graveAccent || markdownLineEndingOrSpace(code5)) {
      return completeAttributeNameAfter(code5);
    }
    effects.consume(code5);
    return completeAttributeValueUnquoted;
  }
  function completeAttributeValueQuotedAfter(code5) {
    if (code5 === codes.slash || code5 === codes.greaterThan || markdownSpace(code5)) {
      return completeAttributeNameBefore(code5);
    }
    return nok(code5);
  }
  function completeEnd(code5) {
    if (code5 === codes.greaterThan) {
      effects.consume(code5);
      return completeAfter;
    }
    return nok(code5);
  }
  function completeAfter(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      return continuation(code5);
    }
    if (markdownSpace(code5)) {
      effects.consume(code5);
      return completeAfter;
    }
    return nok(code5);
  }
  function continuation(code5) {
    if (code5 === codes.dash && marker === constants.htmlComment) {
      effects.consume(code5);
      return continuationCommentInside;
    }
    if (code5 === codes.lessThan && marker === constants.htmlRaw) {
      effects.consume(code5);
      return continuationRawTagOpen;
    }
    if (code5 === codes.greaterThan && marker === constants.htmlDeclaration) {
      effects.consume(code5);
      return continuationClose;
    }
    if (code5 === codes.questionMark && marker === constants.htmlInstruction) {
      effects.consume(code5);
      return continuationDeclarationInside;
    }
    if (code5 === codes.rightSquareBracket && marker === constants.htmlCdata) {
      effects.consume(code5);
      return continuationCdataInside;
    }
    if (markdownLineEnding(code5) && (marker === constants.htmlBasic || marker === constants.htmlComplete)) {
      effects.exit(types.htmlFlowData);
      return effects.check(
        blankLineBefore,
        continuationAfter,
        continuationStart
      )(code5);
    }
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.htmlFlowData);
      return continuationStart(code5);
    }
    effects.consume(code5);
    return continuation;
  }
  function continuationStart(code5) {
    return effects.check(
      nonLazyContinuationStart,
      continuationStartNonLazy,
      continuationAfter
    )(code5);
  }
  function continuationStartNonLazy(code5) {
    ok(markdownLineEnding(code5));
    effects.enter(types.lineEnding);
    effects.consume(code5);
    effects.exit(types.lineEnding);
    return continuationBefore;
  }
  function continuationBefore(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      return continuationStart(code5);
    }
    effects.enter(types.htmlFlowData);
    return continuation(code5);
  }
  function continuationCommentInside(code5) {
    if (code5 === codes.dash) {
      effects.consume(code5);
      return continuationDeclarationInside;
    }
    return continuation(code5);
  }
  function continuationRawTagOpen(code5) {
    if (code5 === codes.slash) {
      effects.consume(code5);
      buffer = "";
      return continuationRawEndTag;
    }
    return continuation(code5);
  }
  function continuationRawEndTag(code5) {
    if (code5 === codes.greaterThan) {
      const name = buffer.toLowerCase();
      if (htmlRawNames.includes(name)) {
        effects.consume(code5);
        return continuationClose;
      }
      return continuation(code5);
    }
    if (asciiAlpha(code5) && buffer.length < constants.htmlRawSizeMax) {
      ok(code5 !== null);
      effects.consume(code5);
      buffer += String.fromCharCode(code5);
      return continuationRawEndTag;
    }
    return continuation(code5);
  }
  function continuationCdataInside(code5) {
    if (code5 === codes.rightSquareBracket) {
      effects.consume(code5);
      return continuationDeclarationInside;
    }
    return continuation(code5);
  }
  function continuationDeclarationInside(code5) {
    if (code5 === codes.greaterThan) {
      effects.consume(code5);
      return continuationClose;
    }
    if (code5 === codes.dash && marker === constants.htmlComment) {
      effects.consume(code5);
      return continuationDeclarationInside;
    }
    return continuation(code5);
  }
  function continuationClose(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.htmlFlowData);
      return continuationAfter(code5);
    }
    effects.consume(code5);
    return continuationClose;
  }
  function continuationAfter(code5) {
    effects.exit(types.htmlFlow);
    return ok3(code5);
  }
}
function tokenizeNonLazyContinuationStart(effects, ok3, nok) {
  const self2 = this;
  return start;
  function start(code5) {
    if (markdownLineEnding(code5)) {
      effects.enter(types.lineEnding);
      effects.consume(code5);
      effects.exit(types.lineEnding);
      return after;
    }
    return nok(code5);
  }
  function after(code5) {
    return self2.parser.lazy[self2.now().line] ? nok(code5) : ok3(code5);
  }
}
function tokenizeBlankLineBefore(effects, ok3, nok) {
  return start;
  function start(code5) {
    ok(markdownLineEnding(code5), "expected a line ending");
    effects.enter(types.lineEnding);
    effects.consume(code5);
    effects.exit(types.lineEnding);
    return effects.attempt(blankLine, ok3, nok);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/html-text.js
var htmlText = { name: "htmlText", tokenize: tokenizeHtmlText };
function tokenizeHtmlText(effects, ok3, nok) {
  const self2 = this;
  let marker;
  let index4;
  let returnState;
  return start;
  function start(code5) {
    ok(code5 === codes.lessThan, "expected `<`");
    effects.enter(types.htmlText);
    effects.enter(types.htmlTextData);
    effects.consume(code5);
    return open;
  }
  function open(code5) {
    if (code5 === codes.exclamationMark) {
      effects.consume(code5);
      return declarationOpen;
    }
    if (code5 === codes.slash) {
      effects.consume(code5);
      return tagCloseStart;
    }
    if (code5 === codes.questionMark) {
      effects.consume(code5);
      return instruction;
    }
    if (asciiAlpha(code5)) {
      effects.consume(code5);
      return tagOpen;
    }
    return nok(code5);
  }
  function declarationOpen(code5) {
    if (code5 === codes.dash) {
      effects.consume(code5);
      return commentOpenInside;
    }
    if (code5 === codes.leftSquareBracket) {
      effects.consume(code5);
      index4 = 0;
      return cdataOpenInside;
    }
    if (asciiAlpha(code5)) {
      effects.consume(code5);
      return declaration;
    }
    return nok(code5);
  }
  function commentOpenInside(code5) {
    if (code5 === codes.dash) {
      effects.consume(code5);
      return commentEnd;
    }
    return nok(code5);
  }
  function comment4(code5) {
    if (code5 === codes.eof) {
      return nok(code5);
    }
    if (code5 === codes.dash) {
      effects.consume(code5);
      return commentClose;
    }
    if (markdownLineEnding(code5)) {
      returnState = comment4;
      return lineEndingBefore(code5);
    }
    effects.consume(code5);
    return comment4;
  }
  function commentClose(code5) {
    if (code5 === codes.dash) {
      effects.consume(code5);
      return commentEnd;
    }
    return comment4(code5);
  }
  function commentEnd(code5) {
    return code5 === codes.greaterThan ? end(code5) : code5 === codes.dash ? commentClose(code5) : comment4(code5);
  }
  function cdataOpenInside(code5) {
    const value = constants.cdataOpeningString;
    if (code5 === value.charCodeAt(index4++)) {
      effects.consume(code5);
      return index4 === value.length ? cdata : cdataOpenInside;
    }
    return nok(code5);
  }
  function cdata(code5) {
    if (code5 === codes.eof) {
      return nok(code5);
    }
    if (code5 === codes.rightSquareBracket) {
      effects.consume(code5);
      return cdataClose;
    }
    if (markdownLineEnding(code5)) {
      returnState = cdata;
      return lineEndingBefore(code5);
    }
    effects.consume(code5);
    return cdata;
  }
  function cdataClose(code5) {
    if (code5 === codes.rightSquareBracket) {
      effects.consume(code5);
      return cdataEnd;
    }
    return cdata(code5);
  }
  function cdataEnd(code5) {
    if (code5 === codes.greaterThan) {
      return end(code5);
    }
    if (code5 === codes.rightSquareBracket) {
      effects.consume(code5);
      return cdataEnd;
    }
    return cdata(code5);
  }
  function declaration(code5) {
    if (code5 === codes.eof || code5 === codes.greaterThan) {
      return end(code5);
    }
    if (markdownLineEnding(code5)) {
      returnState = declaration;
      return lineEndingBefore(code5);
    }
    effects.consume(code5);
    return declaration;
  }
  function instruction(code5) {
    if (code5 === codes.eof) {
      return nok(code5);
    }
    if (code5 === codes.questionMark) {
      effects.consume(code5);
      return instructionClose;
    }
    if (markdownLineEnding(code5)) {
      returnState = instruction;
      return lineEndingBefore(code5);
    }
    effects.consume(code5);
    return instruction;
  }
  function instructionClose(code5) {
    return code5 === codes.greaterThan ? end(code5) : instruction(code5);
  }
  function tagCloseStart(code5) {
    if (asciiAlpha(code5)) {
      effects.consume(code5);
      return tagClose;
    }
    return nok(code5);
  }
  function tagClose(code5) {
    if (code5 === codes.dash || asciiAlphanumeric(code5)) {
      effects.consume(code5);
      return tagClose;
    }
    return tagCloseBetween(code5);
  }
  function tagCloseBetween(code5) {
    if (markdownLineEnding(code5)) {
      returnState = tagCloseBetween;
      return lineEndingBefore(code5);
    }
    if (markdownSpace(code5)) {
      effects.consume(code5);
      return tagCloseBetween;
    }
    return end(code5);
  }
  function tagOpen(code5) {
    if (code5 === codes.dash || asciiAlphanumeric(code5)) {
      effects.consume(code5);
      return tagOpen;
    }
    if (code5 === codes.slash || code5 === codes.greaterThan || markdownLineEndingOrSpace(code5)) {
      return tagOpenBetween(code5);
    }
    return nok(code5);
  }
  function tagOpenBetween(code5) {
    if (code5 === codes.slash) {
      effects.consume(code5);
      return end;
    }
    if (code5 === codes.colon || code5 === codes.underscore || asciiAlpha(code5)) {
      effects.consume(code5);
      return tagOpenAttributeName;
    }
    if (markdownLineEnding(code5)) {
      returnState = tagOpenBetween;
      return lineEndingBefore(code5);
    }
    if (markdownSpace(code5)) {
      effects.consume(code5);
      return tagOpenBetween;
    }
    return end(code5);
  }
  function tagOpenAttributeName(code5) {
    if (code5 === codes.dash || code5 === codes.dot || code5 === codes.colon || code5 === codes.underscore || asciiAlphanumeric(code5)) {
      effects.consume(code5);
      return tagOpenAttributeName;
    }
    return tagOpenAttributeNameAfter(code5);
  }
  function tagOpenAttributeNameAfter(code5) {
    if (code5 === codes.equalsTo) {
      effects.consume(code5);
      return tagOpenAttributeValueBefore;
    }
    if (markdownLineEnding(code5)) {
      returnState = tagOpenAttributeNameAfter;
      return lineEndingBefore(code5);
    }
    if (markdownSpace(code5)) {
      effects.consume(code5);
      return tagOpenAttributeNameAfter;
    }
    return tagOpenBetween(code5);
  }
  function tagOpenAttributeValueBefore(code5) {
    if (code5 === codes.eof || code5 === codes.lessThan || code5 === codes.equalsTo || code5 === codes.greaterThan || code5 === codes.graveAccent) {
      return nok(code5);
    }
    if (code5 === codes.quotationMark || code5 === codes.apostrophe) {
      effects.consume(code5);
      marker = code5;
      return tagOpenAttributeValueQuoted;
    }
    if (markdownLineEnding(code5)) {
      returnState = tagOpenAttributeValueBefore;
      return lineEndingBefore(code5);
    }
    if (markdownSpace(code5)) {
      effects.consume(code5);
      return tagOpenAttributeValueBefore;
    }
    effects.consume(code5);
    return tagOpenAttributeValueUnquoted;
  }
  function tagOpenAttributeValueQuoted(code5) {
    if (code5 === marker) {
      effects.consume(code5);
      marker = void 0;
      return tagOpenAttributeValueQuotedAfter;
    }
    if (code5 === codes.eof) {
      return nok(code5);
    }
    if (markdownLineEnding(code5)) {
      returnState = tagOpenAttributeValueQuoted;
      return lineEndingBefore(code5);
    }
    effects.consume(code5);
    return tagOpenAttributeValueQuoted;
  }
  function tagOpenAttributeValueUnquoted(code5) {
    if (code5 === codes.eof || code5 === codes.quotationMark || code5 === codes.apostrophe || code5 === codes.lessThan || code5 === codes.equalsTo || code5 === codes.graveAccent) {
      return nok(code5);
    }
    if (code5 === codes.slash || code5 === codes.greaterThan || markdownLineEndingOrSpace(code5)) {
      return tagOpenBetween(code5);
    }
    effects.consume(code5);
    return tagOpenAttributeValueUnquoted;
  }
  function tagOpenAttributeValueQuotedAfter(code5) {
    if (code5 === codes.slash || code5 === codes.greaterThan || markdownLineEndingOrSpace(code5)) {
      return tagOpenBetween(code5);
    }
    return nok(code5);
  }
  function end(code5) {
    if (code5 === codes.greaterThan) {
      effects.consume(code5);
      effects.exit(types.htmlTextData);
      effects.exit(types.htmlText);
      return ok3;
    }
    return nok(code5);
  }
  function lineEndingBefore(code5) {
    ok(returnState, "expected return state");
    ok(markdownLineEnding(code5), "expected eol");
    effects.exit(types.htmlTextData);
    effects.enter(types.lineEnding);
    effects.consume(code5);
    effects.exit(types.lineEnding);
    return lineEndingAfter;
  }
  function lineEndingAfter(code5) {
    ok(
      self2.parser.constructs.disable.null,
      "expected `disable.null` to be populated"
    );
    return markdownSpace(code5) ? factorySpace(
      effects,
      lineEndingAfterPrefix,
      types.linePrefix,
      self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : constants.tabSize
    )(code5) : lineEndingAfterPrefix(code5);
  }
  function lineEndingAfterPrefix(code5) {
    effects.enter(types.htmlTextData);
    return returnState(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/label-end.js
var labelEnd = {
  name: "labelEnd",
  resolveAll: resolveAllLabelEnd,
  resolveTo: resolveToLabelEnd,
  tokenize: tokenizeLabelEnd
};
var resourceConstruct = { tokenize: tokenizeResource };
var referenceFullConstruct = { tokenize: tokenizeReferenceFull };
var referenceCollapsedConstruct = { tokenize: tokenizeReferenceCollapsed };
function resolveAllLabelEnd(events) {
  let index4 = -1;
  const newEvents = [];
  while (++index4 < events.length) {
    const token = events[index4][1];
    newEvents.push(events[index4]);
    if (token.type === types.labelImage || token.type === types.labelLink || token.type === types.labelEnd) {
      const offset4 = token.type === types.labelImage ? 4 : 2;
      token.type = types.data;
      index4 += offset4;
    }
  }
  if (events.length !== newEvents.length) {
    splice(events, 0, events.length, newEvents);
  }
  return events;
}
function resolveToLabelEnd(events, context) {
  let index4 = events.length;
  let offset4 = 0;
  let token;
  let open;
  let close2;
  let media2;
  while (index4--) {
    token = events[index4][1];
    if (open) {
      if (token.type === types.link || token.type === types.labelLink && token._inactive) {
        break;
      }
      if (events[index4][0] === "enter" && token.type === types.labelLink) {
        token._inactive = true;
      }
    } else if (close2) {
      if (events[index4][0] === "enter" && (token.type === types.labelImage || token.type === types.labelLink) && !token._balanced) {
        open = index4;
        if (token.type !== types.labelLink) {
          offset4 = 2;
          break;
        }
      }
    } else if (token.type === types.labelEnd) {
      close2 = index4;
    }
  }
  ok(open !== void 0, "`open` is supposed to be found");
  ok(close2 !== void 0, "`close` is supposed to be found");
  const group = {
    type: events[open][1].type === types.labelLink ? types.link : types.image,
    start: { ...events[open][1].start },
    end: { ...events[events.length - 1][1].end }
  };
  const label = {
    type: types.label,
    start: { ...events[open][1].start },
    end: { ...events[close2][1].end }
  };
  const text10 = {
    type: types.labelText,
    start: { ...events[open + offset4 + 2][1].end },
    end: { ...events[close2 - 2][1].start }
  };
  media2 = [
    ["enter", group, context],
    ["enter", label, context]
  ];
  media2 = push(media2, events.slice(open + 1, open + offset4 + 3));
  media2 = push(media2, [["enter", text10, context]]);
  ok(
    context.parser.constructs.insideSpan.null,
    "expected `insideSpan.null` to be populated"
  );
  media2 = push(
    media2,
    resolveAll(
      context.parser.constructs.insideSpan.null,
      events.slice(open + offset4 + 4, close2 - 3),
      context
    )
  );
  media2 = push(media2, [
    ["exit", text10, context],
    events[close2 - 2],
    events[close2 - 1],
    ["exit", label, context]
  ]);
  media2 = push(media2, events.slice(close2 + 1));
  media2 = push(media2, [["exit", group, context]]);
  splice(events, open, events.length, media2);
  return events;
}
function tokenizeLabelEnd(effects, ok3, nok) {
  const self2 = this;
  let index4 = self2.events.length;
  let labelStart;
  let defined;
  while (index4--) {
    if ((self2.events[index4][1].type === types.labelImage || self2.events[index4][1].type === types.labelLink) && !self2.events[index4][1]._balanced) {
      labelStart = self2.events[index4][1];
      break;
    }
  }
  return start;
  function start(code5) {
    ok(code5 === codes.rightSquareBracket, "expected `]`");
    if (!labelStart) {
      return nok(code5);
    }
    if (labelStart._inactive) {
      return labelEndNok(code5);
    }
    defined = self2.parser.defined.includes(
      normalizeIdentifier(
        self2.sliceSerialize({ start: labelStart.end, end: self2.now() })
      )
    );
    effects.enter(types.labelEnd);
    effects.enter(types.labelMarker);
    effects.consume(code5);
    effects.exit(types.labelMarker);
    effects.exit(types.labelEnd);
    return after;
  }
  function after(code5) {
    if (code5 === codes.leftParenthesis) {
      return effects.attempt(
        resourceConstruct,
        labelEndOk,
        defined ? labelEndOk : labelEndNok
      )(code5);
    }
    if (code5 === codes.leftSquareBracket) {
      return effects.attempt(
        referenceFullConstruct,
        labelEndOk,
        defined ? referenceNotFull : labelEndNok
      )(code5);
    }
    return defined ? labelEndOk(code5) : labelEndNok(code5);
  }
  function referenceNotFull(code5) {
    return effects.attempt(
      referenceCollapsedConstruct,
      labelEndOk,
      labelEndNok
    )(code5);
  }
  function labelEndOk(code5) {
    return ok3(code5);
  }
  function labelEndNok(code5) {
    labelStart._balanced = true;
    return nok(code5);
  }
}
function tokenizeResource(effects, ok3, nok) {
  return resourceStart;
  function resourceStart(code5) {
    ok(code5 === codes.leftParenthesis, "expected left paren");
    effects.enter(types.resource);
    effects.enter(types.resourceMarker);
    effects.consume(code5);
    effects.exit(types.resourceMarker);
    return resourceBefore;
  }
  function resourceBefore(code5) {
    return markdownLineEndingOrSpace(code5) ? factoryWhitespace(effects, resourceOpen)(code5) : resourceOpen(code5);
  }
  function resourceOpen(code5) {
    if (code5 === codes.rightParenthesis) {
      return resourceEnd(code5);
    }
    return factoryDestination(
      effects,
      resourceDestinationAfter,
      resourceDestinationMissing,
      types.resourceDestination,
      types.resourceDestinationLiteral,
      types.resourceDestinationLiteralMarker,
      types.resourceDestinationRaw,
      types.resourceDestinationString,
      constants.linkResourceDestinationBalanceMax
    )(code5);
  }
  function resourceDestinationAfter(code5) {
    return markdownLineEndingOrSpace(code5) ? factoryWhitespace(effects, resourceBetween)(code5) : resourceEnd(code5);
  }
  function resourceDestinationMissing(code5) {
    return nok(code5);
  }
  function resourceBetween(code5) {
    if (code5 === codes.quotationMark || code5 === codes.apostrophe || code5 === codes.leftParenthesis) {
      return factoryTitle(
        effects,
        resourceTitleAfter,
        nok,
        types.resourceTitle,
        types.resourceTitleMarker,
        types.resourceTitleString
      )(code5);
    }
    return resourceEnd(code5);
  }
  function resourceTitleAfter(code5) {
    return markdownLineEndingOrSpace(code5) ? factoryWhitespace(effects, resourceEnd)(code5) : resourceEnd(code5);
  }
  function resourceEnd(code5) {
    if (code5 === codes.rightParenthesis) {
      effects.enter(types.resourceMarker);
      effects.consume(code5);
      effects.exit(types.resourceMarker);
      effects.exit(types.resource);
      return ok3;
    }
    return nok(code5);
  }
}
function tokenizeReferenceFull(effects, ok3, nok) {
  const self2 = this;
  return referenceFull;
  function referenceFull(code5) {
    ok(code5 === codes.leftSquareBracket, "expected left bracket");
    return factoryLabel.call(
      self2,
      effects,
      referenceFullAfter,
      referenceFullMissing,
      types.reference,
      types.referenceMarker,
      types.referenceString
    )(code5);
  }
  function referenceFullAfter(code5) {
    return self2.parser.defined.includes(
      normalizeIdentifier(
        self2.sliceSerialize(self2.events[self2.events.length - 1][1]).slice(1, -1)
      )
    ) ? ok3(code5) : nok(code5);
  }
  function referenceFullMissing(code5) {
    return nok(code5);
  }
}
function tokenizeReferenceCollapsed(effects, ok3, nok) {
  return referenceCollapsedStart;
  function referenceCollapsedStart(code5) {
    ok(code5 === codes.leftSquareBracket, "expected left bracket");
    effects.enter(types.reference);
    effects.enter(types.referenceMarker);
    effects.consume(code5);
    effects.exit(types.referenceMarker);
    return referenceCollapsedOpen;
  }
  function referenceCollapsedOpen(code5) {
    if (code5 === codes.rightSquareBracket) {
      effects.enter(types.referenceMarker);
      effects.consume(code5);
      effects.exit(types.referenceMarker);
      effects.exit(types.reference);
      return ok3;
    }
    return nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/label-start-image.js
var labelStartImage = {
  name: "labelStartImage",
  resolveAll: labelEnd.resolveAll,
  tokenize: tokenizeLabelStartImage
};
function tokenizeLabelStartImage(effects, ok3, nok) {
  const self2 = this;
  return start;
  function start(code5) {
    ok(code5 === codes.exclamationMark, "expected `!`");
    effects.enter(types.labelImage);
    effects.enter(types.labelImageMarker);
    effects.consume(code5);
    effects.exit(types.labelImageMarker);
    return open;
  }
  function open(code5) {
    if (code5 === codes.leftSquareBracket) {
      effects.enter(types.labelMarker);
      effects.consume(code5);
      effects.exit(types.labelMarker);
      effects.exit(types.labelImage);
      return after;
    }
    return nok(code5);
  }
  function after(code5) {
    return code5 === codes.caret && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code5) : ok3(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/label-start-link.js
var labelStartLink = {
  name: "labelStartLink",
  resolveAll: labelEnd.resolveAll,
  tokenize: tokenizeLabelStartLink
};
function tokenizeLabelStartLink(effects, ok3, nok) {
  const self2 = this;
  return start;
  function start(code5) {
    ok(code5 === codes.leftSquareBracket, "expected `[`");
    effects.enter(types.labelLink);
    effects.enter(types.labelMarker);
    effects.consume(code5);
    effects.exit(types.labelMarker);
    effects.exit(types.labelLink);
    return after;
  }
  function after(code5) {
    return code5 === codes.caret && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code5) : ok3(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/line-ending.js
var lineEnding = { name: "lineEnding", tokenize: tokenizeLineEnding };
function tokenizeLineEnding(effects, ok3) {
  return start;
  function start(code5) {
    ok(markdownLineEnding(code5), "expected eol");
    effects.enter(types.lineEnding);
    effects.consume(code5);
    effects.exit(types.lineEnding);
    return factorySpace(effects, ok3, types.linePrefix);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/thematic-break.js
var thematicBreak2 = {
  name: "thematicBreak",
  tokenize: tokenizeThematicBreak
};
function tokenizeThematicBreak(effects, ok3, nok) {
  let size5 = 0;
  let marker;
  return start;
  function start(code5) {
    effects.enter(types.thematicBreak);
    return before(code5);
  }
  function before(code5) {
    ok(
      code5 === codes.asterisk || code5 === codes.dash || code5 === codes.underscore,
      "expected `*`, `-`, or `_`"
    );
    marker = code5;
    return atBreak(code5);
  }
  function atBreak(code5) {
    if (code5 === marker) {
      effects.enter(types.thematicBreakSequence);
      return sequence(code5);
    }
    if (size5 >= constants.thematicBreakMarkerCountMin && (code5 === codes.eof || markdownLineEnding(code5))) {
      effects.exit(types.thematicBreak);
      return ok3(code5);
    }
    return nok(code5);
  }
  function sequence(code5) {
    if (code5 === marker) {
      effects.consume(code5);
      size5++;
      return sequence;
    }
    effects.exit(types.thematicBreakSequence);
    return markdownSpace(code5) ? factorySpace(effects, atBreak, types.whitespace)(code5) : atBreak(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/list.js
var list5 = {
  continuation: { tokenize: tokenizeListContinuation },
  exit: tokenizeListEnd,
  name: "list",
  tokenize: tokenizeListStart
};
var listItemPrefixWhitespaceConstruct = {
  partial: true,
  tokenize: tokenizeListItemPrefixWhitespace
};
var indentConstruct = { partial: true, tokenize: tokenizeIndent };
function tokenizeListStart(effects, ok3, nok) {
  const self2 = this;
  const tail = self2.events[self2.events.length - 1];
  let initialSize = tail && tail[1].type === types.linePrefix ? tail[2].sliceSerialize(tail[1], true).length : 0;
  let size5 = 0;
  return start;
  function start(code5) {
    ok(self2.containerState, "expected state");
    const kind = self2.containerState.type || (code5 === codes.asterisk || code5 === codes.plusSign || code5 === codes.dash ? types.listUnordered : types.listOrdered);
    if (kind === types.listUnordered ? !self2.containerState.marker || code5 === self2.containerState.marker : asciiDigit(code5)) {
      if (!self2.containerState.type) {
        self2.containerState.type = kind;
        effects.enter(kind, { _container: true });
      }
      if (kind === types.listUnordered) {
        effects.enter(types.listItemPrefix);
        return code5 === codes.asterisk || code5 === codes.dash ? effects.check(thematicBreak2, nok, atMarker)(code5) : atMarker(code5);
      }
      if (!self2.interrupt || code5 === codes.digit1) {
        effects.enter(types.listItemPrefix);
        effects.enter(types.listItemValue);
        return inside(code5);
      }
    }
    return nok(code5);
  }
  function inside(code5) {
    ok(self2.containerState, "expected state");
    if (asciiDigit(code5) && ++size5 < constants.listItemValueSizeMax) {
      effects.consume(code5);
      return inside;
    }
    if ((!self2.interrupt || size5 < 2) && (self2.containerState.marker ? code5 === self2.containerState.marker : code5 === codes.rightParenthesis || code5 === codes.dot)) {
      effects.exit(types.listItemValue);
      return atMarker(code5);
    }
    return nok(code5);
  }
  function atMarker(code5) {
    ok(self2.containerState, "expected state");
    ok(code5 !== codes.eof, "eof (`null`) is not a marker");
    effects.enter(types.listItemMarker);
    effects.consume(code5);
    effects.exit(types.listItemMarker);
    self2.containerState.marker = self2.containerState.marker || code5;
    return effects.check(
      blankLine,
      // Can’t be empty when interrupting.
      self2.interrupt ? nok : onBlank,
      effects.attempt(
        listItemPrefixWhitespaceConstruct,
        endOfPrefix,
        otherPrefix
      )
    );
  }
  function onBlank(code5) {
    ok(self2.containerState, "expected state");
    self2.containerState.initialBlankLine = true;
    initialSize++;
    return endOfPrefix(code5);
  }
  function otherPrefix(code5) {
    if (markdownSpace(code5)) {
      effects.enter(types.listItemPrefixWhitespace);
      effects.consume(code5);
      effects.exit(types.listItemPrefixWhitespace);
      return endOfPrefix;
    }
    return nok(code5);
  }
  function endOfPrefix(code5) {
    ok(self2.containerState, "expected state");
    self2.containerState.size = initialSize + self2.sliceSerialize(effects.exit(types.listItemPrefix), true).length;
    return ok3(code5);
  }
}
function tokenizeListContinuation(effects, ok3, nok) {
  const self2 = this;
  ok(self2.containerState, "expected state");
  self2.containerState._closeFlow = void 0;
  return effects.check(blankLine, onBlank, notBlank);
  function onBlank(code5) {
    ok(self2.containerState, "expected state");
    ok(typeof self2.containerState.size === "number", "expected size");
    self2.containerState.furtherBlankLines = self2.containerState.furtherBlankLines || self2.containerState.initialBlankLine;
    return factorySpace(
      effects,
      ok3,
      types.listItemIndent,
      self2.containerState.size + 1
    )(code5);
  }
  function notBlank(code5) {
    ok(self2.containerState, "expected state");
    if (self2.containerState.furtherBlankLines || !markdownSpace(code5)) {
      self2.containerState.furtherBlankLines = void 0;
      self2.containerState.initialBlankLine = void 0;
      return notInCurrentItem(code5);
    }
    self2.containerState.furtherBlankLines = void 0;
    self2.containerState.initialBlankLine = void 0;
    return effects.attempt(indentConstruct, ok3, notInCurrentItem)(code5);
  }
  function notInCurrentItem(code5) {
    ok(self2.containerState, "expected state");
    self2.containerState._closeFlow = true;
    self2.interrupt = void 0;
    ok(
      self2.parser.constructs.disable.null,
      "expected `disable.null` to be populated"
    );
    return factorySpace(
      effects,
      effects.attempt(list5, ok3, nok),
      types.linePrefix,
      self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : constants.tabSize
    )(code5);
  }
}
function tokenizeIndent(effects, ok3, nok) {
  const self2 = this;
  ok(self2.containerState, "expected state");
  ok(typeof self2.containerState.size === "number", "expected size");
  return factorySpace(
    effects,
    afterPrefix,
    types.listItemIndent,
    self2.containerState.size + 1
  );
  function afterPrefix(code5) {
    ok(self2.containerState, "expected state");
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === types.listItemIndent && tail[2].sliceSerialize(tail[1], true).length === self2.containerState.size ? ok3(code5) : nok(code5);
  }
}
function tokenizeListEnd(effects) {
  ok(this.containerState, "expected state");
  ok(typeof this.containerState.type === "string", "expected type");
  effects.exit(this.containerState.type);
}
function tokenizeListItemPrefixWhitespace(effects, ok3, nok) {
  const self2 = this;
  ok(
    self2.parser.constructs.disable.null,
    "expected `disable.null` to be populated"
  );
  return factorySpace(
    effects,
    afterPrefix,
    types.listItemPrefixWhitespace,
    self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : constants.tabSize + 1
  );
  function afterPrefix(code5) {
    const tail = self2.events[self2.events.length - 1];
    return !markdownSpace(code5) && tail && tail[1].type === types.listItemPrefixWhitespace ? ok3(code5) : nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-core-commonmark@2.0.3/node_modules/micromark-core-commonmark/dev/lib/setext-underline.js
var setextUnderline = {
  name: "setextUnderline",
  resolveTo: resolveToSetextUnderline,
  tokenize: tokenizeSetextUnderline
};
function resolveToSetextUnderline(events, context) {
  let index4 = events.length;
  let content5;
  let text10;
  let definition3;
  while (index4--) {
    if (events[index4][0] === "enter") {
      if (events[index4][1].type === types.content) {
        content5 = index4;
        break;
      }
      if (events[index4][1].type === types.paragraph) {
        text10 = index4;
      }
    } else {
      if (events[index4][1].type === types.content) {
        events.splice(index4, 1);
      }
      if (!definition3 && events[index4][1].type === types.definition) {
        definition3 = index4;
      }
    }
  }
  ok(text10 !== void 0, "expected a `text` index to be found");
  ok(content5 !== void 0, "expected a `text` index to be found");
  ok(events[content5][2] === context, "enter context should be same");
  ok(
    events[events.length - 1][2] === context,
    "enter context should be same"
  );
  const heading4 = {
    type: types.setextHeading,
    start: { ...events[content5][1].start },
    end: { ...events[events.length - 1][1].end }
  };
  events[text10][1].type = types.setextHeadingText;
  if (definition3) {
    events.splice(text10, 0, ["enter", heading4, context]);
    events.splice(definition3 + 1, 0, ["exit", events[content5][1], context]);
    events[content5][1].end = { ...events[definition3][1].end };
  } else {
    events[content5][1] = heading4;
  }
  events.push(["exit", heading4, context]);
  return events;
}
function tokenizeSetextUnderline(effects, ok3, nok) {
  const self2 = this;
  let marker;
  return start;
  function start(code5) {
    let index4 = self2.events.length;
    let paragraph3;
    ok(
      code5 === codes.dash || code5 === codes.equalsTo,
      "expected `=` or `-`"
    );
    while (index4--) {
      if (self2.events[index4][1].type !== types.lineEnding && self2.events[index4][1].type !== types.linePrefix && self2.events[index4][1].type !== types.content) {
        paragraph3 = self2.events[index4][1].type === types.paragraph;
        break;
      }
    }
    if (!self2.parser.lazy[self2.now().line] && (self2.interrupt || paragraph3)) {
      effects.enter(types.setextHeadingLine);
      marker = code5;
      return before(code5);
    }
    return nok(code5);
  }
  function before(code5) {
    effects.enter(types.setextHeadingLineSequence);
    return inside(code5);
  }
  function inside(code5) {
    if (code5 === marker) {
      effects.consume(code5);
      return inside;
    }
    effects.exit(types.setextHeadingLineSequence);
    return markdownSpace(code5) ? factorySpace(effects, after, types.lineSuffix)(code5) : after(code5);
  }
  function after(code5) {
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit(types.setextHeadingLine);
      return ok3(code5);
    }
    return nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-extension-gfm-footnote@2.1.0/node_modules/micromark-extension-gfm-footnote/dev/lib/syntax.js
var indent = { tokenize: tokenizeIndent2, partial: true };
function gfmFootnote() {
  return {
    document: {
      [codes.leftSquareBracket]: {
        name: "gfmFootnoteDefinition",
        tokenize: tokenizeDefinitionStart,
        continuation: { tokenize: tokenizeDefinitionContinuation },
        exit: gfmFootnoteDefinitionEnd
      }
    },
    text: {
      [codes.leftSquareBracket]: {
        name: "gfmFootnoteCall",
        tokenize: tokenizeGfmFootnoteCall
      },
      [codes.rightSquareBracket]: {
        name: "gfmPotentialFootnoteCall",
        add: "after",
        tokenize: tokenizePotentialGfmFootnoteCall,
        resolveTo: resolveToPotentialGfmFootnoteCall
      }
    }
  };
}
function tokenizePotentialGfmFootnoteCall(effects, ok3, nok) {
  const self2 = this;
  let index4 = self2.events.length;
  const defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []);
  let labelStart;
  while (index4--) {
    const token = self2.events[index4][1];
    if (token.type === types.labelImage) {
      labelStart = token;
      break;
    }
    if (token.type === "gfmFootnoteCall" || token.type === types.labelLink || token.type === types.label || token.type === types.image || token.type === types.link) {
      break;
    }
  }
  return start;
  function start(code5) {
    ok(code5 === codes.rightSquareBracket, "expected `]`");
    if (!labelStart || !labelStart._balanced) {
      return nok(code5);
    }
    const id2 = normalizeIdentifier(
      self2.sliceSerialize({ start: labelStart.end, end: self2.now() })
    );
    if (id2.codePointAt(0) !== codes.caret || !defined.includes(id2.slice(1))) {
      return nok(code5);
    }
    effects.enter("gfmFootnoteCallLabelMarker");
    effects.consume(code5);
    effects.exit("gfmFootnoteCallLabelMarker");
    return ok3(code5);
  }
}
function resolveToPotentialGfmFootnoteCall(events, context) {
  let index4 = events.length;
  let labelStart;
  while (index4--) {
    if (events[index4][1].type === types.labelImage && events[index4][0] === "enter") {
      labelStart = events[index4][1];
      break;
    }
  }
  ok(labelStart, "expected `labelStart` to resolve");
  events[index4 + 1][1].type = types.data;
  events[index4 + 3][1].type = "gfmFootnoteCallLabelMarker";
  const call = {
    type: "gfmFootnoteCall",
    start: Object.assign({}, events[index4 + 3][1].start),
    end: Object.assign({}, events[events.length - 1][1].end)
  };
  const marker = {
    type: "gfmFootnoteCallMarker",
    start: Object.assign({}, events[index4 + 3][1].end),
    end: Object.assign({}, events[index4 + 3][1].end)
  };
  marker.end.column++;
  marker.end.offset++;
  marker.end._bufferIndex++;
  const string3 = {
    type: "gfmFootnoteCallString",
    start: Object.assign({}, marker.end),
    end: Object.assign({}, events[events.length - 1][1].start)
  };
  const chunk = {
    type: types.chunkString,
    contentType: "string",
    start: Object.assign({}, string3.start),
    end: Object.assign({}, string3.end)
  };
  const replacement = [
    // Take the `labelImageMarker` (now `data`, the `!`)
    events[index4 + 1],
    events[index4 + 2],
    ["enter", call, context],
    // The `[`
    events[index4 + 3],
    events[index4 + 4],
    // The `^`.
    ["enter", marker, context],
    ["exit", marker, context],
    // Everything in between.
    ["enter", string3, context],
    ["enter", chunk, context],
    ["exit", chunk, context],
    ["exit", string3, context],
    // The ending (`]`, properly parsed and labelled).
    events[events.length - 2],
    events[events.length - 1],
    ["exit", call, context]
  ];
  events.splice(index4, events.length - index4 + 1, ...replacement);
  return events;
}
function tokenizeGfmFootnoteCall(effects, ok3, nok) {
  const self2 = this;
  const defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []);
  let size5 = 0;
  let data;
  return start;
  function start(code5) {
    ok(code5 === codes.leftSquareBracket, "expected `[`");
    effects.enter("gfmFootnoteCall");
    effects.enter("gfmFootnoteCallLabelMarker");
    effects.consume(code5);
    effects.exit("gfmFootnoteCallLabelMarker");
    return callStart;
  }
  function callStart(code5) {
    if (code5 !== codes.caret) return nok(code5);
    effects.enter("gfmFootnoteCallMarker");
    effects.consume(code5);
    effects.exit("gfmFootnoteCallMarker");
    effects.enter("gfmFootnoteCallString");
    effects.enter("chunkString").contentType = "string";
    return callData;
  }
  function callData(code5) {
    if (
      // Too long.
      size5 > constants.linkReferenceSizeMax || // Closing brace with nothing.
      code5 === codes.rightSquareBracket && !data || // Space or tab is not supported by GFM for some reason.
      // `\n` and `[` not being supported makes sense.
      code5 === codes.eof || code5 === codes.leftSquareBracket || markdownLineEndingOrSpace(code5)
    ) {
      return nok(code5);
    }
    if (code5 === codes.rightSquareBracket) {
      effects.exit("chunkString");
      const token = effects.exit("gfmFootnoteCallString");
      if (!defined.includes(normalizeIdentifier(self2.sliceSerialize(token)))) {
        return nok(code5);
      }
      effects.enter("gfmFootnoteCallLabelMarker");
      effects.consume(code5);
      effects.exit("gfmFootnoteCallLabelMarker");
      effects.exit("gfmFootnoteCall");
      return ok3;
    }
    if (!markdownLineEndingOrSpace(code5)) {
      data = true;
    }
    size5++;
    effects.consume(code5);
    return code5 === codes.backslash ? callEscape : callData;
  }
  function callEscape(code5) {
    if (code5 === codes.leftSquareBracket || code5 === codes.backslash || code5 === codes.rightSquareBracket) {
      effects.consume(code5);
      size5++;
      return callData;
    }
    return callData(code5);
  }
}
function tokenizeDefinitionStart(effects, ok3, nok) {
  const self2 = this;
  const defined = self2.parser.gfmFootnotes || (self2.parser.gfmFootnotes = []);
  let identifier;
  let size5 = 0;
  let data;
  return start;
  function start(code5) {
    ok(code5 === codes.leftSquareBracket, "expected `[`");
    effects.enter("gfmFootnoteDefinition")._container = true;
    effects.enter("gfmFootnoteDefinitionLabel");
    effects.enter("gfmFootnoteDefinitionLabelMarker");
    effects.consume(code5);
    effects.exit("gfmFootnoteDefinitionLabelMarker");
    return labelAtMarker;
  }
  function labelAtMarker(code5) {
    if (code5 === codes.caret) {
      effects.enter("gfmFootnoteDefinitionMarker");
      effects.consume(code5);
      effects.exit("gfmFootnoteDefinitionMarker");
      effects.enter("gfmFootnoteDefinitionLabelString");
      effects.enter("chunkString").contentType = "string";
      return labelInside;
    }
    return nok(code5);
  }
  function labelInside(code5) {
    if (
      // Too long.
      size5 > constants.linkReferenceSizeMax || // Closing brace with nothing.
      code5 === codes.rightSquareBracket && !data || // Space or tab is not supported by GFM for some reason.
      // `\n` and `[` not being supported makes sense.
      code5 === codes.eof || code5 === codes.leftSquareBracket || markdownLineEndingOrSpace(code5)
    ) {
      return nok(code5);
    }
    if (code5 === codes.rightSquareBracket) {
      effects.exit("chunkString");
      const token = effects.exit("gfmFootnoteDefinitionLabelString");
      identifier = normalizeIdentifier(self2.sliceSerialize(token));
      effects.enter("gfmFootnoteDefinitionLabelMarker");
      effects.consume(code5);
      effects.exit("gfmFootnoteDefinitionLabelMarker");
      effects.exit("gfmFootnoteDefinitionLabel");
      return labelAfter;
    }
    if (!markdownLineEndingOrSpace(code5)) {
      data = true;
    }
    size5++;
    effects.consume(code5);
    return code5 === codes.backslash ? labelEscape : labelInside;
  }
  function labelEscape(code5) {
    if (code5 === codes.leftSquareBracket || code5 === codes.backslash || code5 === codes.rightSquareBracket) {
      effects.consume(code5);
      size5++;
      return labelInside;
    }
    return labelInside(code5);
  }
  function labelAfter(code5) {
    if (code5 === codes.colon) {
      effects.enter("definitionMarker");
      effects.consume(code5);
      effects.exit("definitionMarker");
      if (!defined.includes(identifier)) {
        defined.push(identifier);
      }
      return factorySpace(
        effects,
        whitespaceAfter,
        "gfmFootnoteDefinitionWhitespace"
      );
    }
    return nok(code5);
  }
  function whitespaceAfter(code5) {
    return ok3(code5);
  }
}
function tokenizeDefinitionContinuation(effects, ok3, nok) {
  return effects.check(blankLine, ok3, effects.attempt(indent, ok3, nok));
}
function gfmFootnoteDefinitionEnd(effects) {
  effects.exit("gfmFootnoteDefinition");
}
function tokenizeIndent2(effects, ok3, nok) {
  const self2 = this;
  return factorySpace(
    effects,
    afterPrefix,
    "gfmFootnoteDefinitionIndent",
    constants.tabSize + 1
  );
  function afterPrefix(code5) {
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === "gfmFootnoteDefinitionIndent" && tail[2].sliceSerialize(tail[1], true).length === constants.tabSize ? ok3(code5) : nok(code5);
  }
}

// ../../node_modules/.pnpm/micromark-extension-gfm-footnote@2.1.0/node_modules/micromark-extension-gfm-footnote/dev/lib/html.js
var own6 = {}.hasOwnProperty;

// ../../node_modules/.pnpm/micromark-extension-gfm-strikethrough@2.1.0/node_modules/micromark-extension-gfm-strikethrough/dev/lib/syntax.js
function gfmStrikethrough(options2) {
  const options_ = options2 || {};
  let single = options_.singleTilde;
  const tokenizer = {
    name: "strikethrough",
    tokenize: tokenizeStrikethrough,
    resolveAll: resolveAllStrikethrough
  };
  if (single === null || single === void 0) {
    single = true;
  }
  return {
    text: { [codes.tilde]: tokenizer },
    insideSpan: { null: [tokenizer] },
    attentionMarkers: { null: [codes.tilde] }
  };
  function resolveAllStrikethrough(events, context) {
    let index4 = -1;
    while (++index4 < events.length) {
      if (events[index4][0] === "enter" && events[index4][1].type === "strikethroughSequenceTemporary" && events[index4][1]._close) {
        let open = index4;
        while (open--) {
          if (events[open][0] === "exit" && events[open][1].type === "strikethroughSequenceTemporary" && events[open][1]._open && // If the sizes are the same:
          events[index4][1].end.offset - events[index4][1].start.offset === events[open][1].end.offset - events[open][1].start.offset) {
            events[index4][1].type = "strikethroughSequence";
            events[open][1].type = "strikethroughSequence";
            const strikethrough2 = {
              type: "strikethrough",
              start: Object.assign({}, events[open][1].start),
              end: Object.assign({}, events[index4][1].end)
            };
            const text10 = {
              type: "strikethroughText",
              start: Object.assign({}, events[open][1].end),
              end: Object.assign({}, events[index4][1].start)
            };
            const nextEvents = [
              ["enter", strikethrough2, context],
              ["enter", events[open][1], context],
              ["exit", events[open][1], context],
              ["enter", text10, context]
            ];
            const insideSpan2 = context.parser.constructs.insideSpan.null;
            if (insideSpan2) {
              splice(
                nextEvents,
                nextEvents.length,
                0,
                resolveAll(insideSpan2, events.slice(open + 1, index4), context)
              );
            }
            splice(nextEvents, nextEvents.length, 0, [
              ["exit", text10, context],
              ["enter", events[index4][1], context],
              ["exit", events[index4][1], context],
              ["exit", strikethrough2, context]
            ]);
            splice(events, open - 1, index4 - open + 3, nextEvents);
            index4 = open + nextEvents.length - 2;
            break;
          }
        }
      }
    }
    index4 = -1;
    while (++index4 < events.length) {
      if (events[index4][1].type === "strikethroughSequenceTemporary") {
        events[index4][1].type = types.data;
      }
    }
    return events;
  }
  function tokenizeStrikethrough(effects, ok3, nok) {
    const previous3 = this.previous;
    const events = this.events;
    let size5 = 0;
    return start;
    function start(code5) {
      ok(code5 === codes.tilde, "expected `~`");
      if (previous3 === codes.tilde && events[events.length - 1][1].type !== types.characterEscape) {
        return nok(code5);
      }
      effects.enter("strikethroughSequenceTemporary");
      return more(code5);
    }
    function more(code5) {
      const before = classifyCharacter(previous3);
      if (code5 === codes.tilde) {
        if (size5 > 1) return nok(code5);
        effects.consume(code5);
        size5++;
        return more;
      }
      if (size5 < 2 && !single) return nok(code5);
      const token = effects.exit("strikethroughSequenceTemporary");
      const after = classifyCharacter(code5);
      token._open = !after || after === constants.attentionSideAfter && Boolean(before);
      token._close = !before || before === constants.attentionSideAfter && Boolean(after);
      return ok3(code5);
    }
  }
}

// ../../node_modules/.pnpm/micromark-extension-gfm-table@2.1.1/node_modules/micromark-extension-gfm-table/dev/lib/edit-map.js
var EditMap = class {
  /**
   * Create a new edit map.
   */
  constructor() {
    this.map = [];
  }
  /**
   * Create an edit: a remove and/or add at a certain place.
   *
   * @param {number} index
   * @param {number} remove
   * @param {Array<Event>} add
   * @returns {undefined}
   */
  add(index4, remove, add) {
    addImplementation(this, index4, remove, add);
  }
  // To do: add this when moving to `micromark`.
  // /**
  //  * Create an edit: but insert `add` before existing additions.
  //  *
  //  * @param {number} index
  //  * @param {number} remove
  //  * @param {Array<Event>} add
  //  * @returns {undefined}
  //  */
  // addBefore(index, remove, add) {
  //   addImplementation(this, index, remove, add, true)
  // }
  /**
   * Done, change the events.
   *
   * @param {Array<Event>} events
   * @returns {undefined}
   */
  consume(events) {
    this.map.sort(function(a3, b4) {
      return a3[0] - b4[0];
    });
    if (this.map.length === 0) {
      return;
    }
    let index4 = this.map.length;
    const vecs = [];
    while (index4 > 0) {
      index4 -= 1;
      vecs.push(
        events.slice(this.map[index4][0] + this.map[index4][1]),
        this.map[index4][2]
      );
      events.length = this.map[index4][0];
    }
    vecs.push(events.slice());
    events.length = 0;
    let slice2 = vecs.pop();
    while (slice2) {
      for (const element7 of slice2) {
        events.push(element7);
      }
      slice2 = vecs.pop();
    }
    this.map.length = 0;
  }
};
function addImplementation(editMap, at2, remove, add) {
  let index4 = 0;
  if (remove === 0 && add.length === 0) {
    return;
  }
  while (index4 < editMap.map.length) {
    if (editMap.map[index4][0] === at2) {
      editMap.map[index4][1] += remove;
      editMap.map[index4][2].push(...add);
      return;
    }
    index4 += 1;
  }
  editMap.map.push([at2, remove, add]);
}

// ../../node_modules/.pnpm/micromark-extension-gfm-table@2.1.1/node_modules/micromark-extension-gfm-table/dev/lib/infer.js
function gfmTableAlign(events, index4) {
  ok(events[index4][1].type === "table", "expected table");
  let inDelimiterRow = false;
  const align = [];
  while (index4 < events.length) {
    const event = events[index4];
    if (inDelimiterRow) {
      if (event[0] === "enter") {
        if (event[1].type === "tableContent") {
          align.push(
            events[index4 + 1][1].type === "tableDelimiterMarker" ? "left" : "none"
          );
        }
      } else if (event[1].type === "tableContent") {
        if (events[index4 - 1][1].type === "tableDelimiterMarker") {
          const alignIndex = align.length - 1;
          align[alignIndex] = align[alignIndex] === "left" ? "center" : "right";
        }
      } else if (event[1].type === "tableDelimiterRow") {
        break;
      }
    } else if (event[0] === "enter" && event[1].type === "tableDelimiterRow") {
      inDelimiterRow = true;
    }
    index4 += 1;
  }
  return align;
}

// ../../node_modules/.pnpm/micromark-extension-gfm-table@2.1.1/node_modules/micromark-extension-gfm-table/dev/lib/syntax.js
function gfmTable() {
  return {
    flow: {
      null: { name: "table", tokenize: tokenizeTable, resolveAll: resolveTable }
    }
  };
}
function tokenizeTable(effects, ok3, nok) {
  const self2 = this;
  let size5 = 0;
  let sizeB = 0;
  let seen;
  return start;
  function start(code5) {
    let index4 = self2.events.length - 1;
    while (index4 > -1) {
      const type = self2.events[index4][1].type;
      if (type === types.lineEnding || // Note: markdown-rs uses `whitespace` instead of `linePrefix`
      type === types.linePrefix)
        index4--;
      else break;
    }
    const tail = index4 > -1 ? self2.events[index4][1].type : null;
    const next2 = tail === "tableHead" || tail === "tableRow" ? bodyRowStart : headRowBefore;
    if (next2 === bodyRowStart && self2.parser.lazy[self2.now().line]) {
      return nok(code5);
    }
    return next2(code5);
  }
  function headRowBefore(code5) {
    effects.enter("tableHead");
    effects.enter("tableRow");
    return headRowStart(code5);
  }
  function headRowStart(code5) {
    if (code5 === codes.verticalBar) {
      return headRowBreak(code5);
    }
    seen = true;
    sizeB += 1;
    return headRowBreak(code5);
  }
  function headRowBreak(code5) {
    if (code5 === codes.eof) {
      return nok(code5);
    }
    if (markdownLineEnding(code5)) {
      if (sizeB > 1) {
        sizeB = 0;
        self2.interrupt = true;
        effects.exit("tableRow");
        effects.enter(types.lineEnding);
        effects.consume(code5);
        effects.exit(types.lineEnding);
        return headDelimiterStart;
      }
      return nok(code5);
    }
    if (markdownSpace(code5)) {
      return factorySpace(effects, headRowBreak, types.whitespace)(code5);
    }
    sizeB += 1;
    if (seen) {
      seen = false;
      size5 += 1;
    }
    if (code5 === codes.verticalBar) {
      effects.enter("tableCellDivider");
      effects.consume(code5);
      effects.exit("tableCellDivider");
      seen = true;
      return headRowBreak;
    }
    effects.enter(types.data);
    return headRowData(code5);
  }
  function headRowData(code5) {
    if (code5 === codes.eof || code5 === codes.verticalBar || markdownLineEndingOrSpace(code5)) {
      effects.exit(types.data);
      return headRowBreak(code5);
    }
    effects.consume(code5);
    return code5 === codes.backslash ? headRowEscape : headRowData;
  }
  function headRowEscape(code5) {
    if (code5 === codes.backslash || code5 === codes.verticalBar) {
      effects.consume(code5);
      return headRowData;
    }
    return headRowData(code5);
  }
  function headDelimiterStart(code5) {
    self2.interrupt = false;
    if (self2.parser.lazy[self2.now().line]) {
      return nok(code5);
    }
    effects.enter("tableDelimiterRow");
    seen = false;
    if (markdownSpace(code5)) {
      ok(self2.parser.constructs.disable.null, "expected `disabled.null`");
      return factorySpace(
        effects,
        headDelimiterBefore,
        types.linePrefix,
        self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : constants.tabSize
      )(code5);
    }
    return headDelimiterBefore(code5);
  }
  function headDelimiterBefore(code5) {
    if (code5 === codes.dash || code5 === codes.colon) {
      return headDelimiterValueBefore(code5);
    }
    if (code5 === codes.verticalBar) {
      seen = true;
      effects.enter("tableCellDivider");
      effects.consume(code5);
      effects.exit("tableCellDivider");
      return headDelimiterCellBefore;
    }
    return headDelimiterNok(code5);
  }
  function headDelimiterCellBefore(code5) {
    if (markdownSpace(code5)) {
      return factorySpace(
        effects,
        headDelimiterValueBefore,
        types.whitespace
      )(code5);
    }
    return headDelimiterValueBefore(code5);
  }
  function headDelimiterValueBefore(code5) {
    if (code5 === codes.colon) {
      sizeB += 1;
      seen = true;
      effects.enter("tableDelimiterMarker");
      effects.consume(code5);
      effects.exit("tableDelimiterMarker");
      return headDelimiterLeftAlignmentAfter;
    }
    if (code5 === codes.dash) {
      sizeB += 1;
      return headDelimiterLeftAlignmentAfter(code5);
    }
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      return headDelimiterCellAfter(code5);
    }
    return headDelimiterNok(code5);
  }
  function headDelimiterLeftAlignmentAfter(code5) {
    if (code5 === codes.dash) {
      effects.enter("tableDelimiterFiller");
      return headDelimiterFiller(code5);
    }
    return headDelimiterNok(code5);
  }
  function headDelimiterFiller(code5) {
    if (code5 === codes.dash) {
      effects.consume(code5);
      return headDelimiterFiller;
    }
    if (code5 === codes.colon) {
      seen = true;
      effects.exit("tableDelimiterFiller");
      effects.enter("tableDelimiterMarker");
      effects.consume(code5);
      effects.exit("tableDelimiterMarker");
      return headDelimiterRightAlignmentAfter;
    }
    effects.exit("tableDelimiterFiller");
    return headDelimiterRightAlignmentAfter(code5);
  }
  function headDelimiterRightAlignmentAfter(code5) {
    if (markdownSpace(code5)) {
      return factorySpace(
        effects,
        headDelimiterCellAfter,
        types.whitespace
      )(code5);
    }
    return headDelimiterCellAfter(code5);
  }
  function headDelimiterCellAfter(code5) {
    if (code5 === codes.verticalBar) {
      return headDelimiterBefore(code5);
    }
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      if (!seen || size5 !== sizeB) {
        return headDelimiterNok(code5);
      }
      effects.exit("tableDelimiterRow");
      effects.exit("tableHead");
      return ok3(code5);
    }
    return headDelimiterNok(code5);
  }
  function headDelimiterNok(code5) {
    return nok(code5);
  }
  function bodyRowStart(code5) {
    effects.enter("tableRow");
    return bodyRowBreak(code5);
  }
  function bodyRowBreak(code5) {
    if (code5 === codes.verticalBar) {
      effects.enter("tableCellDivider");
      effects.consume(code5);
      effects.exit("tableCellDivider");
      return bodyRowBreak;
    }
    if (code5 === codes.eof || markdownLineEnding(code5)) {
      effects.exit("tableRow");
      return ok3(code5);
    }
    if (markdownSpace(code5)) {
      return factorySpace(effects, bodyRowBreak, types.whitespace)(code5);
    }
    effects.enter(types.data);
    return bodyRowData(code5);
  }
  function bodyRowData(code5) {
    if (code5 === codes.eof || code5 === codes.verticalBar || markdownLineEndingOrSpace(code5)) {
      effects.exit(types.data);
      return bodyRowBreak(code5);
    }
    effects.consume(code5);
    return code5 === codes.backslash ? bodyRowEscape : bodyRowData;
  }
  function bodyRowEscape(code5) {
    if (code5 === codes.backslash || code5 === codes.verticalBar) {
      effects.consume(code5);
      return bodyRowData;
    }
    return bodyRowData(code5);
  }
}
function resolveTable(events, context) {
  let index4 = -1;
  let inFirstCellAwaitingPipe = true;
  let rowKind = 0;
  let lastCell = [0, 0, 0, 0];
  let cell2 = [0, 0, 0, 0];
  let afterHeadAwaitingFirstBodyRow = false;
  let lastTableEnd = 0;
  let currentTable;
  let currentBody;
  let currentCell;
  const map7 = new EditMap();
  while (++index4 < events.length) {
    const event = events[index4];
    const token = event[1];
    if (event[0] === "enter") {
      if (token.type === "tableHead") {
        afterHeadAwaitingFirstBodyRow = false;
        if (lastTableEnd !== 0) {
          ok(currentTable, "there should be a table opening");
          flushTableEnd(map7, context, lastTableEnd, currentTable, currentBody);
          currentBody = void 0;
          lastTableEnd = 0;
        }
        currentTable = {
          type: "table",
          start: Object.assign({}, token.start),
          // Note: correct end is set later.
          end: Object.assign({}, token.end)
        };
        map7.add(index4, 0, [["enter", currentTable, context]]);
      } else if (token.type === "tableRow" || token.type === "tableDelimiterRow") {
        inFirstCellAwaitingPipe = true;
        currentCell = void 0;
        lastCell = [0, 0, 0, 0];
        cell2 = [0, index4 + 1, 0, 0];
        if (afterHeadAwaitingFirstBodyRow) {
          afterHeadAwaitingFirstBodyRow = false;
          currentBody = {
            type: "tableBody",
            start: Object.assign({}, token.start),
            // Note: correct end is set later.
            end: Object.assign({}, token.end)
          };
          map7.add(index4, 0, [["enter", currentBody, context]]);
        }
        rowKind = token.type === "tableDelimiterRow" ? 2 : currentBody ? 3 : 1;
      } else if (rowKind && (token.type === types.data || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller")) {
        inFirstCellAwaitingPipe = false;
        if (cell2[2] === 0) {
          if (lastCell[1] !== 0) {
            cell2[0] = cell2[1];
            currentCell = flushCell(
              map7,
              context,
              lastCell,
              rowKind,
              void 0,
              currentCell
            );
            lastCell = [0, 0, 0, 0];
          }
          cell2[2] = index4;
        }
      } else if (token.type === "tableCellDivider") {
        if (inFirstCellAwaitingPipe) {
          inFirstCellAwaitingPipe = false;
        } else {
          if (lastCell[1] !== 0) {
            cell2[0] = cell2[1];
            currentCell = flushCell(
              map7,
              context,
              lastCell,
              rowKind,
              void 0,
              currentCell
            );
          }
          lastCell = cell2;
          cell2 = [lastCell[1], index4, 0, 0];
        }
      }
    } else if (token.type === "tableHead") {
      afterHeadAwaitingFirstBodyRow = true;
      lastTableEnd = index4;
    } else if (token.type === "tableRow" || token.type === "tableDelimiterRow") {
      lastTableEnd = index4;
      if (lastCell[1] !== 0) {
        cell2[0] = cell2[1];
        currentCell = flushCell(
          map7,
          context,
          lastCell,
          rowKind,
          index4,
          currentCell
        );
      } else if (cell2[1] !== 0) {
        currentCell = flushCell(map7, context, cell2, rowKind, index4, currentCell);
      }
      rowKind = 0;
    } else if (rowKind && (token.type === types.data || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller")) {
      cell2[3] = index4;
    }
  }
  if (lastTableEnd !== 0) {
    ok(currentTable, "expected table opening");
    flushTableEnd(map7, context, lastTableEnd, currentTable, currentBody);
  }
  map7.consume(context.events);
  index4 = -1;
  while (++index4 < context.events.length) {
    const event = context.events[index4];
    if (event[0] === "enter" && event[1].type === "table") {
      event[1]._align = gfmTableAlign(context.events, index4);
    }
  }
  return events;
}
function flushCell(map7, context, range, rowKind, rowEnd, previousCell) {
  const groupName = rowKind === 1 ? "tableHeader" : rowKind === 2 ? "tableDelimiter" : "tableData";
  const valueName = "tableContent";
  if (range[0] !== 0) {
    ok(previousCell, "expected previous cell enter");
    previousCell.end = Object.assign({}, getPoint(context.events, range[0]));
    map7.add(range[0], 0, [["exit", previousCell, context]]);
  }
  const now = getPoint(context.events, range[1]);
  previousCell = {
    type: groupName,
    start: Object.assign({}, now),
    // Note: correct end is set later.
    end: Object.assign({}, now)
  };
  map7.add(range[1], 0, [["enter", previousCell, context]]);
  if (range[2] !== 0) {
    const relatedStart = getPoint(context.events, range[2]);
    const relatedEnd = getPoint(context.events, range[3]);
    const valueToken = {
      type: valueName,
      start: Object.assign({}, relatedStart),
      end: Object.assign({}, relatedEnd)
    };
    map7.add(range[2], 0, [["enter", valueToken, context]]);
    ok(range[3] !== 0);
    if (rowKind !== 2) {
      const start = context.events[range[2]];
      const end = context.events[range[3]];
      start[1].end = Object.assign({}, end[1].end);
      start[1].type = types.chunkText;
      start[1].contentType = constants.contentTypeText;
      if (range[3] > range[2] + 1) {
        const a3 = range[2] + 1;
        const b4 = range[3] - range[2] - 1;
        map7.add(a3, b4, []);
      }
    }
    map7.add(range[3] + 1, 0, [["exit", valueToken, context]]);
  }
  if (rowEnd !== void 0) {
    previousCell.end = Object.assign({}, getPoint(context.events, rowEnd));
    map7.add(rowEnd, 0, [["exit", previousCell, context]]);
    previousCell = void 0;
  }
  return previousCell;
}
function flushTableEnd(map7, context, index4, table3, tableBody) {
  const exits = [];
  const related = getPoint(context.events, index4);
  if (tableBody) {
    tableBody.end = Object.assign({}, related);
    exits.push(["exit", tableBody, context]);
  }
  table3.end = Object.assign({}, related);
  exits.push(["exit", table3, context]);
  map7.add(index4 + 1, 0, exits);
}
function getPoint(events, index4) {
  const event = events[index4];
  const side = event[0] === "enter" ? "start" : "end";
  return event[1][side];
}

// ../../node_modules/.pnpm/micromark-extension-gfm-tagfilter@2.0.0/node_modules/micromark-extension-gfm-tagfilter/lib/index.js
var reFlow = /<(\/?)(iframe|noembed|noframes|plaintext|script|style|title|textarea|xmp)(?=[\t\n\f\r />])/gi;
var reText = new RegExp("^" + reFlow.source, "i");

// ../../node_modules/.pnpm/micromark-extension-gfm-task-list-item@2.1.0/node_modules/micromark-extension-gfm-task-list-item/dev/lib/syntax.js
var tasklistCheck = { name: "tasklistCheck", tokenize: tokenizeTasklistCheck };
function gfmTaskListItem() {
  return {
    text: { [codes.leftSquareBracket]: tasklistCheck }
  };
}
function tokenizeTasklistCheck(effects, ok3, nok) {
  const self2 = this;
  return open;
  function open(code5) {
    ok(code5 === codes.leftSquareBracket, "expected `[`");
    if (
      // Exit if there’s stuff before.
      self2.previous !== codes.eof || // Exit if not in the first content that is the first child of a list
      // item.
      !self2._gfmTasklistFirstContentOfListItem
    ) {
      return nok(code5);
    }
    effects.enter("taskListCheck");
    effects.enter("taskListCheckMarker");
    effects.consume(code5);
    effects.exit("taskListCheckMarker");
    return inside;
  }
  function inside(code5) {
    if (markdownLineEndingOrSpace(code5)) {
      effects.enter("taskListCheckValueUnchecked");
      effects.consume(code5);
      effects.exit("taskListCheckValueUnchecked");
      return close2;
    }
    if (code5 === codes.uppercaseX || code5 === codes.lowercaseX) {
      effects.enter("taskListCheckValueChecked");
      effects.consume(code5);
      effects.exit("taskListCheckValueChecked");
      return close2;
    }
    return nok(code5);
  }
  function close2(code5) {
    if (code5 === codes.rightSquareBracket) {
      effects.enter("taskListCheckMarker");
      effects.consume(code5);
      effects.exit("taskListCheckMarker");
      effects.exit("taskListCheck");
      return after;
    }
    return nok(code5);
  }
  function after(code5) {
    if (markdownLineEnding(code5)) {
      return ok3(code5);
    }
    if (markdownSpace(code5)) {
      return effects.check({ tokenize: spaceThenNonSpace }, ok3, nok)(code5);
    }
    return nok(code5);
  }
}
function spaceThenNonSpace(effects, ok3, nok) {
  return factorySpace(effects, after, types.whitespace);
  function after(code5) {
    return code5 === codes.eof ? nok(code5) : ok3(code5);
  }
}

// ../../node_modules/.pnpm/micromark-extension-gfm@3.0.0/node_modules/micromark-extension-gfm/index.js
function gfm(options2) {
  return combineExtensions([
    gfmAutolinkLiteral(),
    gfmFootnote(),
    gfmStrikethrough(options2),
    gfmTable(),
    gfmTaskListItem()
  ]);
}

// ../../node_modules/.pnpm/remark-gfm@4.0.1/node_modules/remark-gfm/lib/index.js
var emptyOptions5 = {};
function remarkGfm(options2) {
  const self2 = (
    /** @type {Processor<Root>} */
    this
  );
  const settings = options2 || emptyOptions5;
  const data = self2.data();
  const micromarkExtensions = data.micromarkExtensions || (data.micromarkExtensions = []);
  const fromMarkdownExtensions = data.fromMarkdownExtensions || (data.fromMarkdownExtensions = []);
  const toMarkdownExtensions = data.toMarkdownExtensions || (data.toMarkdownExtensions = []);
  micromarkExtensions.push(gfm(settings));
  fromMarkdownExtensions.push(gfmFromMarkdown());
  toMarkdownExtensions.push(gfmToMarkdown(settings));
}

// ../../node_modules/.pnpm/remark-stringify@11.0.0/node_modules/remark-stringify/lib/index.js
function remarkStringify(options2) {
  const self2 = this;
  self2.compiler = compiler2;
  function compiler2(tree) {
    return toMarkdown(tree, {
      ...self2.data("settings"),
      ...options2,
      // Note: this option is not in the readme.
      // The goal is for it to be set by plugins on `data` instead of being
      // passed by users.
      extensions: self2.data("toMarkdownExtensions") || []
    });
  }
}

// ../../node_modules/.pnpm/bail@2.0.2/node_modules/bail/index.js
function bail(error2) {
  if (error2) {
    throw error2;
  }
}

// ../../node_modules/.pnpm/unified@11.0.5/node_modules/unified/lib/index.js
var import_extend = __toESM(require_extend(), 1);

// ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
function isPlainObject2(value) {
  if (typeof value !== "object" || value === null) {
    return false;
  }
  const prototype = Object.getPrototypeOf(value);
  return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
}

// ../../node_modules/.pnpm/trough@2.2.0/node_modules/trough/lib/index.js
function trough() {
  const fns = [];
  const pipeline = { run: run5, use };
  return pipeline;
  function run5(...values2) {
    let middlewareIndex = -1;
    const callback = values2.pop();
    if (typeof callback !== "function") {
      throw new TypeError("Expected function as last argument, not " + callback);
    }
    next2(null, ...values2);
    function next2(error2, ...output) {
      const fn4 = fns[++middlewareIndex];
      let index4 = -1;
      if (error2) {
        callback(error2);
        return;
      }
      while (++index4 < values2.length) {
        if (output[index4] === null || output[index4] === void 0) {
          output[index4] = values2[index4];
        }
      }
      values2 = output;
      if (fn4) {
        wrap3(fn4, next2)(...output);
      } else {
        callback(null, ...output);
      }
    }
  }
  function use(middelware) {
    if (typeof middelware !== "function") {
      throw new TypeError(
        "Expected `middelware` to be a function, not " + middelware
      );
    }
    fns.push(middelware);
    return pipeline;
  }
}
function wrap3(middleware, callback) {
  let called;
  return wrapped;
  function wrapped(...parameters) {
    const fnExpectsCallback = middleware.length > parameters.length;
    let result;
    if (fnExpectsCallback) {
      parameters.push(done);
    }
    try {
      result = middleware.apply(this, parameters);
    } catch (error2) {
      const exception = (
        /** @type {Error} */
        error2
      );
      if (fnExpectsCallback && called) {
        throw exception;
      }
      return done(exception);
    }
    if (!fnExpectsCallback) {
      if (result && result.then && typeof result.then === "function") {
        result.then(then, done);
      } else if (result instanceof Error) {
        done(result);
      } else {
        then(result);
      }
    }
  }
  function done(error2, ...output) {
    if (!called) {
      called = true;
      callback(error2, ...output);
    }
  }
  function then(value) {
    done(null, value);
  }
}

// ../../node_modules/.pnpm/unified@11.0.5/node_modules/unified/lib/callable-instance.js
var CallableInstance = (
  /**
   * @type {new <Parameters extends Array<unknown>, Result>(property: string | symbol) => (...parameters: Parameters) => Result}
   */
  /** @type {unknown} */
  /**
   * @this {Function}
   * @param {string | symbol} property
   * @returns {(...parameters: Array<unknown>) => unknown}
   */
  (function(property) {
    const self2 = this;
    const constr = self2.constructor;
    const proto2 = (
      /** @type {Record<string | symbol, Function>} */
      // Prototypes do exist.
      // type-coverage:ignore-next-line
      constr.prototype
    );
    const value = proto2[property];
    const apply2 = function() {
      return value.apply(apply2, arguments);
    };
    Object.setPrototypeOf(apply2, proto2);
    return apply2;
  })
);

// ../../node_modules/.pnpm/unified@11.0.5/node_modules/unified/lib/index.js
var own7 = {}.hasOwnProperty;
var Processor = class _Processor extends CallableInstance {
  /**
   * Create a processor.
   */
  constructor() {
    super("copy");
    this.Compiler = void 0;
    this.Parser = void 0;
    this.attachers = [];
    this.compiler = void 0;
    this.freezeIndex = -1;
    this.frozen = void 0;
    this.namespace = {};
    this.parser = void 0;
    this.transformers = trough();
  }
  /**
   * Copy a processor.
   *
   * @deprecated
   *   This is a private internal method and should not be used.
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *   New *unfrozen* processor ({@linkcode Processor}) that is
   *   configured to work the same as its ancestor.
   *   When the descendant processor is configured in the future it does not
   *   affect the ancestral processor.
   */
  copy() {
    const destination = (
      /** @type {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>} */
      new _Processor()
    );
    let index4 = -1;
    while (++index4 < this.attachers.length) {
      const attacher = this.attachers[index4];
      destination.use(...attacher);
    }
    destination.data((0, import_extend.default)(true, {}, this.namespace));
    return destination;
  }
  /**
   * Configure the processor with info available to all plugins.
   * Information is stored in an object.
   *
   * Typically, options can be given to a specific plugin, but sometimes it
   * makes sense to have information shared with several plugins.
   * For example, a list of HTML elements that are self-closing, which is
   * needed during all phases.
   *
   * > **Note**: setting information cannot occur on *frozen* processors.
   * > Call the processor first to create a new unfrozen processor.
   *
   * > **Note**: to register custom data in TypeScript, augment the
   * > {@linkcode Data} interface.
   *
   * @example
   *   This example show how to get and set info:
   *
   *   ```js
   *   import {unified} from 'unified'
   *
   *   const processor = unified().data('alpha', 'bravo')
   *
   *   processor.data('alpha') // => 'bravo'
   *
   *   processor.data() // => {alpha: 'bravo'}
   *
   *   processor.data({charlie: 'delta'})
   *
   *   processor.data() // => {charlie: 'delta'}
   *   ```
   *
   * @template {keyof Data} Key
   *
   * @overload
   * @returns {Data}
   *
   * @overload
   * @param {Data} dataset
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *
   * @overload
   * @param {Key} key
   * @returns {Data[Key]}
   *
   * @overload
   * @param {Key} key
   * @param {Data[Key]} value
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *
   * @param {Data | Key} [key]
   *   Key to get or set, or entire dataset to set, or nothing to get the
   *   entire dataset (optional).
   * @param {Data[Key]} [value]
   *   Value to set (optional).
   * @returns {unknown}
   *   The current processor when setting, the value at `key` when getting, or
   *   the entire dataset when getting without key.
   */
  data(key2, value) {
    if (typeof key2 === "string") {
      if (arguments.length === 2) {
        assertUnfrozen("data", this.frozen);
        this.namespace[key2] = value;
        return this;
      }
      return own7.call(this.namespace, key2) && this.namespace[key2] || void 0;
    }
    if (key2) {
      assertUnfrozen("data", this.frozen);
      this.namespace = key2;
      return this;
    }
    return this.namespace;
  }
  /**
   * Freeze a processor.
   *
   * Frozen processors are meant to be extended and not to be configured
   * directly.
   *
   * When a processor is frozen it cannot be unfrozen.
   * New processors working the same way can be created by calling the
   * processor.
   *
   * It’s possible to freeze processors explicitly by calling `.freeze()`.
   * Processors freeze automatically when `.parse()`, `.run()`, `.runSync()`,
   * `.stringify()`, `.process()`, or `.processSync()` are called.
   *
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *   The current processor.
   */
  freeze() {
    if (this.frozen) {
      return this;
    }
    const self2 = (
      /** @type {Processor} */
      /** @type {unknown} */
      this
    );
    while (++this.freezeIndex < this.attachers.length) {
      const [attacher, ...options2] = this.attachers[this.freezeIndex];
      if (options2[0] === false) {
        continue;
      }
      if (options2[0] === true) {
        options2[0] = void 0;
      }
      const transformer = attacher.call(self2, ...options2);
      if (typeof transformer === "function") {
        this.transformers.use(transformer);
      }
    }
    this.frozen = true;
    this.freezeIndex = Number.POSITIVE_INFINITY;
    return this;
  }
  /**
   * Parse text to a syntax tree.
   *
   * > **Note**: `parse` freezes the processor if not already *frozen*.
   *
   * > **Note**: `parse` performs the parse phase, not the run phase or other
   * > phases.
   *
   * @param {Compatible | undefined} [file]
   *   file to parse (optional); typically `string` or `VFile`; any value
   *   accepted as `x` in `new VFile(x)`.
   * @returns {ParseTree extends undefined ? Node : ParseTree}
   *   Syntax tree representing `file`.
   */
  parse(file) {
    this.freeze();
    const realFile = vfile(file);
    const parser = this.parser || this.Parser;
    assertParser("parse", parser);
    return parser(String(realFile), realFile);
  }
  /**
   * Process the given file as configured on the processor.
   *
   * > **Note**: `process` freezes the processor if not already *frozen*.
   *
   * > **Note**: `process` performs the parse, run, and stringify phases.
   *
   * @overload
   * @param {Compatible | undefined} file
   * @param {ProcessCallback<VFileWithOutput<CompileResult>>} done
   * @returns {undefined}
   *
   * @overload
   * @param {Compatible | undefined} [file]
   * @returns {Promise<VFileWithOutput<CompileResult>>}
   *
   * @param {Compatible | undefined} [file]
   *   File (optional); typically `string` or `VFile`]; any value accepted as
   *   `x` in `new VFile(x)`.
   * @param {ProcessCallback<VFileWithOutput<CompileResult>> | undefined} [done]
   *   Callback (optional).
   * @returns {Promise<VFile> | undefined}
   *   Nothing if `done` is given.
   *   Otherwise a promise, rejected with a fatal error or resolved with the
   *   processed file.
   *
   *   The parsed, transformed, and compiled value is available at
   *   `file.value` (see note).
   *
   *   > **Note**: unified typically compiles by serializing: most
   *   > compilers return `string` (or `Uint8Array`).
   *   > Some compilers, such as the one configured with
   *   > [`rehype-react`][rehype-react], return other values (in this case, a
   *   > React tree).
   *   > If you’re using a compiler that doesn’t serialize, expect different
   *   > result values.
   *   >
   *   > To register custom results in TypeScript, add them to
   *   > {@linkcode CompileResultMap}.
   *
   *   [rehype-react]: https://github.com/rehypejs/rehype-react
   */
  process(file, done) {
    const self2 = this;
    this.freeze();
    assertParser("process", this.parser || this.Parser);
    assertCompiler("process", this.compiler || this.Compiler);
    return done ? executor(void 0, done) : new Promise(executor);
    function executor(resolve2, reject) {
      const realFile = vfile(file);
      const parseTree = (
        /** @type {HeadTree extends undefined ? Node : HeadTree} */
        /** @type {unknown} */
        self2.parse(realFile)
      );
      self2.run(parseTree, realFile, function(error2, tree, file2) {
        if (error2 || !tree || !file2) {
          return realDone(error2);
        }
        const compileTree = (
          /** @type {CompileTree extends undefined ? Node : CompileTree} */
          /** @type {unknown} */
          tree
        );
        const compileResult = self2.stringify(compileTree, file2);
        if (looksLikeAValue(compileResult)) {
          file2.value = compileResult;
        } else {
          file2.result = compileResult;
        }
        realDone(
          error2,
          /** @type {VFileWithOutput<CompileResult>} */
          file2
        );
      });
      function realDone(error2, file2) {
        if (error2 || !file2) {
          reject(error2);
        } else if (resolve2) {
          resolve2(file2);
        } else {
          ok(done, "`done` is defined if `resolve` is not");
          done(void 0, file2);
        }
      }
    }
  }
  /**
   * Process the given file as configured on the processor.
   *
   * An error is thrown if asynchronous transforms are configured.
   *
   * > **Note**: `processSync` freezes the processor if not already *frozen*.
   *
   * > **Note**: `processSync` performs the parse, run, and stringify phases.
   *
   * @param {Compatible | undefined} [file]
   *   File (optional); typically `string` or `VFile`; any value accepted as
   *   `x` in `new VFile(x)`.
   * @returns {VFileWithOutput<CompileResult>}
   *   The processed file.
   *
   *   The parsed, transformed, and compiled value is available at
   *   `file.value` (see note).
   *
   *   > **Note**: unified typically compiles by serializing: most
   *   > compilers return `string` (or `Uint8Array`).
   *   > Some compilers, such as the one configured with
   *   > [`rehype-react`][rehype-react], return other values (in this case, a
   *   > React tree).
   *   > If you’re using a compiler that doesn’t serialize, expect different
   *   > result values.
   *   >
   *   > To register custom results in TypeScript, add them to
   *   > {@linkcode CompileResultMap}.
   *
   *   [rehype-react]: https://github.com/rehypejs/rehype-react
   */
  processSync(file) {
    let complete = false;
    let result;
    this.freeze();
    assertParser("processSync", this.parser || this.Parser);
    assertCompiler("processSync", this.compiler || this.Compiler);
    this.process(file, realDone);
    assertDone("processSync", "process", complete);
    ok(result, "we either bailed on an error or have a tree");
    return result;
    function realDone(error2, file2) {
      complete = true;
      bail(error2);
      result = file2;
    }
  }
  /**
   * Run *transformers* on a syntax tree.
   *
   * > **Note**: `run` freezes the processor if not already *frozen*.
   *
   * > **Note**: `run` performs the run phase, not other phases.
   *
   * @overload
   * @param {HeadTree extends undefined ? Node : HeadTree} tree
   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done
   * @returns {undefined}
   *
   * @overload
   * @param {HeadTree extends undefined ? Node : HeadTree} tree
   * @param {Compatible | undefined} file
   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done
   * @returns {undefined}
   *
   * @overload
   * @param {HeadTree extends undefined ? Node : HeadTree} tree
   * @param {Compatible | undefined} [file]
   * @returns {Promise<TailTree extends undefined ? Node : TailTree>}
   *
   * @param {HeadTree extends undefined ? Node : HeadTree} tree
   *   Tree to transform and inspect.
   * @param {(
   *   RunCallback<TailTree extends undefined ? Node : TailTree> |
   *   Compatible
   * )} [file]
   *   File associated with `node` (optional); any value accepted as `x` in
   *   `new VFile(x)`.
   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} [done]
   *   Callback (optional).
   * @returns {Promise<TailTree extends undefined ? Node : TailTree> | undefined}
   *   Nothing if `done` is given.
   *   Otherwise, a promise rejected with a fatal error or resolved with the
   *   transformed tree.
   */
  run(tree, file, done) {
    assertNode(tree);
    this.freeze();
    const transformers = this.transformers;
    if (!done && typeof file === "function") {
      done = file;
      file = void 0;
    }
    return done ? executor(void 0, done) : new Promise(executor);
    function executor(resolve2, reject) {
      ok(
        typeof file !== "function",
        "`file` can’t be a `done` anymore, we checked"
      );
      const realFile = vfile(file);
      transformers.run(tree, realFile, realDone);
      function realDone(error2, outputTree, file2) {
        const resultingTree = (
          /** @type {TailTree extends undefined ? Node : TailTree} */
          outputTree || tree
        );
        if (error2) {
          reject(error2);
        } else if (resolve2) {
          resolve2(resultingTree);
        } else {
          ok(done, "`done` is defined if `resolve` is not");
          done(void 0, resultingTree, file2);
        }
      }
    }
  }
  /**
   * Run *transformers* on a syntax tree.
   *
   * An error is thrown if asynchronous transforms are configured.
   *
   * > **Note**: `runSync` freezes the processor if not already *frozen*.
   *
   * > **Note**: `runSync` performs the run phase, not other phases.
   *
   * @param {HeadTree extends undefined ? Node : HeadTree} tree
   *   Tree to transform and inspect.
   * @param {Compatible | undefined} [file]
   *   File associated with `node` (optional); any value accepted as `x` in
   *   `new VFile(x)`.
   * @returns {TailTree extends undefined ? Node : TailTree}
   *   Transformed tree.
   */
  runSync(tree, file) {
    let complete = false;
    let result;
    this.run(tree, file, realDone);
    assertDone("runSync", "run", complete);
    ok(result, "we either bailed on an error or have a tree");
    return result;
    function realDone(error2, tree2) {
      bail(error2);
      result = tree2;
      complete = true;
    }
  }
  /**
   * Compile a syntax tree.
   *
   * > **Note**: `stringify` freezes the processor if not already *frozen*.
   *
   * > **Note**: `stringify` performs the stringify phase, not the run phase
   * > or other phases.
   *
   * @param {CompileTree extends undefined ? Node : CompileTree} tree
   *   Tree to compile.
   * @param {Compatible | undefined} [file]
   *   File associated with `node` (optional); any value accepted as `x` in
   *   `new VFile(x)`.
   * @returns {CompileResult extends undefined ? Value : CompileResult}
   *   Textual representation of the tree (see note).
   *
   *   > **Note**: unified typically compiles by serializing: most compilers
   *   > return `string` (or `Uint8Array`).
   *   > Some compilers, such as the one configured with
   *   > [`rehype-react`][rehype-react], return other values (in this case, a
   *   > React tree).
   *   > If you’re using a compiler that doesn’t serialize, expect different
   *   > result values.
   *   >
   *   > To register custom results in TypeScript, add them to
   *   > {@linkcode CompileResultMap}.
   *
   *   [rehype-react]: https://github.com/rehypejs/rehype-react
   */
  stringify(tree, file) {
    this.freeze();
    const realFile = vfile(file);
    const compiler2 = this.compiler || this.Compiler;
    assertCompiler("stringify", compiler2);
    assertNode(tree);
    return compiler2(tree, realFile);
  }
  /**
   * Configure the processor to use a plugin, a list of usable values, or a
   * preset.
   *
   * If the processor is already using a plugin, the previous plugin
   * configuration is changed based on the options that are passed in.
   * In other words, the plugin is not added a second time.
   *
   * > **Note**: `use` cannot be called on *frozen* processors.
   * > Call the processor first to create a new unfrozen processor.
   *
   * @example
   *   There are many ways to pass plugins to `.use()`.
   *   This example gives an overview:
   *
   *   ```js
   *   import {unified} from 'unified'
   *
   *   unified()
   *     // Plugin with options:
   *     .use(pluginA, {x: true, y: true})
   *     // Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`):
   *     .use(pluginA, {y: false, z: true})
   *     // Plugins:
   *     .use([pluginB, pluginC])
   *     // Two plugins, the second with options:
   *     .use([pluginD, [pluginE, {}]])
   *     // Preset with plugins and settings:
   *     .use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})
   *     // Settings only:
   *     .use({settings: {position: false}})
   *   ```
   *
   * @template {Array<unknown>} [Parameters=[]]
   * @template {Node | string | undefined} [Input=undefined]
   * @template [Output=Input]
   *
   * @overload
   * @param {Preset | null | undefined} [preset]
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *
   * @overload
   * @param {PluggableList} list
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *
   * @overload
   * @param {Plugin<Parameters, Input, Output>} plugin
   * @param {...(Parameters | [boolean])} parameters
   * @returns {UsePlugin<ParseTree, HeadTree, TailTree, CompileTree, CompileResult, Input, Output>}
   *
   * @param {PluggableList | Plugin | Preset | null | undefined} value
   *   Usable value.
   * @param {...unknown} parameters
   *   Parameters, when a plugin is given as a usable value.
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *   Current processor.
   */
  use(value, ...parameters) {
    const attachers = this.attachers;
    const namespace = this.namespace;
    assertUnfrozen("use", this.frozen);
    if (value === null || value === void 0) {
    } else if (typeof value === "function") {
      addPlugin(value, parameters);
    } else if (typeof value === "object") {
      if (Array.isArray(value)) {
        addList(value);
      } else {
        addPreset(value);
      }
    } else {
      throw new TypeError("Expected usable value, not `" + value + "`");
    }
    return this;
    function add(value2) {
      if (typeof value2 === "function") {
        addPlugin(value2, []);
      } else if (typeof value2 === "object") {
        if (Array.isArray(value2)) {
          const [plugin, ...parameters2] = (
            /** @type {PluginTuple<Array<unknown>>} */
            value2
          );
          addPlugin(plugin, parameters2);
        } else {
          addPreset(value2);
        }
      } else {
        throw new TypeError("Expected usable value, not `" + value2 + "`");
      }
    }
    function addPreset(result) {
      if (!("plugins" in result) && !("settings" in result)) {
        throw new Error(
          "Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither"
        );
      }
      addList(result.plugins);
      if (result.settings) {
        namespace.settings = (0, import_extend.default)(true, namespace.settings, result.settings);
      }
    }
    function addList(plugins) {
      let index4 = -1;
      if (plugins === null || plugins === void 0) {
      } else if (Array.isArray(plugins)) {
        while (++index4 < plugins.length) {
          const thing = plugins[index4];
          add(thing);
        }
      } else {
        throw new TypeError("Expected a list of plugins, not `" + plugins + "`");
      }
    }
    function addPlugin(plugin, parameters2) {
      let index4 = -1;
      let entryIndex = -1;
      while (++index4 < attachers.length) {
        if (attachers[index4][0] === plugin) {
          entryIndex = index4;
          break;
        }
      }
      if (entryIndex === -1) {
        attachers.push([plugin, ...parameters2]);
      } else if (parameters2.length > 0) {
        let [primary, ...rest] = parameters2;
        const currentPrimary = attachers[entryIndex][1];
        if (isPlainObject2(currentPrimary) && isPlainObject2(primary)) {
          primary = (0, import_extend.default)(true, currentPrimary, primary);
        }
        attachers[entryIndex] = [plugin, primary, ...rest];
      }
    }
  }
};
var unified = new Processor().freeze();
function assertParser(name, value) {
  if (typeof value !== "function") {
    throw new TypeError("Cannot `" + name + "` without `parser`");
  }
}
function assertCompiler(name, value) {
  if (typeof value !== "function") {
    throw new TypeError("Cannot `" + name + "` without `compiler`");
  }
}
function assertUnfrozen(name, frozen) {
  if (frozen) {
    throw new Error(
      "Cannot call `" + name + "` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`."
    );
  }
}
function assertNode(node2) {
  if (!isPlainObject2(node2) || typeof node2.type !== "string") {
    throw new TypeError("Expected node, got `" + node2 + "`");
  }
}
function assertDone(name, asyncName, complete) {
  if (!complete) {
    throw new Error(
      "`" + name + "` finished async. Use `" + asyncName + "` instead"
    );
  }
}
function vfile(value) {
  return looksLikeAVFile(value) ? value : new VFile(value);
}
function looksLikeAVFile(value) {
  return Boolean(
    value && typeof value === "object" && "message" in value && "messages" in value
  );
}
function looksLikeAValue(value) {
  return typeof value === "string" || isUint8Array2(value);
}
function isUint8Array2(value) {
  return Boolean(
    value && typeof value === "object" && "byteLength" in value && "byteOffset" in value
  );
}

// ../../node_modules/.pnpm/hast-util-from-dom@5.0.1/node_modules/hast-util-from-dom/lib/index.js
function fromDom(tree, options2) {
  return transform(tree, options2 || {}) || { type: "root", children: [] };
}
function transform(node2, options2) {
  const transformed = one4(node2, options2);
  if (transformed && options2.afterTransform)
    options2.afterTransform(node2, transformed);
  return transformed;
}
function one4(node2, options2) {
  switch (node2.nodeType) {
    case 1: {
      const domNode = (
        /** @type {Element} */
        node2
      );
      return element5(domNode, options2);
    }
    // Ignore: Attr (2).
    case 3: {
      const domNode = (
        /** @type {Text} */
        node2
      );
      return text5(domNode);
    }
    // Ignore: CDATA (4).
    // Removed: Entity reference (5)
    // Removed: Entity (6)
    // Ignore: Processing instruction (7).
    case 8: {
      const domNode = (
        /** @type {Comment} */
        node2
      );
      return comment2(domNode);
    }
    case 9: {
      const domNode = (
        /** @type {Document} */
        node2
      );
      return root3(domNode, options2);
    }
    case 10: {
      return doctype();
    }
    case 11: {
      const domNode = (
        /** @type {DocumentFragment} */
        node2
      );
      return root3(domNode, options2);
    }
    default: {
      return void 0;
    }
  }
}
function root3(node2, options2) {
  return { type: "root", children: all7(node2, options2) };
}
function doctype() {
  return { type: "doctype" };
}
function text5(node2) {
  return { type: "text", value: node2.nodeValue || "" };
}
function comment2(node2) {
  return { type: "comment", value: node2.nodeValue || "" };
}
function element5(node2, options2) {
  const space2 = node2.namespaceURI;
  const x5 = space2 === webNamespaces.svg ? s : h4;
  const tagName = space2 === webNamespaces.html ? node2.tagName.toLowerCase() : node2.tagName;
  const content5 = (
    // @ts-expect-error: DOM types are wrong, content can exist.
    space2 === webNamespaces.html && tagName === "template" ? node2.content : node2
  );
  const attributes = node2.getAttributeNames();
  const properties = {};
  let index4 = -1;
  while (++index4 < attributes.length) {
    properties[attributes[index4]] = node2.getAttribute(attributes[index4]) || "";
  }
  return x5(tagName, properties, all7(content5, options2));
}
function all7(node2, options2) {
  const nodes = node2.childNodes;
  const children = [];
  let index4 = -1;
  while (++index4 < nodes.length) {
    const child = transform(nodes[index4], options2);
    if (child !== void 0) {
      children.push(child);
    }
  }
  return children;
}

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/TrailingNode-8cXFaQUm.js
var Ee = Object.defineProperty;
var Ie2 = (n, e2, t2) => e2 in n ? Ee(n, e2, { enumerable: true, configurable: true, writable: true, value: t2 }) : n[e2] = t2;
var b3 = (n, e2, t2) => Ie2(n, typeof e2 != "symbol" ? e2 + "" : e2, t2);
function we(n) {
  const e2 = Array.from(n.classList).filter(
    (t2) => !t2.startsWith("bn-")
  ) || [];
  e2.length > 0 ? n.className = e2.join(" ") : n.removeAttribute("class");
}
function ye(n, e2, t2, o2) {
  var a3;
  let r4;
  if (e2)
    if (typeof e2 == "string")
      r4 = T([e2], n.pmSchema);
    else if (Array.isArray(e2))
      r4 = T(e2, n.pmSchema);
    else if (e2.type === "tableContent")
      r4 = kt(e2, n.pmSchema);
    else
      throw new O(e2.type);
  else throw new Error("blockContent is required");
  const i3 = ((o2 == null ? void 0 : o2.document) ?? document).createDocumentFragment();
  for (const c3 of r4)
    if (c3.type.name !== "text" && n.schema.inlineContentSchema[c3.type.name]) {
      const l2 = n.schema.inlineContentSpecs[c3.type.name].implementation;
      if (l2) {
        const m2 = wt(
          c3,
          n.schema.inlineContentSchema,
          n.schema.styleSchema
        ), h7 = l2.toExternalHTML ? l2.toExternalHTML(
          m2,
          n
        ) : l2.render.call(
          {
            renderType: "dom",
            props: void 0
          },
          m2,
          () => {
          },
          n
        );
        if (h7) {
          if (i3.appendChild(h7.dom), h7.contentDOM) {
            const f6 = t2.serializeFragment(
              c3.content,
              o2
            );
            h7.contentDOM.dataset.editable = "", h7.contentDOM.appendChild(f6);
          }
          continue;
        }
      }
    } else if (c3.type.name === "text") {
      let l2 = document.createTextNode(
        c3.textContent
      );
      for (const m2 of c3.marks.toReversed())
        if (m2.type.name in n.schema.styleSpecs) {
          const h7 = (n.schema.styleSpecs[m2.type.name].implementation.toExternalHTML ?? n.schema.styleSpecs[m2.type.name].implementation.render)(m2.attrs.stringValue, n);
          h7.contentDOM.appendChild(l2), l2 = h7.dom;
        } else {
          const h7 = m2.type.spec.toDOM(m2, true), f6 = DOMSerializer.renderSpec(document, h7);
          f6.contentDOM.appendChild(l2), l2 = f6.dom;
        }
      i3.appendChild(l2);
    } else {
      const l2 = t2.serializeFragment(
        Fragment.from([c3]),
        o2
      );
      i3.appendChild(l2);
    }
  return i3.childNodes.length === 1 && ((a3 = i3.firstChild) == null ? void 0 : a3.nodeType) === 1 && we(i3.firstChild), i3;
}
function yt3(n, e2, t2, o2, r4, s2, i3) {
  var p4, w3, y3, E4, O2, _2, z2, K6, Y5;
  const a3 = (i3 == null ? void 0 : i3.document) ?? document, c3 = e2.pmSchema.nodes.blockContainer, l2 = t2.props || {};
  for (const [v8, S4] of Object.entries(
    e2.schema.blockSchema[t2.type].propSchema
  ))
    !(v8 in l2) && S4.default !== void 0 && (l2[v8] = S4.default);
  const m2 = (w3 = (p4 = c3.spec) == null ? void 0 : p4.toDOM) == null ? void 0 : w3.call(
    p4,
    c3.create({
      id: t2.id,
      ...l2
    })
  ), h7 = Array.from(m2.dom.attributes), f6 = e2.blockImplementations[t2.type].implementation, u2 = ((y3 = f6.toExternalHTML) == null ? void 0 : y3.call(
    {},
    { ...t2, props: l2 },
    e2
  )) || f6.render.call(
    {},
    { ...t2, props: l2 },
    e2
  ), g = a3.createDocumentFragment();
  if (u2.dom.classList.contains("bn-block-content")) {
    const v8 = [
      ...h7,
      ...Array.from(u2.dom.attributes)
    ].filter(
      (S4) => S4.name.startsWith("data") && S4.name !== "data-content-type" && S4.name !== "data-file-block" && S4.name !== "data-node-view-wrapper" && S4.name !== "data-node-type" && S4.name !== "data-id" && S4.name !== "data-editable"
    );
    for (const S4 of v8)
      u2.dom.firstChild.setAttribute(S4.name, S4.value);
    we(u2.dom.firstChild), g.append(...Array.from(u2.dom.childNodes));
  } else
    g.append(u2.dom);
  if (u2.contentDOM && t2.content) {
    const v8 = ye(
      e2,
      t2.content,
      // TODO
      o2,
      i3
    );
    u2.contentDOM.appendChild(v8);
  }
  let d;
  if (r4.has(t2.type) ? d = "OL" : s2.has(t2.type) && (d = "UL"), d) {
    if (((E4 = n.lastChild) == null ? void 0 : E4.nodeName) !== d) {
      const v8 = a3.createElement(d);
      d === "OL" && "start" in l2 && l2.start && (l2 == null ? void 0 : l2.start) !== 1 && v8.setAttribute("start", l2.start + ""), n.append(v8);
    }
    n.lastChild.appendChild(g);
  } else
    n.append(g);
  if (t2.children && t2.children.length > 0) {
    const v8 = a3.createDocumentFragment();
    if (be(
      v8,
      e2,
      t2.children,
      o2,
      r4,
      s2,
      i3
    ), ((O2 = n.lastChild) == null ? void 0 : O2.nodeName) === "UL" || ((_2 = n.lastChild) == null ? void 0 : _2.nodeName) === "OL")
      for (; ((z2 = v8.firstChild) == null ? void 0 : z2.nodeName) === "UL" || ((K6 = v8.firstChild) == null ? void 0 : K6.nodeName) === "OL"; )
        n.lastChild.lastChild.appendChild(v8.firstChild);
    e2.pmSchema.nodes[t2.type].isInGroup("blockContent") ? n.append(v8) : (Y5 = u2.contentDOM) == null || Y5.append(v8);
  }
}
var be = (n, e2, t2, o2, r4, s2, i3) => {
  for (const a3 of t2)
    yt3(
      n,
      e2,
      a3,
      o2,
      r4,
      s2,
      i3
    );
};
var bt3 = (n, e2, t2, o2, r4, s2) => {
  const a3 = ((s2 == null ? void 0 : s2.document) ?? document).createDocumentFragment();
  return be(
    a3,
    n,
    e2,
    t2,
    o2,
    r4,
    s2
  ), a3;
};
var ve = (n, e2) => {
  const t2 = DOMSerializer.fromSchema(n);
  return {
    exportBlocks: (o2, r4) => {
      const s2 = bt3(
        e2,
        o2,
        t2,
        /* @__PURE__ */ new Set(["numberedListItem"]),
        /* @__PURE__ */ new Set(["bulletListItem", "checkListItem", "toggleListItem"]),
        r4
      ), i3 = document.createElement("div");
      return i3.append(s2), i3.innerHTML;
    },
    exportInlineContent: (o2, r4) => {
      const s2 = ye(
        e2,
        o2,
        t2,
        r4
      ), i3 = document.createElement("div");
      return i3.append(s2.cloneNode(true)), i3.innerHTML;
    }
  };
};
function vt2(n, e2) {
  if (e2 === 0)
    return;
  const t2 = n.resolve(e2);
  for (let o2 = t2.depth; o2 > 0; o2--) {
    const r4 = t2.node(o2);
    if (Bt(r4))
      return r4.attrs.id;
  }
}
function kt3(n) {
  return n.getMeta("paste") ? { type: "paste" } : n.getMeta("uiEvent") === "drop" ? { type: "drop" } : n.getMeta("history$") ? {
    type: n.getMeta("history$").redo ? "redo" : "undo"
  } : n.getMeta("y-sync$") ? n.getMeta("y-sync$").isUndoRedoOperation ? { type: "undo-redo" } : { type: "yjs-remote" } : { type: "local" };
}
function Z3(n) {
  const e2 = "__root__", t2 = {}, o2 = {}, r4 = ht(n);
  return n.descendants((s2, i3) => {
    if (!Bt(s2))
      return true;
    const a3 = vt2(n, i3), c3 = a3 ?? e2;
    o2[c3] || (o2[c3] = []);
    const l2 = L(s2, r4);
    return t2[s2.attrs.id] = { block: l2, parentId: a3 }, o2[c3].push(s2.attrs.id), true;
  }), { byId: t2, childrenByParent: o2 };
}
function Ct3(n, e2) {
  const t2 = /* @__PURE__ */ new Set();
  if (!n || !e2)
    return t2;
  const o2 = new Set(n), r4 = e2.filter((d) => o2.has(d)), s2 = n.filter(
    (d) => r4.includes(d)
  );
  if (s2.length <= 1 || r4.length <= 1)
    return t2;
  const i3 = {};
  for (let d = 0; d < s2.length; d++)
    i3[s2[d]] = d;
  const a3 = r4.map((d) => i3[d]), c3 = a3.length, l2 = [], m2 = [], h7 = new Array(c3).fill(-1), f6 = (d, p4) => {
    let w3 = 0, y3 = d.length;
    for (; w3 < y3; ) {
      const E4 = w3 + y3 >>> 1;
      d[E4] < p4 ? w3 = E4 + 1 : y3 = E4;
    }
    return w3;
  };
  for (let d = 0; d < c3; d++) {
    const p4 = a3[d], w3 = f6(l2, p4);
    w3 > 0 && (h7[d] = m2[w3 - 1]), w3 === l2.length ? (l2.push(p4), m2.push(d)) : (l2[w3] = p4, m2[w3] = d);
  }
  const u2 = /* @__PURE__ */ new Set();
  let g = m2[m2.length - 1] ?? -1;
  for (; g !== -1; )
    u2.add(g), g = h7[g];
  for (let d = 0; d < r4.length; d++)
    u2.has(d) || t2.add(r4[d]);
  return t2;
}
function St3(n, e2 = []) {
  const t2 = kt3(n), o2 = combineTransactionSteps(n.before, [
    n,
    ...e2
  ]), r4 = Z3(
    o2.before
  ), s2 = Z3(
    o2.doc
  ), i3 = [], a3 = /* @__PURE__ */ new Set();
  Object.keys(s2.byId).filter((u2) => !(u2 in r4.byId)).forEach((u2) => {
    i3.push({
      type: "insert",
      block: s2.byId[u2].block,
      source: t2,
      prevBlock: void 0
    }), a3.add(u2);
  }), Object.keys(r4.byId).filter((u2) => !(u2 in s2.byId)).forEach((u2) => {
    i3.push({
      type: "delete",
      block: r4.byId[u2].block,
      source: t2,
      prevBlock: void 0
    }), a3.add(u2);
  }), Object.keys(s2.byId).filter((u2) => u2 in r4.byId).forEach((u2) => {
    var w3, y3;
    const g = r4.byId[u2], d = s2.byId[u2];
    g.parentId !== d.parentId ? (i3.push({
      type: "move",
      block: d.block,
      prevBlock: g.block,
      source: t2,
      prevParent: g.parentId ? (w3 = r4.byId[g.parentId]) == null ? void 0 : w3.block : void 0,
      currentParent: d.parentId ? (y3 = s2.byId[d.parentId]) == null ? void 0 : y3.block : void 0
    }), a3.add(u2)) : (0, import_fast_deep_equal.default)(
      { ...g.block, children: void 0 },
      { ...d.block, children: void 0 }
    ) || (i3.push({
      type: "update",
      block: d.block,
      prevBlock: g.block,
      source: t2
    }), a3.add(u2));
  });
  const c3 = r4.childrenByParent, l2 = s2.childrenByParent, m2 = "__root__", h7 = /* @__PURE__ */ new Set([
    ...Object.keys(c3),
    ...Object.keys(l2)
  ]), f6 = /* @__PURE__ */ new Set();
  return h7.forEach((u2) => {
    const g = Ct3(
      c3[u2],
      l2[u2]
    );
    g.size !== 0 && g.forEach((d) => {
      var E4, O2;
      const p4 = r4.byId[d], w3 = s2.byId[d];
      !p4 || !w3 || p4.parentId !== w3.parentId || a3.has(d) || (p4.parentId ?? m2) !== u2 || f6.has(d) || (f6.add(d), i3.push({
        type: "move",
        block: w3.block,
        prevBlock: p4.block,
        source: t2,
        prevParent: p4.parentId ? (E4 = r4.byId[p4.parentId]) == null ? void 0 : E4.block : void 0,
        currentParent: w3.parentId ? (O2 = s2.byId[w3.parentId]) == null ? void 0 : O2.block : void 0
      }), a3.add(d));
    });
  }), i3;
}
var po2 = a(() => {
  const n = [];
  return {
    key: "blockChange",
    prosemirrorPlugins: [
      new Plugin({
        key: new PluginKey("blockChange"),
        filterTransaction: (e2) => {
          let t2;
          return n.reduce((o2, r4) => o2 === false ? o2 : r4({
            getChanges() {
              return t2 || (t2 = St3(e2), t2);
            },
            tr: e2
          }) !== false, true);
        }
      })
    ],
    /**
     * Subscribe to the block change events.
     */
    subscribe(e2) {
      return n.push(e2), () => {
        n.splice(
          n.indexOf(e2),
          1
        );
      };
    }
  };
});
function ee(n) {
  const e2 = n.charAt(0) === "#" ? n.substring(1, 7) : n, t2 = parseInt(e2.substring(0, 2), 16), o2 = parseInt(e2.substring(2, 4), 16), r4 = parseInt(e2.substring(4, 6), 16), i3 = [t2 / 255, o2 / 255, r4 / 255].map((c3) => c3 <= 0.03928 ? c3 / 12.92 : Math.pow((c3 + 0.055) / 1.055, 2.4));
  return 0.2126 * i3[0] + 0.7152 * i3[1] + 0.0722 * i3[2] <= 0.179;
}
function xt2(n) {
  const e2 = document.createElement("span");
  e2.classList.add("bn-collaboration-cursor__base");
  const t2 = document.createElement("span");
  t2.setAttribute("contentedEditable", "false"), t2.classList.add("bn-collaboration-cursor__caret"), t2.setAttribute(
    "style",
    `background-color: ${n.color}; color: ${ee(n.color) ? "white" : "black"}`
  );
  const o2 = document.createElement("span");
  return o2.classList.add("bn-collaboration-cursor__label"), o2.setAttribute(
    "style",
    `background-color: ${n.color}; color: ${ee(n.color) ? "white" : "black"}`
  ), o2.insertBefore(document.createTextNode(n.name), null), t2.insertBefore(o2, null), e2.insertBefore(document.createTextNode("⁠"), null), e2.insertBefore(t2, null), e2.insertBefore(document.createTextNode("⁠"), null), e2;
}
var te = a(
  ({ options: n }) => {
    const e2 = /* @__PURE__ */ new Map(), t2 = n.provider && "awareness" in n.provider && typeof n.provider.awareness == "object" ? n.provider.awareness : void 0;
    return t2 && ("setLocalStateField" in t2 && typeof t2.setLocalStateField == "function" && t2.setLocalStateField("user", n.user), "on" in t2 && typeof t2.on == "function" && n.showCursorLabels !== "always" && t2.on(
      "change",
      ({
        updated: o2
      }) => {
        for (const r4 of o2) {
          const s2 = e2.get(r4);
          s2 && (s2.element.setAttribute("data-active", ""), s2.hideTimeout && clearTimeout(s2.hideTimeout), e2.set(r4, {
            element: s2.element,
            hideTimeout: setTimeout(() => {
              s2.element.removeAttribute("data-active");
            }, 2e3)
          }));
        }
      }
    )), {
      key: "yCursor",
      prosemirrorPlugins: [
        t2 ? yCursorPlugin(t2, {
          selectionBuilder: defaultSelectionBuilder,
          cursorBuilder(o2, r4) {
            let s2 = e2.get(r4);
            if (!s2) {
              const i3 = (n.renderCursor ?? xt2)(o2);
              n.showCursorLabels !== "always" && (i3.addEventListener("mouseenter", () => {
                const a3 = e2.get(r4);
                a3.element.setAttribute("data-active", ""), a3.hideTimeout && (clearTimeout(a3.hideTimeout), e2.set(r4, {
                  element: a3.element,
                  hideTimeout: void 0
                }));
              }), i3.addEventListener("mouseleave", () => {
                const a3 = e2.get(r4);
                e2.set(r4, {
                  element: a3.element,
                  hideTimeout: setTimeout(() => {
                    a3.element.removeAttribute("data-active");
                  }, 2e3)
                });
              })), s2 = {
                element: i3,
                hideTimeout: void 0
              }, e2.set(r4, s2);
            }
            return s2.element;
          }
        }) : void 0
      ].filter(Boolean),
      dependsOn: ["ySync"],
      updateUser(o2) {
        t2 == null || t2.setLocalStateField("user", o2);
      }
    };
  }
);
var F3 = a(
  ({ options: n }) => ({
    key: "ySync",
    prosemirrorPlugins: [ySyncPlugin(n.fragment)],
    runsBefore: ["default"]
  })
);
var $5 = a(() => ({
  key: "yUndo",
  prosemirrorPlugins: [yUndoPlugin()],
  dependsOn: ["yCursor", "ySync"],
  undoCommand,
  redoCommand
}));
function Et2(n, e2) {
  const t2 = n.doc;
  if (n._item === null) {
    const o2 = Array.from(t2.share.keys()).find(
      (r4) => t2.share.get(r4) === n
    );
    if (o2 == null)
      throw new Error("type does not exist in other ydoc");
    return e2.get(o2, n.constructor);
  } else {
    const o2 = n._item, r4 = e2.store.clients.get(o2.id.client) ?? [], s2 = findIndexSS(r4, o2.id.clock);
    return r4[s2].content.type;
  }
}
var fo2 = a(
  ({ editor: n, options: e2 }) => {
    let t2;
    const o2 = f({ isForked: false });
    return {
      key: "yForkDoc",
      store: o2,
      /**
       * Fork the Y.js document from syncing to the remote,
       * allowing modifications to the document without affecting the remote.
       * These changes can later be rolled back or applied to the remote.
       */
      fork() {
        if (t2)
          return;
        const r4 = e2.fragment;
        if (!r4)
          throw new Error("No fragment to fork from");
        const s2 = new Doc();
        applyUpdate(s2, encodeStateAsUpdate(r4.doc));
        const i3 = Et2(r4, s2);
        t2 = {
          undoStack: yUndoPluginKey.getState(n.prosemirrorState).undoManager.undoStack,
          originalFragment: r4,
          forkedFragment: i3
        }, n.unregisterExtension([
          $5,
          te,
          F3
        ]);
        const a3 = {
          ...e2,
          fragment: i3
        };
        n.registerExtension([
          F3(a3),
          // No need to register the cursor plugin again, it's a local fork
          $5()
        ]), o2.setState({ isForked: true });
      },
      /**
       * Resume syncing the Y.js document to the remote
       * If `keepChanges` is true, any changes that have been made to the forked document will be applied to the original document.
       * Otherwise, the original document will be restored and the changes will be discarded.
       */
      merge({ keepChanges: r4 }) {
        if (!t2)
          return;
        n.unregisterExtension(["ySync", "yCursor", "yUndo"]);
        const { originalFragment: s2, forkedFragment: i3, undoStack: a3 } = t2;
        if (n.registerExtension([
          F3(e2),
          te(e2),
          $5()
        ]), yUndoPluginKey.getState(
          n.prosemirrorState
        ).undoManager.undoStack = a3, r4) {
          const c3 = encodeStateAsUpdate(
            i3.doc,
            encodeStateVector(s2.doc)
          );
          applyUpdate(s2.doc, c3, n);
        }
        t2 = void 0, o2.setState({ isForked: false });
      }
    };
  }
);
var ke = (n, e2) => {
  e2(n), n.forEach((t2) => {
    t2 instanceof YXmlElement && ke(t2, e2);
  });
};
var It3 = (n, e2) => {
  const t2 = /* @__PURE__ */ new Map();
  return n.forEach((o2) => {
    o2 instanceof YXmlElement && ke(o2, (r4) => {
      if (r4.nodeName === "blockContainer" && r4.hasAttribute("id")) {
        const s2 = r4.getAttribute("textColor"), i3 = r4.getAttribute("backgroundColor"), a3 = {
          textColor: s2 === h3.textColor.default ? void 0 : s2,
          backgroundColor: i3 === h3.backgroundColor.default ? void 0 : i3
        };
        (a3.textColor || a3.backgroundColor) && t2.set(r4.getAttribute("id"), a3);
      }
    });
  }), t2.size === 0 ? false : (e2.doc.descendants((o2, r4) => {
    if (o2.type.name === "blockContainer" && t2.has(o2.attrs.id)) {
      const s2 = e2.doc.nodeAt(r4 + 1);
      if (!s2)
        throw new Error("No element found");
      e2.setNodeMarkup(r4 + 1, void 0, {
        // preserve existing attributes
        ...s2.attrs,
        // add the textColor and backgroundColor attributes
        ...t2.get(o2.attrs.id)
      });
    }
  }), true);
};
var Bt2 = [It3];
var go2 = a(
  ({ options: n }) => {
    let e2 = false;
    const t2 = new PluginKey("schemaMigration");
    return {
      key: "schemaMigration",
      prosemirrorPlugins: [
        new Plugin({
          key: t2,
          appendTransaction: (o2, r4, s2) => {
            if (e2 || // If any of the transactions are not due to a yjs sync, we don't need to run the migration
            !o2.some((a3) => a3.getMeta("y-sync$")) || // If none of the transactions result in a document change, we don't need to run the migration
            o2.every((a3) => !a3.docChanged) || // If the fragment is still empty, we can't run the migration (since it has not yet been applied to the Y.Doc)
            !n.fragment.firstChild)
              return;
            const i3 = s2.tr;
            for (const a3 of Bt2)
              a3(n.fragment, i3);
            if (e2 = true, !!i3.docChanged)
              return i3;
          }
        })
      ]
    };
  }
);
var wo = a(
  ({
    editor: n,
    options: e2
  }) => ({
    key: "dropCursor",
    prosemirrorPlugins: [
      (e2.dropCursor ?? dropCursor)({
        width: 5,
        color: "#ddeeff",
        editor: n
      })
    ]
  })
);
var yo2 = a(({ editor: n }) => {
  const e2 = f(false), t2 = () => n.transact((o2) => {
    var s2;
    if (o2.selection.empty || o2.selection instanceof NodeSelection && (o2.selection.node.type.spec.content === "inline*" || ((s2 = o2.selection.node.firstChild) == null ? void 0 : s2.type.spec.content) === "inline*") || o2.selection instanceof TextSelection && o2.doc.textBetween(o2.selection.from, o2.selection.to).length === 0)
      return false;
    let r4 = false;
    return o2.selection.content().content.descendants((i3) => (i3.type.spec.code && (r4 = true), !r4)), !r4;
  });
  return {
    key: "formattingToolbar",
    store: e2,
    mount({ dom: o2, signal: r4 }) {
      let s2 = false;
      const i3 = n.onChange(() => {
        s2 || e2.setState(t2());
      }), a3 = n.onSelectionChange(() => {
        s2 || e2.setState(t2());
      });
      o2.addEventListener(
        "pointerdown",
        () => {
          s2 = true, e2.setState(false);
        },
        { signal: r4 }
      ), n.prosemirrorView.root.addEventListener(
        "pointerup",
        () => {
          s2 = false, n.isFocused() && e2.setState(t2());
        },
        { signal: r4, capture: true }
      ), o2.addEventListener(
        "pointercancel",
        () => {
          s2 = false;
        },
        {
          signal: r4,
          capture: true
        }
      ), r4.addEventListener("abort", () => {
        i3(), a3();
      });
    }
  };
});
var bo2 = a(() => ({
  key: "history",
  prosemirrorPlugins: [history()],
  undoCommand: undo2,
  redoCommand: redo2
}));
var vo = a(({ editor: n }) => {
  function e2(r4) {
    let s2 = n.prosemirrorView.nodeDOM(r4);
    for (; s2 && s2.parentElement; ) {
      if (s2.nodeName === "A")
        return s2;
      s2 = s2.parentElement;
    }
    return null;
  }
  function t2(r4, s2) {
    return n.transact((i3) => {
      const a3 = i3.doc.resolve(r4), c3 = a3.marks().find((m2) => m2.type.name === s2);
      if (!c3)
        return;
      const l2 = getMarkRange(a3, c3.type);
      if (l2)
        return {
          range: l2,
          mark: c3,
          get text() {
            return i3.doc.textBetween(l2.from, l2.to);
          },
          get position() {
            return posToDOMRect(
              n.prosemirrorView,
              l2.from,
              l2.to
            ).toJSON();
          }
        };
    });
  }
  function o2() {
    return n.transact((r4) => {
      const s2 = r4.selection;
      if (s2.empty)
        return t2(s2.anchor, "link");
    });
  }
  return {
    key: "linkToolbar",
    getLinkAtSelection: o2,
    getLinkElementAtPos: e2,
    getMarkAtPos: t2,
    getLinkAtElement(r4) {
      return n.transact(() => {
        const s2 = n.prosemirrorView.posAtDOM(r4, 0) + 1;
        return t2(s2, "link");
      });
    },
    editLink(r4, s2, i3 = n.transact((a3) => a3.selection.anchor)) {
      n.transact((a3) => {
        const c3 = ht(a3), { range: l2 } = t2(i3 + 1, "link") || {
          range: {
            from: a3.selection.from,
            to: a3.selection.to
          }
        };
        l2 && (a3.insertText(s2, l2.from, l2.to), a3.addMark(
          l2.from,
          l2.from + s2.length,
          c3.mark("link", { href: r4 })
        ));
      }), n.prosemirrorView.focus();
    },
    deleteLink(r4 = n.transact((s2) => s2.selection.anchor)) {
      n.transact((s2) => {
        const i3 = ht(s2), { range: a3 } = t2(r4 + 1, "link") || {
          range: {
            from: s2.selection.from,
            to: s2.selection.to
          }
        };
        a3 && s2.removeMark(a3.from, a3.to, i3.marks.link).setMeta(
          "preventAutolink",
          true
        );
      }), n.prosemirrorView.focus();
    }
  };
});
var ko2 = [
  "http",
  "https",
  "ftp",
  "ftps",
  "mailto",
  "tel",
  "callto",
  "sms",
  "cid",
  "xmpp"
];
var Co = "https";
var Tt3 = new PluginKey("node-selection-keyboard");
var So2 = a(
  () => ({
    key: "nodeSelectionKeyboard",
    prosemirrorPlugins: [
      new Plugin({
        key: Tt3,
        props: {
          handleKeyDown: (n, e2) => {
            if ("node" in n.state.selection) {
              if (e2.ctrlKey || e2.metaKey)
                return false;
              if (e2.key.length === 1)
                return e2.preventDefault(), true;
              if (e2.key === "Enter" && !e2.shiftKey && !e2.altKey && !e2.ctrlKey && !e2.metaKey) {
                const t2 = n.state.tr;
                return n.dispatch(
                  t2.insert(
                    n.state.tr.selection.$to.after(),
                    n.state.schema.nodes.paragraph.createChecked()
                  ).setSelection(
                    new TextSelection(
                      t2.doc.resolve(
                        n.state.tr.selection.$to.after() + 1
                      )
                    )
                  )
                ), true;
              }
            }
            return false;
          }
        }
      })
    ]
  })
);
var Pt3 = new PluginKey("blocknote-placeholder");
var xo2 = a(
  ({
    editor: n,
    options: e2
  }) => {
    const t2 = e2.placeholders;
    return {
      key: "placeholder",
      prosemirrorPlugins: [
        new Plugin({
          key: Pt3,
          view: (o2) => {
            const r4 = `placeholder-selector-${v4_default()}`;
            o2.dom.classList.add(r4);
            const s2 = document.createElement("style"), i3 = n._tiptapEditor.options.injectNonce;
            i3 && s2.setAttribute("nonce", i3), o2.root instanceof window.ShadowRoot ? o2.root.append(s2) : o2.root.head.appendChild(s2);
            const a3 = s2.sheet, c3 = (l2 = "") => `.${r4} .bn-block-content${l2} .bn-inline-content:has(> .ProseMirror-trailingBreak:only-child):before`;
            try {
              const {
                default: l2,
                emptyDocument: m2,
                ...h7
              } = t2 || {};
              for (const [g, d] of Object.entries(h7)) {
                const p4 = `[data-content-type="${g}"]`;
                a3.insertRule(
                  `${c3(p4)} { content: ${JSON.stringify(
                    d
                  )}; }`
                );
              }
              const f6 = "[data-is-only-empty-block]", u2 = "[data-is-empty-and-focused]";
              a3.insertRule(
                `${c3(f6)} { content: ${JSON.stringify(
                  m2
                )}; }`
              ), a3.insertRule(
                `${c3(u2)} { content: ${JSON.stringify(
                  l2
                )}; }`
              );
            } catch (l2) {
              console.warn(
                "Failed to insert placeholder CSS rule - this is likely due to the browser not supporting certain CSS pseudo-element selectors (:has, :only-child:, or :before)",
                l2
              );
            }
            return {
              destroy: () => {
                o2.root instanceof window.ShadowRoot ? o2.root.removeChild(s2) : o2.root.head.removeChild(s2);
              }
            };
          },
          props: {
            decorations: (o2) => {
              const { doc: r4, selection: s2 } = o2;
              if (!n.isEditable || !s2.empty || s2.$from.parent.type.spec.code)
                return;
              const i3 = [];
              o2.doc.content.size === 6 && i3.push(
                Decoration.node(2, 4, {
                  "data-is-only-empty-block": "true"
                })
              );
              const a3 = s2.$anchor, c3 = a3.parent;
              if (c3.content.size === 0) {
                const l2 = a3.before();
                i3.push(
                  Decoration.node(l2, l2 + c3.nodeSize, {
                    "data-is-empty-and-focused": "true"
                  })
                );
              }
              return DecorationSet.create(r4, i3);
            }
          }
        })
      ]
    };
  }
);
var oe = new PluginKey("previous-blocks");
var Ot3 = {
  // Numbered List Items
  index: "index",
  // Headings
  level: "level",
  // All Blocks
  type: "type",
  depth: "depth",
  "depth-change": "depth-change"
};
var Eo2 = a(() => {
  let n;
  return {
    key: "previousBlockType",
    prosemirrorPlugins: [
      new Plugin({
        key: oe,
        view(e2) {
          return {
            update: async (t2, o2) => {
              var r4;
              ((r4 = this.key) == null ? void 0 : r4.getState(t2.state).updatedBlocks.size) > 0 && (n = setTimeout(() => {
                t2.dispatch(
                  t2.state.tr.setMeta(oe, { clearUpdate: true })
                );
              }, 0));
            },
            destroy: () => {
              n && clearTimeout(n);
            }
          };
        },
        state: {
          init() {
            return {
              // Block attributes, by block ID, from just before the previous transaction.
              prevTransactionOldBlockAttrs: {},
              // Block attributes, by block ID, from just before the current transaction.
              currentTransactionOldBlockAttrs: {},
              // Set of IDs of blocks whose attributes changed from the current transaction.
              updatedBlocks: /* @__PURE__ */ new Set()
            };
          },
          apply(e2, t2, o2, r4) {
            if (t2.currentTransactionOldBlockAttrs = {}, t2.updatedBlocks.clear(), !e2.docChanged || o2.doc.eq(r4.doc))
              return t2;
            const s2 = {}, i3 = findChildren(
              o2.doc,
              (l2) => l2.attrs.id
            ), a3 = new Map(
              i3.map((l2) => [l2.node.attrs.id, l2])
            ), c3 = findChildren(
              r4.doc,
              (l2) => l2.attrs.id
            );
            for (const l2 of c3) {
              const m2 = a3.get(l2.node.attrs.id), h7 = m2 == null ? void 0 : m2.node.firstChild, f6 = l2.node.firstChild;
              if (m2 && h7 && f6) {
                const u2 = {
                  index: f6.attrs.index,
                  level: f6.attrs.level,
                  type: f6.type.name,
                  depth: r4.doc.resolve(l2.pos).depth
                }, g = {
                  index: h7.attrs.index,
                  level: h7.attrs.level,
                  type: h7.type.name,
                  depth: o2.doc.resolve(m2.pos).depth
                };
                s2[l2.node.attrs.id] = g, t2.currentTransactionOldBlockAttrs[l2.node.attrs.id] = g, JSON.stringify(g) !== JSON.stringify(u2) && (g["depth-change"] = g.depth - u2.depth, t2.updatedBlocks.add(l2.node.attrs.id));
              }
            }
            return t2.prevTransactionOldBlockAttrs = s2, t2;
          }
        },
        props: {
          decorations(e2) {
            const t2 = this.getState(e2);
            if (t2.updatedBlocks.size === 0)
              return;
            const o2 = [];
            return e2.doc.descendants((r4, s2) => {
              if (!r4.attrs.id || !t2.updatedBlocks.has(r4.attrs.id))
                return;
              const i3 = t2.currentTransactionOldBlockAttrs[r4.attrs.id], a3 = {};
              for (const [l2, m2] of Object.entries(i3))
                a3["data-prev-" + Ot3[l2]] = m2 || "none";
              const c3 = Decoration.node(s2, s2 + r4.nodeSize, {
                ...a3
              });
              o2.push(c3);
            }), DecorationSet.create(e2.doc, o2);
          }
        }
      })
    ]
  };
});
function Ce(n, e2) {
  var t2, o2;
  for (; n && n.parentElement && n.parentElement !== e2.dom && ((t2 = n.getAttribute) == null ? void 0 : t2.call(n, "data-node-type")) !== "blockContainer"; )
    n = n.parentElement;
  if (((o2 = n.getAttribute) == null ? void 0 : o2.call(n, "data-node-type")) === "blockContainer")
    return { node: n, id: n.getAttribute("data-id") };
}
function Dt3() {
  const n = (e2) => {
    let t2 = e2.children.length;
    for (let o2 = 0; o2 < t2; o2++) {
      const r4 = e2.children[o2];
      if (r4.type === "element" && (n(r4), r4.tagName === "u"))
        if (r4.children.length > 0) {
          e2.children.splice(o2, 1, ...r4.children);
          const s2 = r4.children.length - 1;
          t2 += s2, o2 += s2;
        } else
          e2.children.splice(o2, 1), t2--, o2--;
    }
  };
  return n;
}
function At3() {
  const n = (e2) => {
    var t2;
    if (e2.children && "length" in e2.children && e2.children.length)
      for (let o2 = e2.children.length - 1; o2 >= 0; o2--) {
        const r4 = e2.children[o2], s2 = o2 + 1 < e2.children.length ? e2.children[o2 + 1] : void 0;
        r4.type === "element" && r4.tagName === "input" && ((t2 = r4.properties) == null ? void 0 : t2.type) === "checkbox" && (s2 == null ? void 0 : s2.type) === "element" && s2.tagName === "p" ? (s2.tagName = "span", s2.children.splice(
          0,
          0,
          fromDom(document.createTextNode(" "))
        )) : n(r4);
      }
  };
  return n;
}
function Mt3() {
  return (n) => {
    visit(n, "element", (e2, t2, o2) => {
      var r4, s2, i3, a3;
      if (o2 && e2.tagName === "video") {
        const c3 = ((r4 = e2.properties) == null ? void 0 : r4.src) || ((s2 = e2.properties) == null ? void 0 : s2["data-url"]) || "", l2 = ((i3 = e2.properties) == null ? void 0 : i3.title) || ((a3 = e2.properties) == null ? void 0 : a3["data-name"]) || "";
        o2.children[t2] = {
          type: "text",
          value: `![${l2}](${c3})`
        };
      }
    });
  };
}
function Se(n) {
  return unified().use(rehypeParse, { fragment: true }).use(Mt3).use(Dt3).use(At3).use(rehypeRemark).use(remarkGfm).use(remarkStringify, {
    handlers: { text: (t2) => t2.value }
  }).processSync(n).value;
}
function Io(n, e2, t2, o2) {
  const s2 = ve(e2, t2).exportBlocks(n, o2);
  return Se(s2);
}
function Lt2(n) {
  const e2 = [];
  return n.descendants((t2) => {
    var r4, s2;
    const o2 = ht(t2);
    return t2.type.name === "blockContainer" && ((r4 = t2.firstChild) == null ? void 0 : r4.type.name) === "blockGroup" ? true : t2.type.name === "columnList" && t2.childCount === 1 ? ((s2 = t2.firstChild) == null || s2.forEach((i3) => {
      e2.push(L(i3, o2));
    }), false) : t2.type.isInGroup("bnBlock") ? (e2.push(L(t2, o2)), false) : true;
  }), e2;
}
var B3 = class _B extends Selection {
  constructor(t2, o2) {
    super(t2, o2);
    b3(this, "nodes");
    const r4 = t2.node();
    this.nodes = [], t2.doc.nodesBetween(t2.pos, o2.pos, (s2, i3, a3) => {
      if (a3 !== null && a3.eq(r4))
        return this.nodes.push(s2), false;
    });
  }
  static create(t2, o2, r4 = o2) {
    return new _B(t2.resolve(o2), t2.resolve(r4));
  }
  content() {
    return new Slice(Fragment.from(this.nodes), 0, 0);
  }
  eq(t2) {
    if (!(t2 instanceof _B) || this.nodes.length !== t2.nodes.length || this.from !== t2.from || this.to !== t2.to)
      return false;
    for (let o2 = 0; o2 < this.nodes.length; o2++)
      if (!this.nodes[o2].eq(t2.nodes[o2]))
        return false;
    return true;
  }
  map(t2, o2) {
    const r4 = o2.mapResult(this.from), s2 = o2.mapResult(this.to);
    return s2.deleted ? Selection.near(t2.resolve(r4.pos)) : r4.deleted ? Selection.near(t2.resolve(s2.pos)) : new _B(
      t2.resolve(r4.pos),
      t2.resolve(s2.pos)
    );
  }
  toJSON() {
    return { type: "multiple-node", anchor: this.anchor, head: this.head };
  }
};
Selection.jsonID("multiple-node", B3);
var x3;
function Nt2(n, e2) {
  let t2, o2;
  const r4 = e2.resolve(n.from).node().type.spec.group === "blockContent", s2 = e2.resolve(n.to).node().type.spec.group === "blockContent", i3 = Math.min(n.$anchor.depth, n.$head.depth);
  if (r4 && s2) {
    const a3 = n.$from.start(i3 - 1), c3 = n.$to.end(i3 - 1);
    t2 = e2.resolve(a3 - 1).pos, o2 = e2.resolve(c3 + 1).pos;
  } else
    t2 = n.from, o2 = n.to;
  return { from: t2, to: o2 };
}
function ne2(n, e2, t2 = e2) {
  e2 === t2 && (t2 += n.state.doc.resolve(e2 + 1).node().nodeSize);
  const o2 = n.domAtPos(e2).node.cloneNode(true), r4 = n.domAtPos(e2).node, s2 = (h7, f6) => Array.prototype.indexOf.call(h7.children, f6), i3 = s2(
    r4,
    // Expects from position to be just before the first selected block.
    n.domAtPos(e2 + 1).node.parentElement
  ), a3 = s2(
    r4,
    // Expects to position to be just after the last selected block.
    n.domAtPos(t2 - 1).node.parentElement
  );
  for (let h7 = r4.childElementCount - 1; h7 >= 0; h7--)
    (h7 > a3 || h7 < i3) && o2.removeChild(o2.children[h7]);
  xe(n.root), x3 = o2;
  const c3 = x3.getElementsByTagName("iframe");
  for (let h7 = 0; h7 < c3.length; h7++) {
    const f6 = c3[h7], u2 = f6.parentElement;
    u2 && u2.removeChild(f6);
  }
  const m2 = n.dom.className.split(" ").filter(
    (h7) => h7 !== "ProseMirror" && h7 !== "bn-root" && h7 !== "bn-editor"
  ).join(" ");
  x3.className = x3.className + " bn-drag-preview " + m2, n.root instanceof ShadowRoot ? n.root.appendChild(x3) : n.root.body.appendChild(x3);
}
function xe(n) {
  x3 !== void 0 && (n instanceof ShadowRoot ? n.removeChild(x3) : n.body.removeChild(x3), x3 = void 0);
}
function Rt3(n, e2, t2) {
  if (!n.dataTransfer || t2.headless)
    return;
  const o2 = t2.prosemirrorView, r4 = Tt2(e2.id, o2.state.doc);
  if (!r4)
    throw new Error(`Block with ID ${e2.id} not found`);
  const s2 = r4.posBeforeNode;
  if (s2 != null) {
    const i3 = o2.state.selection, a3 = o2.state.doc, { from: c3, to: l2 } = Nt2(i3, a3), m2 = c3 <= s2 && s2 < l2, h7 = i3.$anchor.node() !== i3.$head.node() || i3 instanceof B3;
    m2 && h7 ? (o2.dispatch(
      o2.state.tr.setSelection(B3.create(a3, c3, l2))
    ), ne2(o2, c3, l2)) : (o2.dispatch(
      o2.state.tr.setSelection(NodeSelection.create(o2.state.doc, s2))
    ), ne2(o2, s2));
    const f6 = o2.state.selection.content(), u2 = t2.pmSchema, g = o2.serializeForClipboard(f6).dom.innerHTML, d = ve(u2, t2), p4 = Lt2(f6.content), w3 = d.exportBlocks(p4, {}), y3 = Se(w3);
    n.dataTransfer.clearData(), n.dataTransfer.setData("blocknote/html", g), n.dataTransfer.setData("text/html", w3), n.dataTransfer.setData("text/plain", y3), n.dataTransfer.effectAllowed = "move", n.dataTransfer.setDragImage(x3, 0, 0);
  }
}
var re2 = 250;
function U2(n, e2, t2 = true) {
  const o2 = n.root.elementsFromPoint(e2.left, e2.top);
  for (const r4 of o2)
    if (n.dom.contains(r4))
      return t2 && r4.closest("[data-node-type=columnList]") ? U2(
        n,
        {
          // TODO can we do better than this?
          left: e2.left + 50,
          // bit hacky, but if we're inside a column, offset x position to right to account for the width of sidemenu itself
          top: e2.top
        },
        false
      ) : Ce(r4, n);
}
function Vt2(n, e2) {
  if (!e2.dom.firstChild)
    return;
  const t2 = e2.dom.firstChild.getBoundingClientRect(), o2 = {
    // Clamps the x position to the editor's bounding box.
    left: Math.min(
      Math.max(t2.left + 10, n.x),
      t2.right - 10
    ),
    top: n.y
  }, r4 = U2(e2, o2);
  if (!r4)
    return;
  const s2 = r4.node.getBoundingClientRect();
  return U2(
    e2,
    {
      left: s2.right - 10,
      top: n.y
    },
    false
  );
}
var Ht3 = class {
  constructor(e2, t2, o2) {
    b3(this, "state");
    b3(this, "emitUpdate");
    b3(this, "mousePos");
    b3(this, "hoveredBlock");
    b3(this, "menuFrozen", false);
    b3(this, "isDragOrigin", false);
    b3(this, "updateState", (e3) => {
      this.state = e3, this.emitUpdate(this.state);
    });
    b3(this, "updateStateFromMousePos", () => {
      var o3, r4, s2, i3, a3;
      if (this.menuFrozen || !this.mousePos)
        return;
      const e3 = this.findClosestEditorElement({
        clientX: this.mousePos.x,
        clientY: this.mousePos.y
      });
      if ((e3 == null ? void 0 : e3.element) !== this.pmView.dom || e3.distance > re2) {
        (o3 = this.state) != null && o3.show && (this.state.show = false, this.updateState(this.state));
        return;
      }
      const t3 = Vt2(this.mousePos, this.pmView);
      if (!t3 || !this.editor.isEditable) {
        (r4 = this.state) != null && r4.show && (this.state.show = false, this.updateState(this.state));
        return;
      }
      if (!((s2 = this.state) != null && s2.show && ((i3 = this.hoveredBlock) != null && i3.hasAttribute("data-id")) && ((a3 = this.hoveredBlock) == null ? void 0 : a3.getAttribute("data-id")) === t3.id) && (this.hoveredBlock = t3.node, this.editor.isEditable)) {
        const c3 = t3.node.getBoundingClientRect(), l2 = t3.node.closest("[data-node-type=column]");
        this.state = {
          show: true,
          referencePos: new DOMRect(
            l2 ? (
              // We take the first child as column elements have some default
              // padding. This is a little weird since this child element will
              // be the first block, but since it's always non-nested and we
              // only take the x coordinate, it's ok.
              l2.firstElementChild.getBoundingClientRect().x
            ) : this.pmView.dom.firstChild.getBoundingClientRect().x,
            c3.y,
            c3.width,
            c3.height
          ),
          block: this.editor.getBlock(
            this.hoveredBlock.getAttribute("data-id")
          )
        }, this.updateState(this.state);
      }
    });
    b3(this, "onDragStart", (e3) => {
      var i3;
      const t3 = (i3 = e3.dataTransfer) == null ? void 0 : i3.getData("blocknote/html");
      if (!t3 || this.pmView.dragging)
        return;
      const o3 = document.createElement("div");
      o3.innerHTML = t3;
      const s2 = DOMParser2.fromSchema(this.pmView.state.schema).parse(o3, {
        topNode: this.pmView.state.schema.nodes.blockGroup.create()
      });
      this.pmView.dragging = {
        slice: new Slice(s2.content, 0, 0),
        move: true
      };
    });
    b3(this, "findClosestEditorElement", (e3) => {
      const t3 = Array.from(this.pmView.root.querySelectorAll(".bn-editor"));
      if (t3.length === 0)
        return null;
      let o3 = t3[0], r4 = Number.MAX_VALUE;
      return t3.forEach((s2) => {
        const i3 = s2.querySelector(".bn-block-group").getBoundingClientRect(), a3 = e3.clientX < i3.left ? i3.left - e3.clientX : e3.clientX > i3.right ? e3.clientX - i3.right : 0, c3 = e3.clientY < i3.top ? i3.top - e3.clientY : e3.clientY > i3.bottom ? e3.clientY - i3.bottom : 0, l2 = Math.sqrt(
          Math.pow(a3, 2) + Math.pow(c3, 2)
        );
        l2 < r4 && (r4 = l2, o3 = s2);
      }), {
        element: o3,
        distance: r4
      };
    });
    b3(this, "onDragOver", (e3) => {
      if (e3.synthetic)
        return;
      const t3 = this.getDragEventContext(e3);
      if (!t3 || !t3.isDropPoint) {
        this.closeDropCursor();
        return;
      }
      t3.isDropPoint && !t3.isDropWithinEditorBounds && this.dispatchSyntheticEvent(e3);
    });
    b3(this, "closeDropCursor", () => {
      const e3 = new Event("dragleave", { bubbles: false });
      e3.synthetic = true, this.pmView.dom.dispatchEvent(e3);
    });
    b3(this, "getDragEventContext", (e3) => {
      var c3;
      const t3 = !((c3 = e3.dataTransfer) != null && c3.types.includes("blocknote/html")) && !!this.pmView.dragging, o3 = !!this.isDragOrigin, r4 = t3 || o3, s2 = this.findClosestEditorElement(e3);
      if (!s2 || s2.distance > re2)
        return;
      const i3 = s2.element === this.pmView.dom, a3 = i3 && s2.distance === 0;
      if (!(!i3 && !r4))
        return {
          isDropPoint: i3,
          isDropWithinEditorBounds: a3,
          isDragOrigin: r4
        };
    });
    b3(this, "onDrop", (e3) => {
      if (e3.synthetic)
        return;
      const t3 = this.getDragEventContext(e3);
      if (!t3) {
        this.closeDropCursor();
        return;
      }
      const { isDropPoint: o3, isDropWithinEditorBounds: r4, isDragOrigin: s2 } = t3;
      if (!r4 && o3 && this.dispatchSyntheticEvent(e3), o3) {
        if (this.pmView.dragging)
          return;
        this.pmView.dispatch(
          this.pmView.state.tr.setSelection(
            TextSelection.create(
              this.pmView.state.tr.doc,
              this.pmView.state.tr.selection.anchor
            )
          )
        );
        return;
      } else if (s2) {
        setTimeout(
          () => this.pmView.dispatch(this.pmView.state.tr.deleteSelection()),
          0
        );
        return;
      }
    });
    b3(this, "onDragEnd", (e3) => {
      e3.synthetic || (this.pmView.dragging = null);
    });
    b3(this, "onKeyDown", (e3) => {
      var t3;
      (t3 = this.state) != null && t3.show && this.editor.isFocused() && (this.state.show = false, this.emitUpdate(this.state));
    });
    b3(this, "onMouseMove", (e3) => {
      var s2;
      if (this.menuFrozen)
        return;
      this.mousePos = { x: e3.clientX, y: e3.clientY };
      const t3 = this.pmView.dom.getBoundingClientRect(), o3 = this.mousePos.x > t3.left && this.mousePos.x < t3.right && this.mousePos.y > t3.top && this.mousePos.y < t3.bottom, r4 = this.pmView.dom.parentElement;
      if (
        // Cursor is within the editor area
        o3 && // An element is hovered
        e3 && e3.target && // Element is outside the editor
        !(r4 === e3.target || r4.contains(e3.target))
      ) {
        (s2 = this.state) != null && s2.show && (this.state.show = false, this.emitUpdate(this.state));
        return;
      }
      this.updateStateFromMousePos();
    });
    this.editor = e2, this.pmView = t2, this.emitUpdate = () => {
      if (!this.state)
        throw new Error("Attempting to update uninitialized side menu");
      o2(this.state);
    }, this.pmView.root.addEventListener(
      "dragstart",
      this.onDragStart
    ), this.pmView.root.addEventListener(
      "dragover",
      this.onDragOver
    ), this.pmView.root.addEventListener(
      "drop",
      this.onDrop,
      true
    ), this.pmView.root.addEventListener(
      "dragend",
      this.onDragEnd,
      true
    ), this.pmView.root.addEventListener(
      "mousemove",
      this.onMouseMove,
      true
    ), this.pmView.root.addEventListener(
      "keydown",
      this.onKeyDown,
      true
    );
  }
  dispatchSyntheticEvent(e2) {
    const t2 = new Event(e2.type, e2), o2 = this.pmView.dom.firstChild.getBoundingClientRect();
    t2.clientX = e2.clientX, t2.clientY = e2.clientY, t2.clientX = Math.min(
      Math.max(e2.clientX, o2.left),
      o2.left + o2.width
    ), t2.clientY = Math.min(
      Math.max(e2.clientY, o2.top),
      o2.top + o2.height
    ), t2.dataTransfer = e2.dataTransfer, t2.preventDefault = () => e2.preventDefault(), t2.synthetic = true, this.pmView.dom.dispatchEvent(t2);
  }
  // Needed in cases where the editor state updates without the mouse cursor
  // moving, as some state updates can require a side menu update. For example,
  // adding a button to the side menu which removes the block can cause the
  // block below to jump up into the place of the removed block when clicked,
  // allowing the user to click the button again without moving the cursor. This
  // would otherwise not update the side menu, and so clicking the button again
  // would attempt to remove the same block again, causing an error.
  update(e2, t2) {
    var r4;
    !t2.doc.eq(this.pmView.state.doc) && ((r4 = this.state) != null && r4.show) && this.updateStateFromMousePos();
  }
  destroy() {
    var e2;
    (e2 = this.state) != null && e2.show && (this.state.show = false, this.emitUpdate(this.state)), this.pmView.root.removeEventListener(
      "mousemove",
      this.onMouseMove,
      true
    ), this.pmView.root.removeEventListener(
      "dragstart",
      this.onDragStart
    ), this.pmView.root.removeEventListener(
      "dragover",
      this.onDragOver
    ), this.pmView.root.removeEventListener(
      "drop",
      this.onDrop,
      true
    ), this.pmView.root.removeEventListener(
      "dragend",
      this.onDragEnd,
      true
    ), this.pmView.root.removeEventListener(
      "keydown",
      this.onKeyDown,
      true
    );
  }
};
var Ft2 = new PluginKey("SideMenuPlugin");
var Bo2 = a(({ editor: n }) => {
  let e2;
  const t2 = f(
    void 0
  );
  return {
    key: "sideMenu",
    store: t2,
    prosemirrorPlugins: [
      new Plugin({
        key: Ft2,
        view: (o2) => (e2 = new Ht3(n, o2, (r4) => {
          t2.setState({ ...r4 });
        }), e2)
      })
    ],
    /**
     * Handles drag & drop events for blocks.
     */
    blockDragStart(o2, r4) {
      e2 && (e2.isDragOrigin = true), Rt3(o2, r4, n);
    },
    /**
     * Handles drag & drop events for blocks.
     */
    blockDragEnd() {
      xe(n.prosemirrorView.root), e2 && (e2.isDragOrigin = false), n.blur();
    },
    /**
     * Freezes the side menu. When frozen, the side menu will stay
     * attached to the same block regardless of which block is hovered by the
     * mouse cursor.
     */
    freezeMenu() {
      e2.menuFrozen = true, e2.state.show = true, e2.emitUpdate(e2.state);
    },
    /**
     * Unfreezes the side menu. When frozen, the side menu will stay
     * attached to the same block regardless of which block is hovered by the
     * mouse cursor.
     */
    unfreezeMenu() {
      e2.menuFrozen = false, e2.state.show = false, e2.emitUpdate(e2.state);
    }
  };
});
var C2;
function se(n) {
  C2 || (C2 = document.createElement("div"), C2.innerHTML = "_", C2.style.opacity = "0", C2.style.height = "1px", C2.style.width = "1px", n instanceof Document ? n.body.appendChild(C2) : n.appendChild(C2));
}
function $t3(n) {
  C2 && (n instanceof Document ? n.body.removeChild(C2) : n.removeChild(C2), C2 = void 0);
}
function M4(n) {
  return Array.prototype.indexOf.call(n.parentElement.childNodes, n);
}
function Ut2(n) {
  let e2 = n;
  for (; e2 && e2.nodeName !== "TD" && e2.nodeName !== "TH" && !e2.classList.contains("tableWrapper"); ) {
    if (e2.classList.contains("ProseMirror"))
      return;
    const t2 = e2.parentNode;
    if (!t2 || !(t2 instanceof Element))
      return;
    e2 = t2;
  }
  return e2.nodeName === "TD" || e2.nodeName === "TH" ? {
    type: "cell",
    domNode: e2,
    tbodyNode: e2.closest("tbody")
  } : {
    type: "wrapper",
    domNode: e2,
    tbodyNode: e2.querySelector("tbody")
  };
}
function _t4(n, e2) {
  const t2 = e2.querySelectorAll(n);
  for (let o2 = 0; o2 < t2.length; o2++)
    t2[o2].style.visibility = "hidden";
}
var zt2 = class {
  constructor(e2, t2, o2) {
    b3(this, "state");
    b3(this, "emitUpdate");
    b3(this, "tableId");
    b3(this, "tablePos");
    b3(this, "tableElement");
    b3(this, "menuFrozen", false);
    b3(this, "mouseState", "up");
    b3(this, "prevWasEditable", null);
    b3(this, "viewMousedownHandler", () => {
      this.mouseState = "down";
    });
    b3(this, "mouseUpHandler", (e3) => {
      this.mouseState = "up", this.mouseMoveHandler(e3);
    });
    b3(this, "mouseMoveHandler", (e3) => {
      var l2, m2, h7, f6, u2, g, d;
      if (this.menuFrozen || this.mouseState === "selecting" || !(e3.target instanceof Element) || !this.pmView.dom.contains(e3.target))
        return;
      const t3 = Ut2(e3.target);
      if ((t3 == null ? void 0 : t3.type) === "cell" && this.mouseState === "down" && !((l2 = this.state) != null && l2.draggingState)) {
        this.mouseState = "selecting", (m2 = this.state) != null && m2.show && (this.state.show = false, this.state.showAddOrRemoveRowsButton = false, this.state.showAddOrRemoveColumnsButton = false, this.emitUpdate());
        return;
      }
      if (!t3 || !this.editor.isEditable) {
        (h7 = this.state) != null && h7.show && (this.state.show = false, this.state.showAddOrRemoveRowsButton = false, this.state.showAddOrRemoveColumnsButton = false, this.emitUpdate());
        return;
      }
      if (!t3.tbodyNode)
        return;
      const o3 = t3.tbodyNode.getBoundingClientRect(), r4 = Ce(t3.domNode, this.pmView);
      if (!r4)
        return;
      this.tableElement = r4.node;
      let s2;
      const i3 = this.editor.transact(
        (p4) => Tt2(r4.id, p4.doc)
      );
      if (!i3)
        throw new Error(`Block with ID ${r4.id} not found`);
      const a3 = L(
        i3.node,
        this.editor.pmSchema,
        this.editor.schema.blockSchema,
        this.editor.schema.inlineContentSchema,
        this.editor.schema.styleSchema
      );
      if (b2(this.editor, "table") && (this.tablePos = i3.posBeforeNode + 1, s2 = a3), !s2)
        return;
      this.tableId = r4.id;
      const c3 = (f6 = t3.domNode.closest(".tableWrapper")) == null ? void 0 : f6.querySelector(".table-widgets-container");
      if ((t3 == null ? void 0 : t3.type) === "wrapper") {
        const p4 = e3.clientY >= o3.bottom - 1 && // -1 to account for fractions of pixels in "bottom"
        e3.clientY < o3.bottom + 20, w3 = e3.clientX >= o3.right - 1 && e3.clientX < o3.right + 20, y3 = e3.clientX > o3.right || e3.clientY > o3.bottom;
        this.state = {
          ...this.state,
          show: true,
          showAddOrRemoveRowsButton: p4,
          showAddOrRemoveColumnsButton: w3,
          referencePosTable: o3,
          block: s2,
          widgetContainer: c3,
          colIndex: y3 || (u2 = this.state) == null ? void 0 : u2.colIndex,
          rowIndex: y3 || (g = this.state) == null ? void 0 : g.rowIndex,
          referencePosCell: y3 || (d = this.state) == null ? void 0 : d.referencePosCell
        };
      } else {
        const p4 = M4(t3.domNode), w3 = M4(t3.domNode.parentElement), y3 = t3.domNode.getBoundingClientRect();
        if (this.state !== void 0 && this.state.show && this.tableId === r4.id && this.state.rowIndex === w3 && this.state.colIndex === p4)
          return;
        this.state = {
          show: true,
          showAddOrRemoveColumnsButton: p4 === s2.content.rows[0].cells.length - 1,
          showAddOrRemoveRowsButton: w3 === s2.content.rows.length - 1,
          referencePosTable: o3,
          block: s2,
          draggingState: void 0,
          referencePosCell: y3,
          colIndex: p4,
          rowIndex: w3,
          widgetContainer: c3
        };
      }
      return this.emitUpdate(), false;
    });
    b3(this, "dragOverHandler", (e3) => {
      var f6;
      if (((f6 = this.state) == null ? void 0 : f6.draggingState) === void 0)
        return;
      e3.preventDefault(), e3.dataTransfer.dropEffect = "move", _t4(
        ".prosemirror-dropcursor-block, .prosemirror-dropcursor-inline",
        this.pmView.root
      );
      const t3 = {
        left: Math.min(
          Math.max(e3.clientX, this.state.referencePosTable.left + 1),
          this.state.referencePosTable.right - 1
        ),
        top: Math.min(
          Math.max(e3.clientY, this.state.referencePosTable.top + 1),
          this.state.referencePosTable.bottom - 1
        )
      }, o3 = this.pmView.root.elementsFromPoint(t3.left, t3.top).filter(
        (u2) => u2.tagName === "TD" || u2.tagName === "TH"
      );
      if (o3.length === 0)
        return;
      const r4 = o3[0];
      let s2 = false;
      const i3 = M4(r4.parentElement), a3 = M4(r4), c3 = this.state.draggingState.draggedCellOrientation === "row" ? this.state.rowIndex : this.state.colIndex, m2 = (this.state.draggingState.draggedCellOrientation === "row" ? i3 : a3) !== c3;
      (this.state.rowIndex !== i3 || this.state.colIndex !== a3) && (this.state.rowIndex = i3, this.state.colIndex = a3, this.state.referencePosCell = r4.getBoundingClientRect(), s2 = true);
      const h7 = this.state.draggingState.draggedCellOrientation === "row" ? t3.top : t3.left;
      this.state.draggingState.mousePos !== h7 && (this.state.draggingState.mousePos = h7, s2 = true), s2 && this.emitUpdate(), m2 && this.editor.transact((u2) => u2.setMeta(D3, true));
    });
    b3(this, "dropHandler", (e3) => {
      if (this.mouseState = "up", this.state === void 0 || this.state.draggingState === void 0)
        return false;
      if (this.state.rowIndex === void 0 || this.state.colIndex === void 0)
        throw new Error(
          "Attempted to drop table row or column, but no table block was hovered prior."
        );
      e3.preventDefault();
      const { draggingState: t3, colIndex: o3, rowIndex: r4 } = this.state, s2 = this.state.block.content.columnWidths;
      if (t3.draggedCellOrientation === "row") {
        if (!Jt(
          this.state.block,
          t3.originalIndex,
          r4
        ))
          return false;
        const i3 = Pt(
          this.state.block,
          t3.originalIndex,
          r4
        );
        this.editor.updateBlock(this.state.block, {
          type: "table",
          content: {
            ...this.state.block.content,
            rows: i3
          }
        });
      } else {
        if (!_t2(
          this.state.block,
          t3.originalIndex,
          o3
        ))
          return false;
        const i3 = Mt(
          this.state.block,
          t3.originalIndex,
          o3
        ), [a3] = s2.splice(t3.originalIndex, 1);
        s2.splice(o3, 0, a3), this.editor.updateBlock(this.state.block, {
          type: "table",
          content: {
            ...this.state.block.content,
            columnWidths: s2,
            rows: i3
          }
        });
      }
      return this.editor.setTextCursorPosition(this.state.block.id), true;
    });
    this.editor = e2, this.pmView = t2, this.emitUpdate = () => {
      if (!this.state)
        throw new Error("Attempting to update uninitialized image toolbar");
      o2(this.state);
    }, t2.dom.addEventListener("mousemove", this.mouseMoveHandler), t2.dom.addEventListener("mousedown", this.viewMousedownHandler), window.addEventListener("mouseup", this.mouseUpHandler), t2.root.addEventListener(
      "dragover",
      this.dragOverHandler
    ), t2.root.addEventListener(
      "drop",
      this.dropHandler
    );
  }
  // Updates drag handles when the table is modified or removed.
  update() {
    var r4;
    if (!this.state || !this.state.show)
      return;
    if (this.state.block = this.editor.getBlock(this.state.block.id), !this.state.block || this.state.block.type !== "table" || // when collaborating, the table element might be replaced and out of date
    // because yjs replaces the element when for example you change the color via the side menu
    !((r4 = this.tableElement) != null && r4.isConnected)) {
      this.state.show = false, this.state.showAddOrRemoveRowsButton = false, this.state.showAddOrRemoveColumnsButton = false, this.emitUpdate();
      return;
    }
    const { height: e2, width: t2 } = tt(
      this.state.block
    );
    this.state.rowIndex !== void 0 && this.state.colIndex !== void 0 && (this.state.rowIndex >= e2 && (this.state.rowIndex = e2 - 1), this.state.colIndex >= t2 && (this.state.colIndex = t2 - 1));
    const o2 = this.tableElement.querySelector("tbody");
    if (!o2)
      throw new Error(
        "Table block does not contain a 'tbody' HTML element. This should never happen."
      );
    if (this.state.rowIndex !== void 0 && this.state.colIndex !== void 0) {
      const i3 = o2.children[this.state.rowIndex].children[this.state.colIndex];
      i3 ? this.state.referencePosCell = i3.getBoundingClientRect() : (this.state.rowIndex = void 0, this.state.colIndex = void 0);
    }
    this.state.referencePosTable = o2.getBoundingClientRect(), this.emitUpdate();
  }
  destroy() {
    this.pmView.dom.removeEventListener("mousemove", this.mouseMoveHandler), window.removeEventListener("mouseup", this.mouseUpHandler), this.pmView.dom.removeEventListener("mousedown", this.viewMousedownHandler), this.pmView.root.removeEventListener(
      "dragover",
      this.dragOverHandler
    ), this.pmView.root.removeEventListener(
      "drop",
      this.dropHandler
    );
  }
};
var D3 = new PluginKey("TableHandlesPlugin");
var To2 = a(({ editor: n }) => {
  let e2;
  const t2 = f(void 0);
  return {
    key: "tableHandles",
    store: t2,
    prosemirrorPlugins: [
      new Plugin({
        key: D3,
        view: (o2) => (e2 = new zt2(n, o2, (r4) => {
          t2.setState(
            r4.block ? {
              ...r4,
              draggingState: r4.draggingState ? { ...r4.draggingState } : void 0
            } : void 0
          );
        }), e2),
        // We use decorations to render the drop cursor when dragging a table row
        // or column. The decorations are updated in the `dragOverHandler` method.
        props: {
          decorations: (o2) => {
            if (e2 === void 0 || e2.state === void 0 || e2.state.draggingState === void 0 || e2.tablePos === void 0)
              return;
            const r4 = e2.state.draggingState.draggedCellOrientation === "row" ? e2.state.rowIndex : e2.state.colIndex;
            if (r4 === void 0)
              return;
            const s2 = [], { block: i3, draggingState: a3 } = e2.state, { originalIndex: c3, draggedCellOrientation: l2 } = a3;
            if (r4 === c3 || !i3 || l2 === "row" && !Jt(i3, c3, r4) || l2 === "col" && !_t2(i3, c3, r4))
              return DecorationSet.create(o2.doc, s2);
            const m2 = o2.doc.resolve(e2.tablePos + 1);
            return e2.state.draggingState.draggedCellOrientation === "row" ? yt(
              e2.state.block,
              r4
            ).forEach(({ row: f6, col: u2 }) => {
              const g = o2.doc.resolve(
                m2.posAtIndex(f6) + 1
              ), d = o2.doc.resolve(
                g.posAtIndex(u2) + 1
              ), p4 = d.node(), w3 = d.pos + (r4 > c3 ? p4.nodeSize - 2 : 0);
              s2.push(
                // The widget is a small bar which spans the width of the cell.
                Decoration.widget(w3, () => {
                  const y3 = document.createElement("div");
                  return y3.className = "bn-table-drop-cursor", y3.style.left = "0", y3.style.right = "0", r4 > c3 ? y3.style.bottom = "-2px" : y3.style.top = "-3px", y3.style.height = "4px", y3;
                })
              );
            }) : Ct(
              e2.state.block,
              r4
            ).forEach(({ row: f6, col: u2 }) => {
              const g = o2.doc.resolve(
                m2.posAtIndex(f6) + 1
              ), d = o2.doc.resolve(
                g.posAtIndex(u2) + 1
              ), p4 = d.node(), w3 = d.pos + (r4 > c3 ? p4.nodeSize - 2 : 0);
              s2.push(
                // The widget is a small bar which spans the height of the cell.
                Decoration.widget(w3, () => {
                  const y3 = document.createElement("div");
                  return y3.className = "bn-table-drop-cursor", y3.style.top = "0", y3.style.bottom = "0", r4 > c3 ? y3.style.right = "-2px" : y3.style.left = "-3px", y3.style.width = "4px", y3;
                })
              );
            }), DecorationSet.create(o2.doc, s2);
          }
        }
      })
    ],
    /**
     * Callback that should be set on the `dragStart` event for whichever element
     * is used as the column drag handle.
     */
    colDragStart(o2) {
      if (e2 === void 0 || e2.state === void 0 || e2.state.colIndex === void 0)
        throw new Error(
          "Attempted to drag table column, but no table block was hovered prior."
        );
      e2.state.draggingState = {
        draggedCellOrientation: "col",
        originalIndex: e2.state.colIndex,
        mousePos: o2.clientX
      }, e2.emitUpdate(), n.transact(
        (r4) => r4.setMeta(D3, {
          draggedCellOrientation: e2.state.draggingState.draggedCellOrientation,
          originalIndex: e2.state.colIndex,
          newIndex: e2.state.colIndex,
          tablePos: e2.tablePos
        })
      ), !n.headless && (se(n.prosemirrorView.root), o2.dataTransfer.setDragImage(C2, 0, 0), o2.dataTransfer.effectAllowed = "move");
    },
    /**
     * Callback that should be set on the `dragStart` event for whichever element
     * is used as the row drag handle.
     */
    rowDragStart(o2) {
      if (e2.state === void 0 || e2.state.rowIndex === void 0)
        throw new Error(
          "Attempted to drag table row, but no table block was hovered prior."
        );
      e2.state.draggingState = {
        draggedCellOrientation: "row",
        originalIndex: e2.state.rowIndex,
        mousePos: o2.clientY
      }, e2.emitUpdate(), n.transact(
        (r4) => r4.setMeta(D3, {
          draggedCellOrientation: e2.state.draggingState.draggedCellOrientation,
          originalIndex: e2.state.rowIndex,
          newIndex: e2.state.rowIndex,
          tablePos: e2.tablePos
        })
      ), !n.headless && (se(n.prosemirrorView.root), o2.dataTransfer.setDragImage(C2, 0, 0), o2.dataTransfer.effectAllowed = "copyMove");
    },
    /**
     * Callback that should be set on the `dragEnd` event for both the element
     * used as the row drag handle, and the one used as the column drag handle.
     */
    dragEnd() {
      if (e2.state === void 0)
        throw new Error(
          "Attempted to drag table row, but no table block was hovered prior."
        );
      e2.state.draggingState = void 0, e2.emitUpdate(), n.transact((o2) => o2.setMeta(D3, null)), !n.headless && $t3(n.prosemirrorView.root);
    },
    /**
     * Freezes the drag handles. When frozen, they will stay attached to the same
     * cell regardless of which cell is hovered by the mouse cursor.
     */
    freezeHandles() {
      e2.menuFrozen = true;
    },
    /**
     * Unfreezes the drag handles. When frozen, they will stay attached to the
     * same cell regardless of which cell is hovered by the mouse cursor.
     */
    unfreezeHandles() {
      e2.menuFrozen = false;
    },
    getCellsAtRowHandle(o2, r4) {
      return yt(o2, r4);
    },
    /**
     * Get all the cells in a column of the table block.
     */
    getCellsAtColumnHandle(o2, r4) {
      return Ct(o2, r4);
    },
    /**
     * Sets the selection to the given cell or a range of cells.
     * @returns The new state after the selection has been set.
     */
    setCellSelection(o2, r4, s2 = r4) {
      if (!e2)
        throw new Error("Table handles view not initialized");
      const i3 = o2.doc.resolve(e2.tablePos + 1), a3 = o2.doc.resolve(
        i3.posAtIndex(r4.row) + 1
      ), c3 = o2.doc.resolve(
        // No need for +1, since CellSelection expects the position before the cell
        a3.posAtIndex(r4.col)
      ), l2 = o2.doc.resolve(
        i3.posAtIndex(s2.row) + 1
      ), m2 = o2.doc.resolve(
        // No need for +1, since CellSelection expects the position before the cell
        l2.posAtIndex(s2.col)
      ), h7 = o2.tr;
      return h7.setSelection(
        new CellSelection(c3, m2)
      ), o2.apply(h7);
    },
    /**
     * Adds a row or column to the table using prosemirror-table commands
     */
    addRowOrColumn(o2, r4) {
      n.exec((s2, i3) => {
        const a3 = this.setCellSelection(
          s2,
          r4.orientation === "row" ? { row: o2, col: 0 } : { row: 0, col: o2 }
        );
        return r4.orientation === "row" ? r4.side === "above" ? addRowBefore(a3, i3) : addRowAfter(a3, i3) : r4.side === "left" ? addColumnBefore(a3, i3) : addColumnAfter(a3, i3);
      });
    },
    /**
     * Removes a row or column from the table using prosemirror-table commands
     */
    removeRowOrColumn(o2, r4) {
      return r4 === "row" ? n.exec((s2, i3) => {
        const a3 = this.setCellSelection(s2, {
          row: o2,
          col: 0
        });
        return deleteRow(a3, i3);
      }) : n.exec((s2, i3) => {
        const a3 = this.setCellSelection(s2, {
          row: 0,
          col: o2
        });
        return deleteColumn(a3, i3);
      });
    },
    /**
     * Merges the cells in the table block.
     */
    mergeCells(o2) {
      return n.exec((r4, s2) => {
        const i3 = o2 ? this.setCellSelection(
          r4,
          o2.relativeStartCell,
          o2.relativeEndCell
        ) : r4;
        return mergeCells(i3, s2);
      });
    },
    /**
     * Splits the cell in the table block.
     * If no cell is provided, the current cell selected will be split.
     */
    splitCell(o2) {
      return n.exec((r4, s2) => {
        const i3 = o2 ? this.setCellSelection(r4, o2) : r4;
        return splitCell(i3, s2);
      });
    },
    /**
     * Gets the start and end cells of the current cell selection.
     * @returns The start and end cells of the current cell selection.
     */
    getCellSelection() {
      return n.transact((o2) => {
        const r4 = o2.selection;
        let s2 = r4.$from, i3 = r4.$to;
        if (To(r4)) {
          const { ranges: d } = r4;
          d.forEach((p4) => {
            s2 = p4.$from.min(s2 ?? p4.$from), i3 = p4.$to.max(i3 ?? p4.$to);
          });
        } else if (s2 = o2.doc.resolve(
          r4.$from.pos - r4.$from.parentOffset - 1
        ), i3 = o2.doc.resolve(
          r4.$to.pos - r4.$to.parentOffset - 1
        ), s2.pos === 0 || i3.pos === 0)
          return;
        const a3 = o2.doc.resolve(
          s2.pos - s2.parentOffset - 1
        ), c3 = o2.doc.resolve(i3.pos - i3.parentOffset - 1), l2 = o2.doc.resolve(a3.pos - a3.parentOffset - 1), m2 = s2.index(a3.depth), h7 = a3.index(l2.depth), f6 = i3.index(c3.depth), u2 = c3.index(l2.depth), g = [];
        for (let d = h7; d <= u2; d++)
          for (let p4 = m2; p4 <= f6; p4++)
            g.push({ row: d, col: p4 });
        return {
          from: {
            row: h7,
            col: m2
          },
          to: {
            row: u2,
            col: f6
          },
          cells: g
        };
      });
    },
    /**
     * Gets the direction of the merge based on the current cell selection.
     *
     * Returns undefined when there is no cell selection, or the selection is not within a table.
     */
    getMergeDirection(o2) {
      return n.transact((r4) => {
        const s2 = To(r4.selection) ? r4.selection : void 0;
        if (!s2 || !o2 || // Only offer the merge button if there is more than one cell selected.
        s2.ranges.length <= 1)
          return;
        const i3 = this.getCellSelection();
        if (i3)
          return Ht(i3.from, i3.to, o2) ? "vertical" : "horizontal";
      });
    },
    cropEmptyRowsOrColumns(o2, r4) {
      return Rt(o2, r4);
    },
    addRowsOrColumns(o2, r4, s2) {
      return $t(o2, r4, s2);
    }
  };
});
var ie3 = new PluginKey("trailingNode");
var Po2 = a(() => ({
  key: "trailingNode",
  prosemirrorPlugins: [
    new Plugin({
      key: ie3,
      appendTransaction: (n, e2, t2) => {
        const { doc: o2, tr: r4, schema: s2 } = t2, i3 = ie3.getState(t2), a3 = o2.content.size - 2, c3 = s2.nodes.blockContainer, l2 = s2.nodes.paragraph;
        if (i3)
          return r4.insert(
            a3,
            c3.create(void 0, l2.create())
          );
      },
      state: {
        init: (n, e2) => {
        },
        apply: (n, e2) => {
          if (!n.docChanged)
            return e2;
          let t2 = n.doc.lastChild;
          if (!t2 || t2.type.name !== "blockGroup")
            throw new Error("Expected blockGroup");
          if (t2 = t2.lastChild, !t2 || t2.type.name !== "blockContainer")
            return true;
          const o2 = t2.firstChild;
          if (!o2)
            throw new Error("Expected blockContent");
          return t2.nodeSize > 4 || o2.type.spec.content !== "inline*";
        }
      }
    })
  ]
}));

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/extensions.js
var o;
async function r3() {
  return o || (o = (async () => {
    const [e2, n] = await Promise.all([
      import("./module-4GIHSJCO.js"),
      // use a dynamic import to encourage bundle-splitting
      // and a smaller initial client bundle size
      import("./native-JYCSL3WK.js")
    ]), a3 = "default" in e2 ? e2.default : e2, t2 = "default" in n ? n.default : n;
    return await a3.init({ data: t2 }), { emojiMart: a3, emojiData: t2 };
  })(), o);
}
async function c2(e2, n) {
  if (!("text" in e2.schema.inlineContentSchema) || e2.schema.inlineContentSchema.text !== Ho.text)
    return [];
  const { emojiData: a3, emojiMart: t2 } = await r3();
  return (n.trim() === "" ? Object.values(a3.emojis) : await t2.SearchIndex.search(n)).map((s2) => ({
    id: s2.skins[0].native,
    onItemClick: () => e2.insertInlineContent(s2.skins[0].native + " ")
  }));
}

// ../../node_modules/.pnpm/@floating-ui+react@0.27.16_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@floating-ui/react/dist/floating-ui.react.mjs
var React3 = __toESM(require_react(), 1);

// ../../node_modules/.pnpm/@floating-ui+utils@0.2.10/node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs
function hasWindow() {
  return typeof window !== "undefined";
}
function getNodeName(node2) {
  if (isNode2(node2)) {
    return (node2.nodeName || "").toLowerCase();
  }
  return "#document";
}
function getWindow(node2) {
  var _node$ownerDocument;
  return (node2 == null || (_node$ownerDocument = node2.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
}
function getDocumentElement(node2) {
  var _ref;
  return (_ref = (isNode2(node2) ? node2.ownerDocument : node2.document) || window.document) == null ? void 0 : _ref.documentElement;
}
function isNode2(value) {
  if (!hasWindow()) {
    return false;
  }
  return value instanceof Node || value instanceof getWindow(value).Node;
}
function isElement2(value) {
  if (!hasWindow()) {
    return false;
  }
  return value instanceof Element || value instanceof getWindow(value).Element;
}
function isHTMLElement(value) {
  if (!hasWindow()) {
    return false;
  }
  return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
}
function isShadowRoot(value) {
  if (!hasWindow() || typeof ShadowRoot === "undefined") {
    return false;
  }
  return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
}
var invalidOverflowDisplayValues = /* @__PURE__ */ new Set(["inline", "contents"]);
function isOverflowElement(element7) {
  const {
    overflow,
    overflowX,
    overflowY,
    display
  } = getComputedStyle2(element7);
  return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !invalidOverflowDisplayValues.has(display);
}
var tableElements = /* @__PURE__ */ new Set(["table", "td", "th"]);
function isTableElement(element7) {
  return tableElements.has(getNodeName(element7));
}
var topLayerSelectors = [":popover-open", ":modal"];
function isTopLayer(element7) {
  return topLayerSelectors.some((selector) => {
    try {
      return element7.matches(selector);
    } catch (_e4) {
      return false;
    }
  });
}
var transformProperties = ["transform", "translate", "scale", "rotate", "perspective"];
var willChangeValues = ["transform", "translate", "scale", "rotate", "perspective", "filter"];
var containValues = ["paint", "layout", "strict", "content"];
function isContainingBlock(elementOrCss) {
  const webkit2 = isWebKit();
  const css = isElement2(elementOrCss) ? getComputedStyle2(elementOrCss) : elementOrCss;
  return transformProperties.some((value) => css[value] ? css[value] !== "none" : false) || (css.containerType ? css.containerType !== "normal" : false) || !webkit2 && (css.backdropFilter ? css.backdropFilter !== "none" : false) || !webkit2 && (css.filter ? css.filter !== "none" : false) || willChangeValues.some((value) => (css.willChange || "").includes(value)) || containValues.some((value) => (css.contain || "").includes(value));
}
function getContainingBlock(element7) {
  let currentNode = getParentNode(element7);
  while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
    if (isContainingBlock(currentNode)) {
      return currentNode;
    } else if (isTopLayer(currentNode)) {
      return null;
    }
    currentNode = getParentNode(currentNode);
  }
  return null;
}
function isWebKit() {
  if (typeof CSS === "undefined" || !CSS.supports) return false;
  return CSS.supports("-webkit-backdrop-filter", "none");
}
var lastTraversableNodeNames = /* @__PURE__ */ new Set(["html", "body", "#document"]);
function isLastTraversableNode(node2) {
  return lastTraversableNodeNames.has(getNodeName(node2));
}
function getComputedStyle2(element7) {
  return getWindow(element7).getComputedStyle(element7);
}
function getNodeScroll(element7) {
  if (isElement2(element7)) {
    return {
      scrollLeft: element7.scrollLeft,
      scrollTop: element7.scrollTop
    };
  }
  return {
    scrollLeft: element7.scrollX,
    scrollTop: element7.scrollY
  };
}
function getParentNode(node2) {
  if (getNodeName(node2) === "html") {
    return node2;
  }
  const result = (
    // Step into the shadow DOM of the parent of a slotted node.
    node2.assignedSlot || // DOM Element detected.
    node2.parentNode || // ShadowRoot detected.
    isShadowRoot(node2) && node2.host || // Fallback.
    getDocumentElement(node2)
  );
  return isShadowRoot(result) ? result.host : result;
}
function getNearestOverflowAncestor(node2) {
  const parentNode2 = getParentNode(node2);
  if (isLastTraversableNode(parentNode2)) {
    return node2.ownerDocument ? node2.ownerDocument.body : node2.body;
  }
  if (isHTMLElement(parentNode2) && isOverflowElement(parentNode2)) {
    return parentNode2;
  }
  return getNearestOverflowAncestor(parentNode2);
}
function getOverflowAncestors(node2, list7, traverseIframes) {
  var _node$ownerDocument2;
  if (list7 === void 0) {
    list7 = [];
  }
  if (traverseIframes === void 0) {
    traverseIframes = true;
  }
  const scrollableAncestor = getNearestOverflowAncestor(node2);
  const isBody = scrollableAncestor === ((_node$ownerDocument2 = node2.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
  const win = getWindow(scrollableAncestor);
  if (isBody) {
    const frameElement = getFrameElement(win);
    return list7.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []);
  }
  return list7.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes));
}
function getFrameElement(win) {
  return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;
}

// ../../node_modules/.pnpm/@floating-ui+react@0.27.16_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@floating-ui/react/dist/floating-ui.react.utils.mjs
var React = __toESM(require_react(), 1);
var import_react = __toESM(require_react(), 1);

// ../../node_modules/.pnpm/@floating-ui+utils@0.2.10/node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs
var sides = ["top", "right", "bottom", "left"];
var alignments = ["start", "end"];
var placements = sides.reduce((acc, side) => acc.concat(side, side + "-" + alignments[0], side + "-" + alignments[1]), []);
var min2 = Math.min;
var max2 = Math.max;
var round2 = Math.round;
var floor2 = Math.floor;
var createCoords = (v8) => ({
  x: v8,
  y: v8
});
var oppositeSideMap = {
  left: "right",
  right: "left",
  bottom: "top",
  top: "bottom"
};
var oppositeAlignmentMap = {
  start: "end",
  end: "start"
};
function clamp(start, value, end) {
  return max2(start, min2(value, end));
}
function evaluate(value, param) {
  return typeof value === "function" ? value(param) : value;
}
function getSide2(placement) {
  return placement.split("-")[0];
}
function getAlignment(placement) {
  return placement.split("-")[1];
}
function getOppositeAxis(axis) {
  return axis === "x" ? "y" : "x";
}
function getAxisLength(axis) {
  return axis === "y" ? "height" : "width";
}
var yAxisSides = /* @__PURE__ */ new Set(["top", "bottom"]);
function getSideAxis(placement) {
  return yAxisSides.has(getSide2(placement)) ? "y" : "x";
}
function getAlignmentAxis(placement) {
  return getOppositeAxis(getSideAxis(placement));
}
function getAlignmentSides(placement, rects, rtl) {
  if (rtl === void 0) {
    rtl = false;
  }
  const alignment = getAlignment(placement);
  const alignmentAxis = getAlignmentAxis(placement);
  const length2 = getAxisLength(alignmentAxis);
  let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top";
  if (rects.reference[length2] > rects.floating[length2]) {
    mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
  }
  return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
}
function getExpandedPlacements(placement) {
  const oppositePlacement = getOppositePlacement(placement);
  return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
}
function getOppositeAlignmentPlacement(placement) {
  return placement.replace(/start|end/g, (alignment) => oppositeAlignmentMap[alignment]);
}
var lrPlacement = ["left", "right"];
var rlPlacement = ["right", "left"];
var tbPlacement = ["top", "bottom"];
var btPlacement = ["bottom", "top"];
function getSideList(side, isStart, rtl) {
  switch (side) {
    case "top":
    case "bottom":
      if (rtl) return isStart ? rlPlacement : lrPlacement;
      return isStart ? lrPlacement : rlPlacement;
    case "left":
    case "right":
      return isStart ? tbPlacement : btPlacement;
    default:
      return [];
  }
}
function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
  const alignment = getAlignment(placement);
  let list7 = getSideList(getSide2(placement), direction === "start", rtl);
  if (alignment) {
    list7 = list7.map((side) => side + "-" + alignment);
    if (flipAlignment) {
      list7 = list7.concat(list7.map(getOppositeAlignmentPlacement));
    }
  }
  return list7;
}
function getOppositePlacement(placement) {
  return placement.replace(/left|right|bottom|top/g, (side) => oppositeSideMap[side]);
}
function expandPaddingObject(padding) {
  return {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    ...padding
  };
}
function getPaddingObject(padding) {
  return typeof padding !== "number" ? expandPaddingObject(padding) : {
    top: padding,
    right: padding,
    bottom: padding,
    left: padding
  };
}
function rectToClientRect(rect) {
  const {
    x: x5,
    y: y3,
    width,
    height
  } = rect;
  return {
    width,
    height,
    top: y3,
    left: x5,
    right: x5 + width,
    bottom: y3 + height,
    x: x5,
    y: y3
  };
}

// ../../node_modules/.pnpm/tabbable@6.3.0/node_modules/tabbable/dist/index.esm.js
var candidateSelectors = ["input:not([inert])", "select:not([inert])", "textarea:not([inert])", "a[href]:not([inert])", "button:not([inert])", "[tabindex]:not(slot):not([inert])", "audio[controls]:not([inert])", "video[controls]:not([inert])", '[contenteditable]:not([contenteditable="false"]):not([inert])', "details>summary:first-of-type:not([inert])", "details:not([inert])"];
var candidateSelector = candidateSelectors.join(",");
var NoElement = typeof Element === "undefined";
var matches2 = NoElement ? function() {
} : Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
var getRootNode = !NoElement && Element.prototype.getRootNode ? function(element7) {
  var _element$getRootNode;
  return element7 === null || element7 === void 0 ? void 0 : (_element$getRootNode = element7.getRootNode) === null || _element$getRootNode === void 0 ? void 0 : _element$getRootNode.call(element7);
} : function(element7) {
  return element7 === null || element7 === void 0 ? void 0 : element7.ownerDocument;
};
var focusableCandidateSelector = candidateSelectors.concat("iframe").join(",");

// ../../node_modules/.pnpm/@floating-ui+react@0.27.16_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@floating-ui/react/dist/floating-ui.react.utils.mjs
function getPlatform() {
  const uaData = navigator.userAgentData;
  if (uaData != null && uaData.platform) {
    return uaData.platform;
  }
  return navigator.platform;
}
function isSafari() {
  return /apple/i.test(navigator.vendor);
}
var ARROW_LEFT = "ArrowLeft";
var ARROW_RIGHT = "ArrowRight";
var ARROW_UP = "ArrowUp";
var ARROW_DOWN = "ArrowDown";
function contains(parent, child) {
  if (!parent || !child) {
    return false;
  }
  const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();
  if (parent.contains(child)) {
    return true;
  }
  if (rootNode && isShadowRoot(rootNode)) {
    let next2 = child;
    while (next2) {
      if (parent === next2) {
        return true;
      }
      next2 = next2.parentNode || next2.host;
    }
  }
  return false;
}
function getTarget(event) {
  if ("composedPath" in event) {
    return event.composedPath()[0];
  }
  return event.target;
}
function isEventTargetWithin(event, node2) {
  if (node2 == null) {
    return false;
  }
  if ("composedPath" in event) {
    return event.composedPath().includes(node2);
  }
  const e2 = event;
  return e2.target != null && node2.contains(e2.target);
}
function isRootElement(element7) {
  return element7.matches("html,body");
}
function getDocument(node2) {
  return (node2 == null ? void 0 : node2.ownerDocument) || document;
}
function getNodeChildren(nodes, id2, onlyOpenChildren) {
  if (onlyOpenChildren === void 0) {
    onlyOpenChildren = true;
  }
  const directChildren = nodes.filter((node2) => {
    var _node$context;
    return node2.parentId === id2 && (!onlyOpenChildren || ((_node$context = node2.context) == null ? void 0 : _node$context.open));
  });
  return directChildren.flatMap((child) => [child, ...getNodeChildren(nodes, child.id, onlyOpenChildren)]);
}
function stopEvent(event) {
  event.preventDefault();
  event.stopPropagation();
}
function isReactEvent(event) {
  return "nativeEvent" in event;
}
function isMouseLikePointerType(pointerType, strict) {
  const values2 = ["mouse", "pen"];
  if (!strict) {
    values2.push("", void 0);
  }
  return values2.includes(pointerType);
}
var isClient = typeof document !== "undefined";
var noop = function noop2() {
};
var index2 = isClient ? import_react.useLayoutEffect : noop;
var SafeReact = {
  ...React
};
function useLatestRef(value) {
  const ref = React.useRef(value);
  index2(() => {
    ref.current = value;
  });
  return ref;
}
var useInsertionEffect = SafeReact.useInsertionEffect;
var useSafeInsertionEffect = useInsertionEffect || ((fn4) => fn4());
function useEffectEvent(callback) {
  const ref = React.useRef(() => {
    if (true) {
      throw new Error("Cannot call an event handler while rendering.");
    }
  });
  useSafeInsertionEffect(() => {
    ref.current = callback;
  });
  return React.useCallback(function() {
    for (var _len = arguments.length, args2 = new Array(_len), _key = 0; _key < _len; _key++) {
      args2[_key] = arguments[_key];
    }
    return ref.current == null ? void 0 : ref.current(...args2);
  }, []);
}
function isDifferentGridRow(index4, cols, prevRow) {
  return Math.floor(index4 / cols) !== prevRow;
}
function isIndexOutOfListBounds(listRef, index4) {
  return index4 < 0 || index4 >= listRef.current.length;
}
function getMinListIndex(listRef, disabledIndices) {
  return findNonDisabledListIndex(listRef, {
    disabledIndices
  });
}
function getMaxListIndex(listRef, disabledIndices) {
  return findNonDisabledListIndex(listRef, {
    decrement: true,
    startingIndex: listRef.current.length,
    disabledIndices
  });
}
function findNonDisabledListIndex(listRef, _temp) {
  let {
    startingIndex = -1,
    decrement = false,
    disabledIndices,
    amount = 1
  } = _temp === void 0 ? {} : _temp;
  let index4 = startingIndex;
  do {
    index4 += decrement ? -amount : amount;
  } while (index4 >= 0 && index4 <= listRef.current.length - 1 && isListIndexDisabled(listRef, index4, disabledIndices));
  return index4;
}
function getGridNavigatedIndex(listRef, _ref) {
  let {
    event,
    orientation,
    loop,
    rtl,
    cols,
    disabledIndices,
    minIndex,
    maxIndex,
    prevIndex,
    stopEvent: stop = false
  } = _ref;
  let nextIndex = prevIndex;
  if (event.key === ARROW_UP) {
    stop && stopEvent(event);
    if (prevIndex === -1) {
      nextIndex = maxIndex;
    } else {
      nextIndex = findNonDisabledListIndex(listRef, {
        startingIndex: nextIndex,
        amount: cols,
        decrement: true,
        disabledIndices
      });
      if (loop && (prevIndex - cols < minIndex || nextIndex < 0)) {
        const col = prevIndex % cols;
        const maxCol = maxIndex % cols;
        const offset4 = maxIndex - (maxCol - col);
        if (maxCol === col) {
          nextIndex = maxIndex;
        } else {
          nextIndex = maxCol > col ? offset4 : offset4 - cols;
        }
      }
    }
    if (isIndexOutOfListBounds(listRef, nextIndex)) {
      nextIndex = prevIndex;
    }
  }
  if (event.key === ARROW_DOWN) {
    stop && stopEvent(event);
    if (prevIndex === -1) {
      nextIndex = minIndex;
    } else {
      nextIndex = findNonDisabledListIndex(listRef, {
        startingIndex: prevIndex,
        amount: cols,
        disabledIndices
      });
      if (loop && prevIndex + cols > maxIndex) {
        nextIndex = findNonDisabledListIndex(listRef, {
          startingIndex: prevIndex % cols - cols,
          amount: cols,
          disabledIndices
        });
      }
    }
    if (isIndexOutOfListBounds(listRef, nextIndex)) {
      nextIndex = prevIndex;
    }
  }
  if (orientation === "both") {
    const prevRow = floor2(prevIndex / cols);
    if (event.key === (rtl ? ARROW_LEFT : ARROW_RIGHT)) {
      stop && stopEvent(event);
      if (prevIndex % cols !== cols - 1) {
        nextIndex = findNonDisabledListIndex(listRef, {
          startingIndex: prevIndex,
          disabledIndices
        });
        if (loop && isDifferentGridRow(nextIndex, cols, prevRow)) {
          nextIndex = findNonDisabledListIndex(listRef, {
            startingIndex: prevIndex - prevIndex % cols - 1,
            disabledIndices
          });
        }
      } else if (loop) {
        nextIndex = findNonDisabledListIndex(listRef, {
          startingIndex: prevIndex - prevIndex % cols - 1,
          disabledIndices
        });
      }
      if (isDifferentGridRow(nextIndex, cols, prevRow)) {
        nextIndex = prevIndex;
      }
    }
    if (event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT)) {
      stop && stopEvent(event);
      if (prevIndex % cols !== 0) {
        nextIndex = findNonDisabledListIndex(listRef, {
          startingIndex: prevIndex,
          decrement: true,
          disabledIndices
        });
        if (loop && isDifferentGridRow(nextIndex, cols, prevRow)) {
          nextIndex = findNonDisabledListIndex(listRef, {
            startingIndex: prevIndex + (cols - prevIndex % cols),
            decrement: true,
            disabledIndices
          });
        }
      } else if (loop) {
        nextIndex = findNonDisabledListIndex(listRef, {
          startingIndex: prevIndex + (cols - prevIndex % cols),
          decrement: true,
          disabledIndices
        });
      }
      if (isDifferentGridRow(nextIndex, cols, prevRow)) {
        nextIndex = prevIndex;
      }
    }
    const lastRow = floor2(maxIndex / cols) === prevRow;
    if (isIndexOutOfListBounds(listRef, nextIndex)) {
      if (loop && lastRow) {
        nextIndex = event.key === (rtl ? ARROW_RIGHT : ARROW_LEFT) ? maxIndex : findNonDisabledListIndex(listRef, {
          startingIndex: prevIndex - prevIndex % cols - 1,
          disabledIndices
        });
      } else {
        nextIndex = prevIndex;
      }
    }
  }
  return nextIndex;
}
function createGridCellMap(sizes, cols, dense) {
  const cellMap = [];
  let startIndex = 0;
  sizes.forEach((_ref2, index4) => {
    let {
      width,
      height
    } = _ref2;
    if (width > cols) {
      if (true) {
        throw new Error("[Floating UI]: Invalid grid - item width at index " + index4 + " is greater than grid columns");
      }
    }
    let itemPlaced = false;
    if (dense) {
      startIndex = 0;
    }
    while (!itemPlaced) {
      const targetCells = [];
      for (let i3 = 0; i3 < width; i3++) {
        for (let j4 = 0; j4 < height; j4++) {
          targetCells.push(startIndex + i3 + j4 * cols);
        }
      }
      if (startIndex % cols + width <= cols && targetCells.every((cell2) => cellMap[cell2] == null)) {
        targetCells.forEach((cell2) => {
          cellMap[cell2] = index4;
        });
        itemPlaced = true;
      } else {
        startIndex++;
      }
    }
  });
  return [...cellMap];
}
function getGridCellIndexOfCorner(index4, sizes, cellMap, cols, corner) {
  if (index4 === -1) return -1;
  const firstCellIndex = cellMap.indexOf(index4);
  const sizeItem = sizes[index4];
  switch (corner) {
    case "tl":
      return firstCellIndex;
    case "tr":
      if (!sizeItem) {
        return firstCellIndex;
      }
      return firstCellIndex + sizeItem.width - 1;
    case "bl":
      if (!sizeItem) {
        return firstCellIndex;
      }
      return firstCellIndex + (sizeItem.height - 1) * cols;
    case "br":
      return cellMap.lastIndexOf(index4);
  }
}
function getGridCellIndices(indices, cellMap) {
  return cellMap.flatMap((index4, cellIndex) => indices.includes(index4) ? [cellIndex] : []);
}
function isListIndexDisabled(listRef, index4, disabledIndices) {
  if (typeof disabledIndices === "function") {
    return disabledIndices(index4);
  } else if (disabledIndices) {
    return disabledIndices.includes(index4);
  }
  const element7 = listRef.current[index4];
  return element7 == null || element7.hasAttribute("disabled") || element7.getAttribute("aria-disabled") === "true";
}

// ../../node_modules/.pnpm/@floating-ui+react@0.27.16_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@floating-ui/react/dist/floating-ui.react.mjs
var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
var ReactDOM2 = __toESM(require_react_dom(), 1);

// ../../node_modules/.pnpm/@floating-ui+core@1.7.3/node_modules/@floating-ui/core/dist/floating-ui.core.mjs
function computeCoordsFromPlacement(_ref, placement, rtl) {
  let {
    reference,
    floating
  } = _ref;
  const sideAxis = getSideAxis(placement);
  const alignmentAxis = getAlignmentAxis(placement);
  const alignLength = getAxisLength(alignmentAxis);
  const side = getSide2(placement);
  const isVertical = sideAxis === "y";
  const commonX = reference.x + reference.width / 2 - floating.width / 2;
  const commonY = reference.y + reference.height / 2 - floating.height / 2;
  const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
  let coords;
  switch (side) {
    case "top":
      coords = {
        x: commonX,
        y: reference.y - floating.height
      };
      break;
    case "bottom":
      coords = {
        x: commonX,
        y: reference.y + reference.height
      };
      break;
    case "right":
      coords = {
        x: reference.x + reference.width,
        y: commonY
      };
      break;
    case "left":
      coords = {
        x: reference.x - floating.width,
        y: commonY
      };
      break;
    default:
      coords = {
        x: reference.x,
        y: reference.y
      };
  }
  switch (getAlignment(placement)) {
    case "start":
      coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
      break;
    case "end":
      coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
      break;
  }
  return coords;
}
var computePosition = async (reference, floating, config) => {
  const {
    placement = "bottom",
    strategy = "absolute",
    middleware = [],
    platform: platform2
  } = config;
  const validMiddleware = middleware.filter(Boolean);
  const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(floating));
  let rects = await platform2.getElementRects({
    reference,
    floating,
    strategy
  });
  let {
    x: x5,
    y: y3
  } = computeCoordsFromPlacement(rects, placement, rtl);
  let statefulPlacement = placement;
  let middlewareData = {};
  let resetCount = 0;
  for (let i3 = 0; i3 < validMiddleware.length; i3++) {
    const {
      name,
      fn: fn4
    } = validMiddleware[i3];
    const {
      x: nextX,
      y: nextY,
      data,
      reset: reset2
    } = await fn4({
      x: x5,
      y: y3,
      initialPlacement: placement,
      placement: statefulPlacement,
      strategy,
      middlewareData,
      rects,
      platform: platform2,
      elements: {
        reference,
        floating
      }
    });
    x5 = nextX != null ? nextX : x5;
    y3 = nextY != null ? nextY : y3;
    middlewareData = {
      ...middlewareData,
      [name]: {
        ...middlewareData[name],
        ...data
      }
    };
    if (reset2 && resetCount <= 50) {
      resetCount++;
      if (typeof reset2 === "object") {
        if (reset2.placement) {
          statefulPlacement = reset2.placement;
        }
        if (reset2.rects) {
          rects = reset2.rects === true ? await platform2.getElementRects({
            reference,
            floating,
            strategy
          }) : reset2.rects;
        }
        ({
          x: x5,
          y: y3
        } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
      }
      i3 = -1;
    }
  }
  return {
    x: x5,
    y: y3,
    placement: statefulPlacement,
    strategy,
    middlewareData
  };
};
async function detectOverflow(state, options2) {
  var _await$platform$isEle;
  if (options2 === void 0) {
    options2 = {};
  }
  const {
    x: x5,
    y: y3,
    platform: platform2,
    rects,
    elements,
    strategy
  } = state;
  const {
    boundary = "clippingAncestors",
    rootBoundary = "viewport",
    elementContext = "floating",
    altBoundary = false,
    padding = 0
  } = evaluate(options2, state);
  const paddingObject = getPaddingObject(padding);
  const altContext = elementContext === "floating" ? "reference" : "floating";
  const element7 = elements[altBoundary ? altContext : elementContext];
  const clippingClientRect = rectToClientRect(await platform2.getClippingRect({
    element: ((_await$platform$isEle = await (platform2.isElement == null ? void 0 : platform2.isElement(element7))) != null ? _await$platform$isEle : true) ? element7 : element7.contextElement || await (platform2.getDocumentElement == null ? void 0 : platform2.getDocumentElement(elements.floating)),
    boundary,
    rootBoundary,
    strategy
  }));
  const rect = elementContext === "floating" ? {
    x: x5,
    y: y3,
    width: rects.floating.width,
    height: rects.floating.height
  } : rects.reference;
  const offsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(elements.floating));
  const offsetScale = await (platform2.isElement == null ? void 0 : platform2.isElement(offsetParent)) ? await (platform2.getScale == null ? void 0 : platform2.getScale(offsetParent)) || {
    x: 1,
    y: 1
  } : {
    x: 1,
    y: 1
  };
  const elementClientRect = rectToClientRect(platform2.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform2.convertOffsetParentRelativeRectToViewportRelativeRect({
    elements,
    rect,
    offsetParent,
    strategy
  }) : rect);
  return {
    top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
    bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
    left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
    right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
  };
}
var arrow2 = (options2) => ({
  name: "arrow",
  options: options2,
  async fn(state) {
    const {
      x: x5,
      y: y3,
      placement,
      rects,
      platform: platform2,
      elements,
      middlewareData
    } = state;
    const {
      element: element7,
      padding = 0
    } = evaluate(options2, state) || {};
    if (element7 == null) {
      return {};
    }
    const paddingObject = getPaddingObject(padding);
    const coords = {
      x: x5,
      y: y3
    };
    const axis = getAlignmentAxis(placement);
    const length2 = getAxisLength(axis);
    const arrowDimensions = await platform2.getDimensions(element7);
    const isYAxis = axis === "y";
    const minProp = isYAxis ? "top" : "left";
    const maxProp = isYAxis ? "bottom" : "right";
    const clientProp = isYAxis ? "clientHeight" : "clientWidth";
    const endDiff = rects.reference[length2] + rects.reference[axis] - coords[axis] - rects.floating[length2];
    const startDiff = coords[axis] - rects.reference[axis];
    const arrowOffsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(element7));
    let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0;
    if (!clientSize || !await (platform2.isElement == null ? void 0 : platform2.isElement(arrowOffsetParent))) {
      clientSize = elements.floating[clientProp] || rects.floating[length2];
    }
    const centerToReference = endDiff / 2 - startDiff / 2;
    const largestPossiblePadding = clientSize / 2 - arrowDimensions[length2] / 2 - 1;
    const minPadding = min2(paddingObject[minProp], largestPossiblePadding);
    const maxPadding = min2(paddingObject[maxProp], largestPossiblePadding);
    const min$1 = minPadding;
    const max3 = clientSize - arrowDimensions[length2] - maxPadding;
    const center = clientSize / 2 - arrowDimensions[length2] / 2 + centerToReference;
    const offset4 = clamp(min$1, center, max3);
    const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset4 && rects.reference[length2] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length2] / 2 < 0;
    const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max3 : 0;
    return {
      [axis]: coords[axis] + alignmentOffset,
      data: {
        [axis]: offset4,
        centerOffset: center - offset4 - alignmentOffset,
        ...shouldAddOffset && {
          alignmentOffset
        }
      },
      reset: shouldAddOffset
    };
  }
});
function getPlacementList(alignment, autoAlignment, allowedPlacements) {
  const allowedPlacementsSortedByAlignment = alignment ? [...allowedPlacements.filter((placement) => getAlignment(placement) === alignment), ...allowedPlacements.filter((placement) => getAlignment(placement) !== alignment)] : allowedPlacements.filter((placement) => getSide2(placement) === placement);
  return allowedPlacementsSortedByAlignment.filter((placement) => {
    if (alignment) {
      return getAlignment(placement) === alignment || (autoAlignment ? getOppositeAlignmentPlacement(placement) !== placement : false);
    }
    return true;
  });
}
var autoPlacement = function(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  return {
    name: "autoPlacement",
    options: options2,
    async fn(state) {
      var _middlewareData$autoP, _middlewareData$autoP2, _placementsThatFitOnE;
      const {
        rects,
        middlewareData,
        placement,
        platform: platform2,
        elements
      } = state;
      const {
        crossAxis = false,
        alignment,
        allowedPlacements = placements,
        autoAlignment = true,
        ...detectOverflowOptions
      } = evaluate(options2, state);
      const placements$1 = alignment !== void 0 || allowedPlacements === placements ? getPlacementList(alignment || null, autoAlignment, allowedPlacements) : allowedPlacements;
      const overflow = await detectOverflow(state, detectOverflowOptions);
      const currentIndex = ((_middlewareData$autoP = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP.index) || 0;
      const currentPlacement = placements$1[currentIndex];
      if (currentPlacement == null) {
        return {};
      }
      const alignmentSides = getAlignmentSides(currentPlacement, rects, await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating)));
      if (placement !== currentPlacement) {
        return {
          reset: {
            placement: placements$1[0]
          }
        };
      }
      const currentOverflows = [overflow[getSide2(currentPlacement)], overflow[alignmentSides[0]], overflow[alignmentSides[1]]];
      const allOverflows = [...((_middlewareData$autoP2 = middlewareData.autoPlacement) == null ? void 0 : _middlewareData$autoP2.overflows) || [], {
        placement: currentPlacement,
        overflows: currentOverflows
      }];
      const nextPlacement = placements$1[currentIndex + 1];
      if (nextPlacement) {
        return {
          data: {
            index: currentIndex + 1,
            overflows: allOverflows
          },
          reset: {
            placement: nextPlacement
          }
        };
      }
      const placementsSortedByMostSpace = allOverflows.map((d) => {
        const alignment2 = getAlignment(d.placement);
        return [d.placement, alignment2 && crossAxis ? (
          // Check along the mainAxis and main crossAxis side.
          d.overflows.slice(0, 2).reduce((acc, v8) => acc + v8, 0)
        ) : (
          // Check only the mainAxis.
          d.overflows[0]
        ), d.overflows];
      }).sort((a3, b4) => a3[1] - b4[1]);
      const placementsThatFitOnEachSide = placementsSortedByMostSpace.filter((d) => d[2].slice(
        0,
        // Aligned placements should not check their opposite crossAxis
        // side.
        getAlignment(d[0]) ? 2 : 3
      ).every((v8) => v8 <= 0));
      const resetPlacement = ((_placementsThatFitOnE = placementsThatFitOnEachSide[0]) == null ? void 0 : _placementsThatFitOnE[0]) || placementsSortedByMostSpace[0][0];
      if (resetPlacement !== placement) {
        return {
          data: {
            index: currentIndex + 1,
            overflows: allOverflows
          },
          reset: {
            placement: resetPlacement
          }
        };
      }
      return {};
    }
  };
};
var flip = function(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  return {
    name: "flip",
    options: options2,
    async fn(state) {
      var _middlewareData$arrow, _middlewareData$flip;
      const {
        placement,
        middlewareData,
        rects,
        initialPlacement,
        platform: platform2,
        elements
      } = state;
      const {
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = true,
        fallbackPlacements: specifiedFallbackPlacements,
        fallbackStrategy = "bestFit",
        fallbackAxisSideDirection = "none",
        flipAlignment = true,
        ...detectOverflowOptions
      } = evaluate(options2, state);
      if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
        return {};
      }
      const side = getSide2(placement);
      const initialSideAxis = getSideAxis(initialPlacement);
      const isBasePlacement = getSide2(initialPlacement) === initialPlacement;
      const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
      const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
      const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== "none";
      if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {
        fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
      }
      const placements2 = [initialPlacement, ...fallbackPlacements];
      const overflow = await detectOverflow(state, detectOverflowOptions);
      const overflows = [];
      let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
      if (checkMainAxis) {
        overflows.push(overflow[side]);
      }
      if (checkCrossAxis) {
        const sides2 = getAlignmentSides(placement, rects, rtl);
        overflows.push(overflow[sides2[0]], overflow[sides2[1]]);
      }
      overflowsData = [...overflowsData, {
        placement,
        overflows
      }];
      if (!overflows.every((side2) => side2 <= 0)) {
        var _middlewareData$flip2, _overflowsData$filter;
        const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
        const nextPlacement = placements2[nextIndex];
        if (nextPlacement) {
          const ignoreCrossAxisOverflow = checkCrossAxis === "alignment" ? initialSideAxis !== getSideAxis(nextPlacement) : false;
          if (!ignoreCrossAxisOverflow || // We leave the current main axis only if every placement on that axis
          // overflows the main axis.
          overflowsData.every((d) => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) {
            return {
              data: {
                index: nextIndex,
                overflows: overflowsData
              },
              reset: {
                placement: nextPlacement
              }
            };
          }
        }
        let resetPlacement = (_overflowsData$filter = overflowsData.filter((d) => d.overflows[0] <= 0).sort((a3, b4) => a3.overflows[1] - b4.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
        if (!resetPlacement) {
          switch (fallbackStrategy) {
            case "bestFit": {
              var _overflowsData$filter2;
              const placement2 = (_overflowsData$filter2 = overflowsData.filter((d) => {
                if (hasFallbackAxisSideDirection) {
                  const currentSideAxis = getSideAxis(d.placement);
                  return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal
                  // reading directions favoring greater width.
                  currentSideAxis === "y";
                }
                return true;
              }).map((d) => [d.placement, d.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a3, b4) => a3[1] - b4[1])[0]) == null ? void 0 : _overflowsData$filter2[0];
              if (placement2) {
                resetPlacement = placement2;
              }
              break;
            }
            case "initialPlacement":
              resetPlacement = initialPlacement;
              break;
          }
        }
        if (placement !== resetPlacement) {
          return {
            reset: {
              placement: resetPlacement
            }
          };
        }
      }
      return {};
    }
  };
};
function getSideOffsets(overflow, rect) {
  return {
    top: overflow.top - rect.height,
    right: overflow.right - rect.width,
    bottom: overflow.bottom - rect.height,
    left: overflow.left - rect.width
  };
}
function isAnySideFullyClipped(overflow) {
  return sides.some((side) => overflow[side] >= 0);
}
var hide = function(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  return {
    name: "hide",
    options: options2,
    async fn(state) {
      const {
        rects
      } = state;
      const {
        strategy = "referenceHidden",
        ...detectOverflowOptions
      } = evaluate(options2, state);
      switch (strategy) {
        case "referenceHidden": {
          const overflow = await detectOverflow(state, {
            ...detectOverflowOptions,
            elementContext: "reference"
          });
          const offsets = getSideOffsets(overflow, rects.reference);
          return {
            data: {
              referenceHiddenOffsets: offsets,
              referenceHidden: isAnySideFullyClipped(offsets)
            }
          };
        }
        case "escaped": {
          const overflow = await detectOverflow(state, {
            ...detectOverflowOptions,
            altBoundary: true
          });
          const offsets = getSideOffsets(overflow, rects.floating);
          return {
            data: {
              escapedOffsets: offsets,
              escaped: isAnySideFullyClipped(offsets)
            }
          };
        }
        default: {
          return {};
        }
      }
    }
  };
};
var originSides = /* @__PURE__ */ new Set(["left", "top"]);
async function convertValueToCoords(state, options2) {
  const {
    placement,
    platform: platform2,
    elements
  } = state;
  const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
  const side = getSide2(placement);
  const alignment = getAlignment(placement);
  const isVertical = getSideAxis(placement) === "y";
  const mainAxisMulti = originSides.has(side) ? -1 : 1;
  const crossAxisMulti = rtl && isVertical ? -1 : 1;
  const rawValue = evaluate(options2, state);
  let {
    mainAxis,
    crossAxis,
    alignmentAxis
  } = typeof rawValue === "number" ? {
    mainAxis: rawValue,
    crossAxis: 0,
    alignmentAxis: null
  } : {
    mainAxis: rawValue.mainAxis || 0,
    crossAxis: rawValue.crossAxis || 0,
    alignmentAxis: rawValue.alignmentAxis
  };
  if (alignment && typeof alignmentAxis === "number") {
    crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis;
  }
  return isVertical ? {
    x: crossAxis * crossAxisMulti,
    y: mainAxis * mainAxisMulti
  } : {
    x: mainAxis * mainAxisMulti,
    y: crossAxis * crossAxisMulti
  };
}
var offset = function(options2) {
  if (options2 === void 0) {
    options2 = 0;
  }
  return {
    name: "offset",
    options: options2,
    async fn(state) {
      var _middlewareData$offse, _middlewareData$arrow;
      const {
        x: x5,
        y: y3,
        placement,
        middlewareData
      } = state;
      const diffCoords = await convertValueToCoords(state, options2);
      if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
        return {};
      }
      return {
        x: x5 + diffCoords.x,
        y: y3 + diffCoords.y,
        data: {
          ...diffCoords,
          placement
        }
      };
    }
  };
};
var shift2 = function(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  return {
    name: "shift",
    options: options2,
    async fn(state) {
      const {
        x: x5,
        y: y3,
        placement
      } = state;
      const {
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = false,
        limiter = {
          fn: (_ref) => {
            let {
              x: x6,
              y: y4
            } = _ref;
            return {
              x: x6,
              y: y4
            };
          }
        },
        ...detectOverflowOptions
      } = evaluate(options2, state);
      const coords = {
        x: x5,
        y: y3
      };
      const overflow = await detectOverflow(state, detectOverflowOptions);
      const crossAxis = getSideAxis(getSide2(placement));
      const mainAxis = getOppositeAxis(crossAxis);
      let mainAxisCoord = coords[mainAxis];
      let crossAxisCoord = coords[crossAxis];
      if (checkMainAxis) {
        const minSide = mainAxis === "y" ? "top" : "left";
        const maxSide = mainAxis === "y" ? "bottom" : "right";
        const min3 = mainAxisCoord + overflow[minSide];
        const max3 = mainAxisCoord - overflow[maxSide];
        mainAxisCoord = clamp(min3, mainAxisCoord, max3);
      }
      if (checkCrossAxis) {
        const minSide = crossAxis === "y" ? "top" : "left";
        const maxSide = crossAxis === "y" ? "bottom" : "right";
        const min3 = crossAxisCoord + overflow[minSide];
        const max3 = crossAxisCoord - overflow[maxSide];
        crossAxisCoord = clamp(min3, crossAxisCoord, max3);
      }
      const limitedCoords = limiter.fn({
        ...state,
        [mainAxis]: mainAxisCoord,
        [crossAxis]: crossAxisCoord
      });
      return {
        ...limitedCoords,
        data: {
          x: limitedCoords.x - x5,
          y: limitedCoords.y - y3,
          enabled: {
            [mainAxis]: checkMainAxis,
            [crossAxis]: checkCrossAxis
          }
        }
      };
    }
  };
};
var limitShift = function(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  return {
    options: options2,
    fn(state) {
      const {
        x: x5,
        y: y3,
        placement,
        rects,
        middlewareData
      } = state;
      const {
        offset: offset4 = 0,
        mainAxis: checkMainAxis = true,
        crossAxis: checkCrossAxis = true
      } = evaluate(options2, state);
      const coords = {
        x: x5,
        y: y3
      };
      const crossAxis = getSideAxis(placement);
      const mainAxis = getOppositeAxis(crossAxis);
      let mainAxisCoord = coords[mainAxis];
      let crossAxisCoord = coords[crossAxis];
      const rawOffset = evaluate(offset4, state);
      const computedOffset = typeof rawOffset === "number" ? {
        mainAxis: rawOffset,
        crossAxis: 0
      } : {
        mainAxis: 0,
        crossAxis: 0,
        ...rawOffset
      };
      if (checkMainAxis) {
        const len = mainAxis === "y" ? "height" : "width";
        const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis;
        const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis;
        if (mainAxisCoord < limitMin) {
          mainAxisCoord = limitMin;
        } else if (mainAxisCoord > limitMax) {
          mainAxisCoord = limitMax;
        }
      }
      if (checkCrossAxis) {
        var _middlewareData$offse, _middlewareData$offse2;
        const len = mainAxis === "y" ? "width" : "height";
        const isOriginSide = originSides.has(getSide2(placement));
        const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis);
        const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0);
        if (crossAxisCoord < limitMin) {
          crossAxisCoord = limitMin;
        } else if (crossAxisCoord > limitMax) {
          crossAxisCoord = limitMax;
        }
      }
      return {
        [mainAxis]: mainAxisCoord,
        [crossAxis]: crossAxisCoord
      };
    }
  };
};
var size2 = function(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  return {
    name: "size",
    options: options2,
    async fn(state) {
      var _state$middlewareData, _state$middlewareData2;
      const {
        placement,
        rects,
        platform: platform2,
        elements
      } = state;
      const {
        apply: apply2 = () => {
        },
        ...detectOverflowOptions
      } = evaluate(options2, state);
      const overflow = await detectOverflow(state, detectOverflowOptions);
      const side = getSide2(placement);
      const alignment = getAlignment(placement);
      const isYAxis = getSideAxis(placement) === "y";
      const {
        width,
        height
      } = rects.floating;
      let heightSide;
      let widthSide;
      if (side === "top" || side === "bottom") {
        heightSide = side;
        widthSide = alignment === (await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating)) ? "start" : "end") ? "left" : "right";
      } else {
        widthSide = side;
        heightSide = alignment === "end" ? "top" : "bottom";
      }
      const maximumClippingHeight = height - overflow.top - overflow.bottom;
      const maximumClippingWidth = width - overflow.left - overflow.right;
      const overflowAvailableHeight = min2(height - overflow[heightSide], maximumClippingHeight);
      const overflowAvailableWidth = min2(width - overflow[widthSide], maximumClippingWidth);
      const noShift = !state.middlewareData.shift;
      let availableHeight = overflowAvailableHeight;
      let availableWidth = overflowAvailableWidth;
      if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) {
        availableWidth = maximumClippingWidth;
      }
      if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) {
        availableHeight = maximumClippingHeight;
      }
      if (noShift && !alignment) {
        const xMin = max2(overflow.left, 0);
        const xMax = max2(overflow.right, 0);
        const yMin = max2(overflow.top, 0);
        const yMax = max2(overflow.bottom, 0);
        if (isYAxis) {
          availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max2(overflow.left, overflow.right));
        } else {
          availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max2(overflow.top, overflow.bottom));
        }
      }
      await apply2({
        ...state,
        availableWidth,
        availableHeight
      });
      const nextDimensions = await platform2.getDimensions(elements.floating);
      if (width !== nextDimensions.width || height !== nextDimensions.height) {
        return {
          reset: {
            rects: true
          }
        };
      }
      return {};
    }
  };
};

// ../../node_modules/.pnpm/@floating-ui+dom@1.7.4/node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs
function getCssDimensions(element7) {
  const css = getComputedStyle2(element7);
  let width = parseFloat(css.width) || 0;
  let height = parseFloat(css.height) || 0;
  const hasOffset = isHTMLElement(element7);
  const offsetWidth = hasOffset ? element7.offsetWidth : width;
  const offsetHeight = hasOffset ? element7.offsetHeight : height;
  const shouldFallback = round2(width) !== offsetWidth || round2(height) !== offsetHeight;
  if (shouldFallback) {
    width = offsetWidth;
    height = offsetHeight;
  }
  return {
    width,
    height,
    $: shouldFallback
  };
}
function unwrapElement(element7) {
  return !isElement2(element7) ? element7.contextElement : element7;
}
function getScale(element7) {
  const domElement = unwrapElement(element7);
  if (!isHTMLElement(domElement)) {
    return createCoords(1);
  }
  const rect = domElement.getBoundingClientRect();
  const {
    width,
    height,
    $: $6
  } = getCssDimensions(domElement);
  let x5 = ($6 ? round2(rect.width) : rect.width) / width;
  let y3 = ($6 ? round2(rect.height) : rect.height) / height;
  if (!x5 || !Number.isFinite(x5)) {
    x5 = 1;
  }
  if (!y3 || !Number.isFinite(y3)) {
    y3 = 1;
  }
  return {
    x: x5,
    y: y3
  };
}
var noOffsets = createCoords(0);
function getVisualOffsets(element7) {
  const win = getWindow(element7);
  if (!isWebKit() || !win.visualViewport) {
    return noOffsets;
  }
  return {
    x: win.visualViewport.offsetLeft,
    y: win.visualViewport.offsetTop
  };
}
function shouldAddVisualOffsets(element7, isFixed, floatingOffsetParent) {
  if (isFixed === void 0) {
    isFixed = false;
  }
  if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element7)) {
    return false;
  }
  return isFixed;
}
function getBoundingClientRect(element7, includeScale, isFixedStrategy, offsetParent) {
  if (includeScale === void 0) {
    includeScale = false;
  }
  if (isFixedStrategy === void 0) {
    isFixedStrategy = false;
  }
  const clientRect2 = element7.getBoundingClientRect();
  const domElement = unwrapElement(element7);
  let scale = createCoords(1);
  if (includeScale) {
    if (offsetParent) {
      if (isElement2(offsetParent)) {
        scale = getScale(offsetParent);
      }
    } else {
      scale = getScale(element7);
    }
  }
  const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
  let x5 = (clientRect2.left + visualOffsets.x) / scale.x;
  let y3 = (clientRect2.top + visualOffsets.y) / scale.y;
  let width = clientRect2.width / scale.x;
  let height = clientRect2.height / scale.y;
  if (domElement) {
    const win = getWindow(domElement);
    const offsetWin = offsetParent && isElement2(offsetParent) ? getWindow(offsetParent) : offsetParent;
    let currentWin = win;
    let currentIFrame = getFrameElement(currentWin);
    while (currentIFrame && offsetParent && offsetWin !== currentWin) {
      const iframeScale = getScale(currentIFrame);
      const iframeRect = currentIFrame.getBoundingClientRect();
      const css = getComputedStyle2(currentIFrame);
      const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
      const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
      x5 *= iframeScale.x;
      y3 *= iframeScale.y;
      width *= iframeScale.x;
      height *= iframeScale.y;
      x5 += left;
      y3 += top;
      currentWin = getWindow(currentIFrame);
      currentIFrame = getFrameElement(currentWin);
    }
  }
  return rectToClientRect({
    width,
    height,
    x: x5,
    y: y3
  });
}
function getWindowScrollBarX(element7, rect) {
  const leftScroll = getNodeScroll(element7).scrollLeft;
  if (!rect) {
    return getBoundingClientRect(getDocumentElement(element7)).left + leftScroll;
  }
  return rect.left + leftScroll;
}
function getHTMLOffset(documentElement, scroll) {
  const htmlRect = documentElement.getBoundingClientRect();
  const x5 = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);
  const y3 = htmlRect.top + scroll.scrollTop;
  return {
    x: x5,
    y: y3
  };
}
function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
  let {
    elements,
    rect,
    offsetParent,
    strategy
  } = _ref;
  const isFixed = strategy === "fixed";
  const documentElement = getDocumentElement(offsetParent);
  const topLayer = elements ? isTopLayer(elements.floating) : false;
  if (offsetParent === documentElement || topLayer && isFixed) {
    return rect;
  }
  let scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  let scale = createCoords(1);
  const offsets = createCoords(0);
  const isOffsetParentAnElement = isHTMLElement(offsetParent);
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isHTMLElement(offsetParent)) {
      const offsetRect = getBoundingClientRect(offsetParent);
      scale = getScale(offsetParent);
      offsets.x = offsetRect.x + offsetParent.clientLeft;
      offsets.y = offsetRect.y + offsetParent.clientTop;
    }
  }
  const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
  return {
    width: rect.width * scale.x,
    height: rect.height * scale.y,
    x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,
    y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y
  };
}
function getClientRects(element7) {
  return Array.from(element7.getClientRects());
}
function getDocumentRect(element7) {
  const html7 = getDocumentElement(element7);
  const scroll = getNodeScroll(element7);
  const body3 = element7.ownerDocument.body;
  const width = max2(html7.scrollWidth, html7.clientWidth, body3.scrollWidth, body3.clientWidth);
  const height = max2(html7.scrollHeight, html7.clientHeight, body3.scrollHeight, body3.clientHeight);
  let x5 = -scroll.scrollLeft + getWindowScrollBarX(element7);
  const y3 = -scroll.scrollTop;
  if (getComputedStyle2(body3).direction === "rtl") {
    x5 += max2(html7.clientWidth, body3.clientWidth) - width;
  }
  return {
    width,
    height,
    x: x5,
    y: y3
  };
}
var SCROLLBAR_MAX = 25;
function getViewportRect(element7, strategy) {
  const win = getWindow(element7);
  const html7 = getDocumentElement(element7);
  const visualViewport = win.visualViewport;
  let width = html7.clientWidth;
  let height = html7.clientHeight;
  let x5 = 0;
  let y3 = 0;
  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    const visualViewportBased = isWebKit();
    if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
      x5 = visualViewport.offsetLeft;
      y3 = visualViewport.offsetTop;
    }
  }
  const windowScrollbarX = getWindowScrollBarX(html7);
  if (windowScrollbarX <= 0) {
    const doc4 = html7.ownerDocument;
    const body3 = doc4.body;
    const bodyStyles = getComputedStyle(body3);
    const bodyMarginInline = doc4.compatMode === "CSS1Compat" ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;
    const clippingStableScrollbarWidth = Math.abs(html7.clientWidth - body3.clientWidth - bodyMarginInline);
    if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {
      width -= clippingStableScrollbarWidth;
    }
  } else if (windowScrollbarX <= SCROLLBAR_MAX) {
    width += windowScrollbarX;
  }
  return {
    width,
    height,
    x: x5,
    y: y3
  };
}
var absoluteOrFixed = /* @__PURE__ */ new Set(["absolute", "fixed"]);
function getInnerBoundingClientRect(element7, strategy) {
  const clientRect2 = getBoundingClientRect(element7, true, strategy === "fixed");
  const top = clientRect2.top + element7.clientTop;
  const left = clientRect2.left + element7.clientLeft;
  const scale = isHTMLElement(element7) ? getScale(element7) : createCoords(1);
  const width = element7.clientWidth * scale.x;
  const height = element7.clientHeight * scale.y;
  const x5 = left * scale.x;
  const y3 = top * scale.y;
  return {
    width,
    height,
    x: x5,
    y: y3
  };
}
function getClientRectFromClippingAncestor(element7, clippingAncestor, strategy) {
  let rect;
  if (clippingAncestor === "viewport") {
    rect = getViewportRect(element7, strategy);
  } else if (clippingAncestor === "document") {
    rect = getDocumentRect(getDocumentElement(element7));
  } else if (isElement2(clippingAncestor)) {
    rect = getInnerBoundingClientRect(clippingAncestor, strategy);
  } else {
    const visualOffsets = getVisualOffsets(element7);
    rect = {
      x: clippingAncestor.x - visualOffsets.x,
      y: clippingAncestor.y - visualOffsets.y,
      width: clippingAncestor.width,
      height: clippingAncestor.height
    };
  }
  return rectToClientRect(rect);
}
function hasFixedPositionAncestor(element7, stopNode) {
  const parentNode2 = getParentNode(element7);
  if (parentNode2 === stopNode || !isElement2(parentNode2) || isLastTraversableNode(parentNode2)) {
    return false;
  }
  return getComputedStyle2(parentNode2).position === "fixed" || hasFixedPositionAncestor(parentNode2, stopNode);
}
function getClippingElementAncestors(element7, cache) {
  const cachedResult2 = cache.get(element7);
  if (cachedResult2) {
    return cachedResult2;
  }
  let result = getOverflowAncestors(element7, [], false).filter((el2) => isElement2(el2) && getNodeName(el2) !== "body");
  let currentContainingBlockComputedStyle = null;
  const elementIsFixed = getComputedStyle2(element7).position === "fixed";
  let currentNode = elementIsFixed ? getParentNode(element7) : element7;
  while (isElement2(currentNode) && !isLastTraversableNode(currentNode)) {
    const computedStyle = getComputedStyle2(currentNode);
    const currentNodeIsContaining = isContainingBlock(currentNode);
    if (!currentNodeIsContaining && computedStyle.position === "fixed") {
      currentContainingBlockComputedStyle = null;
    }
    const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && absoluteOrFixed.has(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element7, currentNode);
    if (shouldDropCurrentNode) {
      result = result.filter((ancestor) => ancestor !== currentNode);
    } else {
      currentContainingBlockComputedStyle = computedStyle;
    }
    currentNode = getParentNode(currentNode);
  }
  cache.set(element7, result);
  return result;
}
function getClippingRect(_ref) {
  let {
    element: element7,
    boundary,
    rootBoundary,
    strategy
  } = _ref;
  const elementClippingAncestors = boundary === "clippingAncestors" ? isTopLayer(element7) ? [] : getClippingElementAncestors(element7, this._c) : [].concat(boundary);
  const clippingAncestors = [...elementClippingAncestors, rootBoundary];
  const firstClippingAncestor = clippingAncestors[0];
  const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
    const rect = getClientRectFromClippingAncestor(element7, clippingAncestor, strategy);
    accRect.top = max2(rect.top, accRect.top);
    accRect.right = min2(rect.right, accRect.right);
    accRect.bottom = min2(rect.bottom, accRect.bottom);
    accRect.left = max2(rect.left, accRect.left);
    return accRect;
  }, getClientRectFromClippingAncestor(element7, firstClippingAncestor, strategy));
  return {
    width: clippingRect.right - clippingRect.left,
    height: clippingRect.bottom - clippingRect.top,
    x: clippingRect.left,
    y: clippingRect.top
  };
}
function getDimensions(element7) {
  const {
    width,
    height
  } = getCssDimensions(element7);
  return {
    width,
    height
  };
}
function getRectRelativeToOffsetParent(element7, offsetParent, strategy) {
  const isOffsetParentAnElement = isHTMLElement(offsetParent);
  const documentElement = getDocumentElement(offsetParent);
  const isFixed = strategy === "fixed";
  const rect = getBoundingClientRect(element7, true, isFixed, offsetParent);
  let scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  const offsets = createCoords(0);
  function setLeftRTLScrollbarOffset() {
    offsets.x = getWindowScrollBarX(documentElement);
  }
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isOffsetParentAnElement) {
      const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
      offsets.x = offsetRect.x + offsetParent.clientLeft;
      offsets.y = offsetRect.y + offsetParent.clientTop;
    } else if (documentElement) {
      setLeftRTLScrollbarOffset();
    }
  }
  if (isFixed && !isOffsetParentAnElement && documentElement) {
    setLeftRTLScrollbarOffset();
  }
  const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
  const x5 = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;
  const y3 = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;
  return {
    x: x5,
    y: y3,
    width: rect.width,
    height: rect.height
  };
}
function isStaticPositioned(element7) {
  return getComputedStyle2(element7).position === "static";
}
function getTrueOffsetParent(element7, polyfill) {
  if (!isHTMLElement(element7) || getComputedStyle2(element7).position === "fixed") {
    return null;
  }
  if (polyfill) {
    return polyfill(element7);
  }
  let rawOffsetParent = element7.offsetParent;
  if (getDocumentElement(element7) === rawOffsetParent) {
    rawOffsetParent = rawOffsetParent.ownerDocument.body;
  }
  return rawOffsetParent;
}
function getOffsetParent(element7, polyfill) {
  const win = getWindow(element7);
  if (isTopLayer(element7)) {
    return win;
  }
  if (!isHTMLElement(element7)) {
    let svgOffsetParent = getParentNode(element7);
    while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
      if (isElement2(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
        return svgOffsetParent;
      }
      svgOffsetParent = getParentNode(svgOffsetParent);
    }
    return win;
  }
  let offsetParent = getTrueOffsetParent(element7, polyfill);
  while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
    offsetParent = getTrueOffsetParent(offsetParent, polyfill);
  }
  if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
    return win;
  }
  return offsetParent || getContainingBlock(element7) || win;
}
var getElementRects = async function(data) {
  const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
  const getDimensionsFn = this.getDimensions;
  const floatingDimensions = await getDimensionsFn(data.floating);
  return {
    reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
    floating: {
      x: 0,
      y: 0,
      width: floatingDimensions.width,
      height: floatingDimensions.height
    }
  };
};
function isRTL(element7) {
  return getComputedStyle2(element7).direction === "rtl";
}
var platform = {
  convertOffsetParentRelativeRectToViewportRelativeRect,
  getDocumentElement,
  getClippingRect,
  getOffsetParent,
  getElementRects,
  getClientRects,
  getDimensions,
  getScale,
  isElement: isElement2,
  isRTL
};
function rectsAreEqual(a3, b4) {
  return a3.x === b4.x && a3.y === b4.y && a3.width === b4.width && a3.height === b4.height;
}
function observeMove(element7, onMove) {
  let io3 = null;
  let timeoutId;
  const root6 = getDocumentElement(element7);
  function cleanup2() {
    var _io;
    clearTimeout(timeoutId);
    (_io = io3) == null || _io.disconnect();
    io3 = null;
  }
  function refresh(skip, threshold) {
    if (skip === void 0) {
      skip = false;
    }
    if (threshold === void 0) {
      threshold = 1;
    }
    cleanup2();
    const elementRectForRootMargin = element7.getBoundingClientRect();
    const {
      left,
      top,
      width,
      height
    } = elementRectForRootMargin;
    if (!skip) {
      onMove();
    }
    if (!width || !height) {
      return;
    }
    const insetTop = floor2(top);
    const insetRight = floor2(root6.clientWidth - (left + width));
    const insetBottom = floor2(root6.clientHeight - (top + height));
    const insetLeft = floor2(left);
    const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px";
    const options2 = {
      rootMargin,
      threshold: max2(0, min2(1, threshold)) || 1
    };
    let isFirstUpdate = true;
    function handleObserve(entries) {
      const ratio = entries[0].intersectionRatio;
      if (ratio !== threshold) {
        if (!isFirstUpdate) {
          return refresh();
        }
        if (!ratio) {
          timeoutId = setTimeout(() => {
            refresh(false, 1e-7);
          }, 1e3);
        } else {
          refresh(false, ratio);
        }
      }
      if (ratio === 1 && !rectsAreEqual(elementRectForRootMargin, element7.getBoundingClientRect())) {
        refresh();
      }
      isFirstUpdate = false;
    }
    try {
      io3 = new IntersectionObserver(handleObserve, {
        ...options2,
        // Handle <iframe>s
        root: root6.ownerDocument
      });
    } catch (_e4) {
      io3 = new IntersectionObserver(handleObserve, options2);
    }
    io3.observe(element7);
  }
  refresh(true);
  return cleanup2;
}
function autoUpdate(reference, floating, update, options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  const {
    ancestorScroll = true,
    ancestorResize = true,
    elementResize = typeof ResizeObserver === "function",
    layoutShift = typeof IntersectionObserver === "function",
    animationFrame = false
  } = options2;
  const referenceEl = unwrapElement(reference);
  const ancestors = ancestorScroll || ancestorResize ? [...referenceEl ? getOverflowAncestors(referenceEl) : [], ...getOverflowAncestors(floating)] : [];
  ancestors.forEach((ancestor) => {
    ancestorScroll && ancestor.addEventListener("scroll", update, {
      passive: true
    });
    ancestorResize && ancestor.addEventListener("resize", update);
  });
  const cleanupIo = referenceEl && layoutShift ? observeMove(referenceEl, update) : null;
  let reobserveFrame = -1;
  let resizeObserver = null;
  if (elementResize) {
    resizeObserver = new ResizeObserver((_ref) => {
      let [firstEntry] = _ref;
      if (firstEntry && firstEntry.target === referenceEl && resizeObserver) {
        resizeObserver.unobserve(floating);
        cancelAnimationFrame(reobserveFrame);
        reobserveFrame = requestAnimationFrame(() => {
          var _resizeObserver;
          (_resizeObserver = resizeObserver) == null || _resizeObserver.observe(floating);
        });
      }
      update();
    });
    if (referenceEl && !animationFrame) {
      resizeObserver.observe(referenceEl);
    }
    resizeObserver.observe(floating);
  }
  let frameId;
  let prevRefRect = animationFrame ? getBoundingClientRect(reference) : null;
  if (animationFrame) {
    frameLoop();
  }
  function frameLoop() {
    const nextRefRect = getBoundingClientRect(reference);
    if (prevRefRect && !rectsAreEqual(prevRefRect, nextRefRect)) {
      update();
    }
    prevRefRect = nextRefRect;
    frameId = requestAnimationFrame(frameLoop);
  }
  update();
  return () => {
    var _resizeObserver2;
    ancestors.forEach((ancestor) => {
      ancestorScroll && ancestor.removeEventListener("scroll", update);
      ancestorResize && ancestor.removeEventListener("resize", update);
    });
    cleanupIo == null || cleanupIo();
    (_resizeObserver2 = resizeObserver) == null || _resizeObserver2.disconnect();
    resizeObserver = null;
    if (animationFrame) {
      cancelAnimationFrame(frameId);
    }
  };
}
var offset2 = offset;
var autoPlacement2 = autoPlacement;
var shift3 = shift2;
var flip2 = flip;
var size3 = size2;
var hide2 = hide;
var arrow3 = arrow2;
var limitShift2 = limitShift;
var computePosition2 = (reference, floating, options2) => {
  const cache = /* @__PURE__ */ new Map();
  const mergedOptions = {
    platform,
    ...options2
  };
  const platformWithCache = {
    ...mergedOptions.platform,
    _c: cache
  };
  return computePosition(reference, floating, {
    ...mergedOptions,
    platform: platformWithCache
  });
};

// ../../node_modules/.pnpm/@floating-ui+react-dom@2.1.6_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@floating-ui/react-dom/dist/floating-ui.react-dom.mjs
var React2 = __toESM(require_react(), 1);
var import_react2 = __toESM(require_react(), 1);
var ReactDOM = __toESM(require_react_dom(), 1);
var isClient2 = typeof document !== "undefined";
var noop3 = function noop4() {
};
var index3 = isClient2 ? import_react2.useLayoutEffect : noop3;
function deepEqual(a3, b4) {
  if (a3 === b4) {
    return true;
  }
  if (typeof a3 !== typeof b4) {
    return false;
  }
  if (typeof a3 === "function" && a3.toString() === b4.toString()) {
    return true;
  }
  let length2;
  let i3;
  let keys5;
  if (a3 && b4 && typeof a3 === "object") {
    if (Array.isArray(a3)) {
      length2 = a3.length;
      if (length2 !== b4.length) return false;
      for (i3 = length2; i3-- !== 0; ) {
        if (!deepEqual(a3[i3], b4[i3])) {
          return false;
        }
      }
      return true;
    }
    keys5 = Object.keys(a3);
    length2 = keys5.length;
    if (length2 !== Object.keys(b4).length) {
      return false;
    }
    for (i3 = length2; i3-- !== 0; ) {
      if (!{}.hasOwnProperty.call(b4, keys5[i3])) {
        return false;
      }
    }
    for (i3 = length2; i3-- !== 0; ) {
      const key2 = keys5[i3];
      if (key2 === "_owner" && a3.$$typeof) {
        continue;
      }
      if (!deepEqual(a3[key2], b4[key2])) {
        return false;
      }
    }
    return true;
  }
  return a3 !== a3 && b4 !== b4;
}
function getDPR(element7) {
  if (typeof window === "undefined") {
    return 1;
  }
  const win = element7.ownerDocument.defaultView || window;
  return win.devicePixelRatio || 1;
}
function roundByDPR(element7, value) {
  const dpr = getDPR(element7);
  return Math.round(value * dpr) / dpr;
}
function useLatestRef2(value) {
  const ref = React2.useRef(value);
  index3(() => {
    ref.current = value;
  });
  return ref;
}
function useFloating(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  const {
    placement = "bottom",
    strategy = "absolute",
    middleware = [],
    platform: platform2,
    elements: {
      reference: externalReference,
      floating: externalFloating
    } = {},
    transform: transform2 = true,
    whileElementsMounted,
    open
  } = options2;
  const [data, setData] = React2.useState({
    x: 0,
    y: 0,
    strategy,
    placement,
    middlewareData: {},
    isPositioned: false
  });
  const [latestMiddleware, setLatestMiddleware] = React2.useState(middleware);
  if (!deepEqual(latestMiddleware, middleware)) {
    setLatestMiddleware(middleware);
  }
  const [_reference, _setReference] = React2.useState(null);
  const [_floating, _setFloating] = React2.useState(null);
  const setReference = React2.useCallback((node2) => {
    if (node2 !== referenceRef.current) {
      referenceRef.current = node2;
      _setReference(node2);
    }
  }, []);
  const setFloating = React2.useCallback((node2) => {
    if (node2 !== floatingRef.current) {
      floatingRef.current = node2;
      _setFloating(node2);
    }
  }, []);
  const referenceEl = externalReference || _reference;
  const floatingEl = externalFloating || _floating;
  const referenceRef = React2.useRef(null);
  const floatingRef = React2.useRef(null);
  const dataRef = React2.useRef(data);
  const hasWhileElementsMounted = whileElementsMounted != null;
  const whileElementsMountedRef = useLatestRef2(whileElementsMounted);
  const platformRef = useLatestRef2(platform2);
  const openRef = useLatestRef2(open);
  const update = React2.useCallback(() => {
    if (!referenceRef.current || !floatingRef.current) {
      return;
    }
    const config = {
      placement,
      strategy,
      middleware: latestMiddleware
    };
    if (platformRef.current) {
      config.platform = platformRef.current;
    }
    computePosition2(referenceRef.current, floatingRef.current, config).then((data2) => {
      const fullData = {
        ...data2,
        // The floating element's position may be recomputed while it's closed
        // but still mounted (such as when transitioning out). To ensure
        // `isPositioned` will be `false` initially on the next open, avoid
        // setting it to `true` when `open === false` (must be specified).
        isPositioned: openRef.current !== false
      };
      if (isMountedRef.current && !deepEqual(dataRef.current, fullData)) {
        dataRef.current = fullData;
        ReactDOM.flushSync(() => {
          setData(fullData);
        });
      }
    });
  }, [latestMiddleware, placement, strategy, platformRef, openRef]);
  index3(() => {
    if (open === false && dataRef.current.isPositioned) {
      dataRef.current.isPositioned = false;
      setData((data2) => ({
        ...data2,
        isPositioned: false
      }));
    }
  }, [open]);
  const isMountedRef = React2.useRef(false);
  index3(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);
  index3(() => {
    if (referenceEl) referenceRef.current = referenceEl;
    if (floatingEl) floatingRef.current = floatingEl;
    if (referenceEl && floatingEl) {
      if (whileElementsMountedRef.current) {
        return whileElementsMountedRef.current(referenceEl, floatingEl, update);
      }
      update();
    }
  }, [referenceEl, floatingEl, update, whileElementsMountedRef, hasWhileElementsMounted]);
  const refs = React2.useMemo(() => ({
    reference: referenceRef,
    floating: floatingRef,
    setReference,
    setFloating
  }), [setReference, setFloating]);
  const elements = React2.useMemo(() => ({
    reference: referenceEl,
    floating: floatingEl
  }), [referenceEl, floatingEl]);
  const floatingStyles = React2.useMemo(() => {
    const initialStyles = {
      position: strategy,
      left: 0,
      top: 0
    };
    if (!elements.floating) {
      return initialStyles;
    }
    const x5 = roundByDPR(elements.floating, data.x);
    const y3 = roundByDPR(elements.floating, data.y);
    if (transform2) {
      return {
        ...initialStyles,
        transform: "translate(" + x5 + "px, " + y3 + "px)",
        ...getDPR(elements.floating) >= 1.5 && {
          willChange: "transform"
        }
      };
    }
    return {
      position: strategy,
      left: x5,
      top: y3
    };
  }, [strategy, transform2, elements.floating, data.x, data.y]);
  return React2.useMemo(() => ({
    ...data,
    update,
    refs,
    elements,
    floatingStyles
  }), [data, update, refs, elements, floatingStyles]);
}
var arrow$1 = (options2) => {
  function isRef(value) {
    return {}.hasOwnProperty.call(value, "current");
  }
  return {
    name: "arrow",
    options: options2,
    fn(state) {
      const {
        element: element7,
        padding
      } = typeof options2 === "function" ? options2(state) : options2;
      if (element7 && isRef(element7)) {
        if (element7.current != null) {
          return arrow3({
            element: element7.current,
            padding
          }).fn(state);
        }
        return {};
      }
      if (element7) {
        return arrow3({
          element: element7,
          padding
        }).fn(state);
      }
      return {};
    }
  };
};
var offset3 = (options2, deps) => ({
  ...offset2(options2),
  options: [options2, deps]
});
var shift4 = (options2, deps) => ({
  ...shift3(options2),
  options: [options2, deps]
});
var limitShift3 = (options2, deps) => ({
  ...limitShift2(options2),
  options: [options2, deps]
});
var flip3 = (options2, deps) => ({
  ...flip2(options2),
  options: [options2, deps]
});
var size4 = (options2, deps) => ({
  ...size3(options2),
  options: [options2, deps]
});
var autoPlacement3 = (options2, deps) => ({
  ...autoPlacement2(options2),
  options: [options2, deps]
});
var hide3 = (options2, deps) => ({
  ...hide2(options2),
  options: [options2, deps]
});
var arrow4 = (options2, deps) => ({
  ...arrow$1(options2),
  options: [options2, deps]
});

// ../../node_modules/.pnpm/@floating-ui+react@0.27.16_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@floating-ui/react/dist/floating-ui.react.mjs
function useMergeRefs(refs) {
  const cleanupRef = React3.useRef(void 0);
  const refEffect = React3.useCallback((instance) => {
    const cleanups = refs.map((ref) => {
      if (ref == null) {
        return;
      }
      if (typeof ref === "function") {
        const refCallback = ref;
        const refCleanup = refCallback(instance);
        return typeof refCleanup === "function" ? refCleanup : () => {
          refCallback(null);
        };
      }
      ref.current = instance;
      return () => {
        ref.current = null;
      };
    });
    return () => {
      cleanups.forEach((refCleanup) => refCleanup == null ? void 0 : refCleanup());
    };
  }, refs);
  return React3.useMemo(() => {
    if (refs.every((ref) => ref == null)) {
      return null;
    }
    return (value) => {
      if (cleanupRef.current) {
        cleanupRef.current();
        cleanupRef.current = void 0;
      }
      if (value != null) {
        cleanupRef.current = refEffect(value);
      }
    };
  }, refs);
}
function sortByDocumentPosition(a3, b4) {
  const position4 = a3.compareDocumentPosition(b4);
  if (position4 & Node.DOCUMENT_POSITION_FOLLOWING || position4 & Node.DOCUMENT_POSITION_CONTAINED_BY) {
    return -1;
  }
  if (position4 & Node.DOCUMENT_POSITION_PRECEDING || position4 & Node.DOCUMENT_POSITION_CONTAINS) {
    return 1;
  }
  return 0;
}
var FloatingListContext = React3.createContext({
  register: () => {
  },
  unregister: () => {
  },
  map: /* @__PURE__ */ new Map(),
  elementsRef: {
    current: []
  }
});
function FloatingList(props) {
  const {
    children,
    elementsRef,
    labelsRef
  } = props;
  const [nodes, setNodes] = React3.useState(() => /* @__PURE__ */ new Set());
  const register = React3.useCallback((node2) => {
    setNodes((prevSet) => new Set(prevSet).add(node2));
  }, []);
  const unregister = React3.useCallback((node2) => {
    setNodes((prevSet) => {
      const set = new Set(prevSet);
      set.delete(node2);
      return set;
    });
  }, []);
  const map7 = React3.useMemo(() => {
    const newMap = /* @__PURE__ */ new Map();
    const sortedNodes = Array.from(nodes.keys()).sort(sortByDocumentPosition);
    sortedNodes.forEach((node2, index4) => {
      newMap.set(node2, index4);
    });
    return newMap;
  }, [nodes]);
  return (0, import_jsx_runtime2.jsx)(FloatingListContext.Provider, {
    value: React3.useMemo(() => ({
      register,
      unregister,
      map: map7,
      elementsRef,
      labelsRef
    }), [register, unregister, map7, elementsRef, labelsRef]),
    children
  });
}
function useListItem(props) {
  if (props === void 0) {
    props = {};
  }
  const {
    label
  } = props;
  const {
    register,
    unregister,
    map: map7,
    elementsRef,
    labelsRef
  } = React3.useContext(FloatingListContext);
  const [index4, setIndex] = React3.useState(null);
  const componentRef = React3.useRef(null);
  const ref = React3.useCallback((node2) => {
    componentRef.current = node2;
    if (index4 !== null) {
      elementsRef.current[index4] = node2;
      if (labelsRef) {
        var _node$textContent;
        const isLabelDefined = label !== void 0;
        labelsRef.current[index4] = isLabelDefined ? label : (_node$textContent = node2 == null ? void 0 : node2.textContent) != null ? _node$textContent : null;
      }
    }
  }, [index4, elementsRef, labelsRef, label]);
  index2(() => {
    const node2 = componentRef.current;
    if (node2) {
      register(node2);
      return () => {
        unregister(node2);
      };
    }
  }, [register, unregister]);
  index2(() => {
    const index5 = componentRef.current ? map7.get(componentRef.current) : null;
    if (index5 != null) {
      setIndex(index5);
    }
  }, [map7]);
  return React3.useMemo(() => ({
    ref,
    index: index4 == null ? -1 : index4
  }), [index4, ref]);
}
var FOCUSABLE_ATTRIBUTE = "data-floating-ui-focusable";
var ACTIVE_KEY = "active";
var SELECTED_KEY = "selected";
var ARROW_LEFT2 = "ArrowLeft";
var ARROW_RIGHT2 = "ArrowRight";
var ARROW_UP2 = "ArrowUp";
var ARROW_DOWN2 = "ArrowDown";
function renderJsx(render, computedProps) {
  if (typeof render === "function") {
    return render(computedProps);
  }
  if (render) {
    return React3.cloneElement(render, computedProps);
  }
  return (0, import_jsx_runtime2.jsx)("div", {
    ...computedProps
  });
}
var CompositeContext = React3.createContext({
  activeIndex: 0,
  onNavigate: () => {
  }
});
var horizontalKeys = [ARROW_LEFT2, ARROW_RIGHT2];
var verticalKeys = [ARROW_UP2, ARROW_DOWN2];
var allKeys = [...horizontalKeys, ...verticalKeys];
var Composite = React3.forwardRef(function Composite2(props, forwardedRef) {
  const {
    render,
    orientation = "both",
    loop = true,
    rtl = false,
    cols = 1,
    disabledIndices,
    activeIndex: externalActiveIndex,
    onNavigate: externalSetActiveIndex,
    itemSizes,
    dense = false,
    ...domProps
  } = props;
  const [internalActiveIndex, internalSetActiveIndex] = React3.useState(0);
  const activeIndex = externalActiveIndex != null ? externalActiveIndex : internalActiveIndex;
  const onNavigate = useEffectEvent(externalSetActiveIndex != null ? externalSetActiveIndex : internalSetActiveIndex);
  const elementsRef = React3.useRef([]);
  const renderElementProps = render && typeof render !== "function" ? render.props : {};
  const contextValue = React3.useMemo(() => ({
    activeIndex,
    onNavigate
  }), [activeIndex, onNavigate]);
  const isGrid = cols > 1;
  function handleKeyDown3(event) {
    if (!allKeys.includes(event.key)) return;
    let nextIndex = activeIndex;
    const minIndex = getMinListIndex(elementsRef, disabledIndices);
    const maxIndex = getMaxListIndex(elementsRef, disabledIndices);
    const horizontalEndKey = rtl ? ARROW_LEFT2 : ARROW_RIGHT2;
    const horizontalStartKey = rtl ? ARROW_RIGHT2 : ARROW_LEFT2;
    if (isGrid) {
      const sizes = itemSizes || Array.from({
        length: elementsRef.current.length
      }, () => ({
        width: 1,
        height: 1
      }));
      const cellMap = createGridCellMap(sizes, cols, dense);
      const minGridIndex = cellMap.findIndex((index4) => index4 != null && !isListIndexDisabled(elementsRef, index4, disabledIndices));
      const maxGridIndex = cellMap.reduce((foundIndex, index4, cellIndex) => index4 != null && !isListIndexDisabled(elementsRef, index4, disabledIndices) ? cellIndex : foundIndex, -1);
      const maybeNextIndex = cellMap[getGridNavigatedIndex({
        current: cellMap.map((itemIndex) => itemIndex ? elementsRef.current[itemIndex] : null)
      }, {
        event,
        orientation,
        loop,
        rtl,
        cols,
        // treat undefined (empty grid spaces) as disabled indices so we
        // don't end up in them
        disabledIndices: getGridCellIndices([...(typeof disabledIndices !== "function" ? disabledIndices : null) || elementsRef.current.map((_2, index4) => isListIndexDisabled(elementsRef, index4, disabledIndices) ? index4 : void 0), void 0], cellMap),
        minIndex: minGridIndex,
        maxIndex: maxGridIndex,
        prevIndex: getGridCellIndexOfCorner(
          activeIndex > maxIndex ? minIndex : activeIndex,
          sizes,
          cellMap,
          cols,
          // use a corner matching the edge closest to the direction we're
          // moving in so we don't end up in the same item. Prefer
          // top/left over bottom/right.
          event.key === ARROW_DOWN2 ? "bl" : event.key === horizontalEndKey ? "tr" : "tl"
        )
      })];
      if (maybeNextIndex != null) {
        nextIndex = maybeNextIndex;
      }
    }
    const toEndKeys = {
      horizontal: [horizontalEndKey],
      vertical: [ARROW_DOWN2],
      both: [horizontalEndKey, ARROW_DOWN2]
    }[orientation];
    const toStartKeys = {
      horizontal: [horizontalStartKey],
      vertical: [ARROW_UP2],
      both: [horizontalStartKey, ARROW_UP2]
    }[orientation];
    const preventedKeys = isGrid ? allKeys : {
      horizontal: horizontalKeys,
      vertical: verticalKeys,
      both: allKeys
    }[orientation];
    if (nextIndex === activeIndex && [...toEndKeys, ...toStartKeys].includes(event.key)) {
      if (loop && nextIndex === maxIndex && toEndKeys.includes(event.key)) {
        nextIndex = minIndex;
      } else if (loop && nextIndex === minIndex && toStartKeys.includes(event.key)) {
        nextIndex = maxIndex;
      } else {
        nextIndex = findNonDisabledListIndex(elementsRef, {
          startingIndex: nextIndex,
          decrement: toStartKeys.includes(event.key),
          disabledIndices
        });
      }
    }
    if (nextIndex !== activeIndex && !isIndexOutOfListBounds(elementsRef, nextIndex)) {
      var _elementsRef$current$;
      event.stopPropagation();
      if (preventedKeys.includes(event.key)) {
        event.preventDefault();
      }
      onNavigate(nextIndex);
      (_elementsRef$current$ = elementsRef.current[nextIndex]) == null || _elementsRef$current$.focus();
    }
  }
  const computedProps = {
    ...domProps,
    ...renderElementProps,
    ref: forwardedRef,
    "aria-orientation": orientation === "both" ? void 0 : orientation,
    onKeyDown(e2) {
      domProps.onKeyDown == null || domProps.onKeyDown(e2);
      renderElementProps.onKeyDown == null || renderElementProps.onKeyDown(e2);
      handleKeyDown3(e2);
    }
  };
  return (0, import_jsx_runtime2.jsx)(CompositeContext.Provider, {
    value: contextValue,
    children: (0, import_jsx_runtime2.jsx)(FloatingList, {
      elementsRef,
      children: renderJsx(render, computedProps)
    })
  });
});
var CompositeItem = React3.forwardRef(function CompositeItem2(props, forwardedRef) {
  const {
    render,
    ...domProps
  } = props;
  const renderElementProps = render && typeof render !== "function" ? render.props : {};
  const {
    activeIndex,
    onNavigate
  } = React3.useContext(CompositeContext);
  const {
    ref,
    index: index4
  } = useListItem();
  const mergedRef = useMergeRefs([ref, forwardedRef, renderElementProps.ref]);
  const isActive2 = activeIndex === index4;
  const computedProps = {
    ...domProps,
    ...renderElementProps,
    ref: mergedRef,
    tabIndex: isActive2 ? 0 : -1,
    "data-active": isActive2 ? "" : void 0,
    onFocus(e2) {
      domProps.onFocus == null || domProps.onFocus(e2);
      renderElementProps.onFocus == null || renderElementProps.onFocus(e2);
      onNavigate(index4);
    }
  };
  return renderJsx(render, computedProps);
});
var SafeReact2 = {
  ...React3
};
var serverHandoffComplete = false;
var count = 0;
var genId = () => (
  // Ensure the id is unique with multiple independent versions of Floating UI
  // on <React 18
  "floating-ui-" + Math.random().toString(36).slice(2, 6) + count++
);
function useFloatingId() {
  const [id2, setId] = React3.useState(() => serverHandoffComplete ? genId() : void 0);
  index2(() => {
    if (id2 == null) {
      setId(genId());
    }
  }, []);
  React3.useEffect(() => {
    serverHandoffComplete = true;
  }, []);
  return id2;
}
var useReactId = SafeReact2.useId;
var useId = useReactId || useFloatingId;
var devMessageSet;
if (true) {
  devMessageSet = /* @__PURE__ */ new Set();
}
function warn2() {
  var _devMessageSet;
  for (var _len = arguments.length, messages = new Array(_len), _key = 0; _key < _len; _key++) {
    messages[_key] = arguments[_key];
  }
  const message = "Floating UI: " + messages.join(" ");
  if (!((_devMessageSet = devMessageSet) != null && _devMessageSet.has(message))) {
    var _devMessageSet2;
    (_devMessageSet2 = devMessageSet) == null || _devMessageSet2.add(message);
    console.warn(message);
  }
}
function error() {
  var _devMessageSet3;
  for (var _len2 = arguments.length, messages = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
    messages[_key2] = arguments[_key2];
  }
  const message = "Floating UI: " + messages.join(" ");
  if (!((_devMessageSet3 = devMessageSet) != null && _devMessageSet3.has(message))) {
    var _devMessageSet4;
    (_devMessageSet4 = devMessageSet) == null || _devMessageSet4.add(message);
    console.error(message);
  }
}
var FloatingArrow = React3.forwardRef(function FloatingArrow2(props, ref) {
  const {
    context: {
      placement,
      elements: {
        floating
      },
      middlewareData: {
        arrow: arrow6,
        shift: shift5
      }
    },
    width = 14,
    height = 7,
    tipRadius = 0,
    strokeWidth = 0,
    staticOffset,
    stroke,
    d,
    style: {
      transform: transform2,
      ...restStyle
    } = {},
    ...rest
  } = props;
  if (true) {
    if (!ref) {
      warn2("The `ref` prop is required for `FloatingArrow`.");
    }
  }
  const clipPathId = useId();
  const [isRTL2, setIsRTL] = React3.useState(false);
  index2(() => {
    if (!floating) return;
    const isRTL3 = getComputedStyle2(floating).direction === "rtl";
    if (isRTL3) {
      setIsRTL(true);
    }
  }, [floating]);
  if (!floating) {
    return null;
  }
  const [side, alignment] = placement.split("-");
  const isVerticalSide = side === "top" || side === "bottom";
  let computedStaticOffset = staticOffset;
  if (isVerticalSide && shift5 != null && shift5.x || !isVerticalSide && shift5 != null && shift5.y) {
    computedStaticOffset = null;
  }
  const computedStrokeWidth = strokeWidth * 2;
  const halfStrokeWidth = computedStrokeWidth / 2;
  const svgX = width / 2 * (tipRadius / -8 + 1);
  const svgY = height / 2 * tipRadius / 4;
  const isCustomShape = !!d;
  const yOffsetProp = computedStaticOffset && alignment === "end" ? "bottom" : "top";
  let xOffsetProp = computedStaticOffset && alignment === "end" ? "right" : "left";
  if (computedStaticOffset && isRTL2) {
    xOffsetProp = alignment === "end" ? "left" : "right";
  }
  const arrowX = (arrow6 == null ? void 0 : arrow6.x) != null ? computedStaticOffset || arrow6.x : "";
  const arrowY = (arrow6 == null ? void 0 : arrow6.y) != null ? computedStaticOffset || arrow6.y : "";
  const dValue = d || "M0,0" + (" H" + width) + (" L" + (width - svgX) + "," + (height - svgY)) + (" Q" + width / 2 + "," + height + " " + svgX + "," + (height - svgY)) + " Z";
  const rotation = {
    top: isCustomShape ? "rotate(180deg)" : "",
    left: isCustomShape ? "rotate(90deg)" : "rotate(-90deg)",
    bottom: isCustomShape ? "" : "rotate(180deg)",
    right: isCustomShape ? "rotate(-90deg)" : "rotate(90deg)"
  }[side];
  return (0, import_jsx_runtime2.jsxs)("svg", {
    ...rest,
    "aria-hidden": true,
    ref,
    width: isCustomShape ? width : width + computedStrokeWidth,
    height: width,
    viewBox: "0 0 " + width + " " + (height > width ? height : width),
    style: {
      position: "absolute",
      pointerEvents: "none",
      [xOffsetProp]: arrowX,
      [yOffsetProp]: arrowY,
      [side]: isVerticalSide || isCustomShape ? "100%" : "calc(100% - " + computedStrokeWidth / 2 + "px)",
      transform: [rotation, transform2].filter((t2) => !!t2).join(" "),
      ...restStyle
    },
    children: [computedStrokeWidth > 0 && (0, import_jsx_runtime2.jsx)("path", {
      clipPath: "url(#" + clipPathId + ")",
      fill: "none",
      stroke,
      strokeWidth: computedStrokeWidth + (d ? 0 : 1),
      d: dValue
    }), (0, import_jsx_runtime2.jsx)("path", {
      stroke: computedStrokeWidth && !d ? rest.fill : "none",
      d: dValue
    }), (0, import_jsx_runtime2.jsx)("clipPath", {
      id: clipPathId,
      children: (0, import_jsx_runtime2.jsx)("rect", {
        x: -halfStrokeWidth,
        y: halfStrokeWidth * (isCustomShape ? -1 : 1),
        width: width + computedStrokeWidth,
        height: width
      })
    })]
  });
});
function createEventEmitter() {
  const map7 = /* @__PURE__ */ new Map();
  return {
    emit(event, data) {
      var _map$get;
      (_map$get = map7.get(event)) == null || _map$get.forEach((listener) => listener(data));
    },
    on(event, listener) {
      if (!map7.has(event)) {
        map7.set(event, /* @__PURE__ */ new Set());
      }
      map7.get(event).add(listener);
    },
    off(event, listener) {
      var _map$get2;
      (_map$get2 = map7.get(event)) == null || _map$get2.delete(listener);
    }
  };
}
var FloatingNodeContext = React3.createContext(null);
var FloatingTreeContext = React3.createContext(null);
var useFloatingParentNodeId = () => {
  var _React$useContext;
  return ((_React$useContext = React3.useContext(FloatingNodeContext)) == null ? void 0 : _React$useContext.id) || null;
};
var useFloatingTree = () => React3.useContext(FloatingTreeContext);
function createAttribute(name) {
  return "data-floating-ui-" + name;
}
function clearTimeoutIfSet(timeoutRef) {
  if (timeoutRef.current !== -1) {
    clearTimeout(timeoutRef.current);
    timeoutRef.current = -1;
  }
}
var safePolygonIdentifier = createAttribute("safe-polygon");
function getDelay(value, prop, pointerType) {
  if (pointerType && !isMouseLikePointerType(pointerType)) {
    return 0;
  }
  if (typeof value === "number") {
    return value;
  }
  if (typeof value === "function") {
    const result = value();
    if (typeof result === "number") {
      return result;
    }
    return result == null ? void 0 : result[prop];
  }
  return value == null ? void 0 : value[prop];
}
function getRestMs(value) {
  if (typeof value === "function") {
    return value();
  }
  return value;
}
function useHover(context, props) {
  if (props === void 0) {
    props = {};
  }
  const {
    open,
    onOpenChange,
    dataRef,
    events,
    elements
  } = context;
  const {
    enabled = true,
    delay = 0,
    handleClose = null,
    mouseOnly = false,
    restMs = 0,
    move = true
  } = props;
  const tree = useFloatingTree();
  const parentId = useFloatingParentNodeId();
  const handleCloseRef = useLatestRef(handleClose);
  const delayRef = useLatestRef(delay);
  const openRef = useLatestRef(open);
  const restMsRef = useLatestRef(restMs);
  const pointerTypeRef = React3.useRef();
  const timeoutRef = React3.useRef(-1);
  const handlerRef = React3.useRef();
  const restTimeoutRef = React3.useRef(-1);
  const blockMouseMoveRef = React3.useRef(true);
  const performedPointerEventsMutationRef = React3.useRef(false);
  const unbindMouseMoveRef = React3.useRef(() => {
  });
  const restTimeoutPendingRef = React3.useRef(false);
  const isHoverOpen = useEffectEvent(() => {
    var _dataRef$current$open;
    const type = (_dataRef$current$open = dataRef.current.openEvent) == null ? void 0 : _dataRef$current$open.type;
    return (type == null ? void 0 : type.includes("mouse")) && type !== "mousedown";
  });
  React3.useEffect(() => {
    if (!enabled) return;
    function onOpenChange2(_ref) {
      let {
        open: open2
      } = _ref;
      if (!open2) {
        clearTimeoutIfSet(timeoutRef);
        clearTimeoutIfSet(restTimeoutRef);
        blockMouseMoveRef.current = true;
        restTimeoutPendingRef.current = false;
      }
    }
    events.on("openchange", onOpenChange2);
    return () => {
      events.off("openchange", onOpenChange2);
    };
  }, [enabled, events]);
  React3.useEffect(() => {
    if (!enabled) return;
    if (!handleCloseRef.current) return;
    if (!open) return;
    function onLeave(event) {
      if (isHoverOpen()) {
        onOpenChange(false, event, "hover");
      }
    }
    const html7 = getDocument(elements.floating).documentElement;
    html7.addEventListener("mouseleave", onLeave);
    return () => {
      html7.removeEventListener("mouseleave", onLeave);
    };
  }, [elements.floating, open, onOpenChange, enabled, handleCloseRef, isHoverOpen]);
  const closeWithDelay = React3.useCallback(function(event, runElseBranch, reason) {
    if (runElseBranch === void 0) {
      runElseBranch = true;
    }
    if (reason === void 0) {
      reason = "hover";
    }
    const closeDelay = getDelay(delayRef.current, "close", pointerTypeRef.current);
    if (closeDelay && !handlerRef.current) {
      clearTimeoutIfSet(timeoutRef);
      timeoutRef.current = window.setTimeout(() => onOpenChange(false, event, reason), closeDelay);
    } else if (runElseBranch) {
      clearTimeoutIfSet(timeoutRef);
      onOpenChange(false, event, reason);
    }
  }, [delayRef, onOpenChange]);
  const cleanupMouseMoveHandler = useEffectEvent(() => {
    unbindMouseMoveRef.current();
    handlerRef.current = void 0;
  });
  const clearPointerEvents = useEffectEvent(() => {
    if (performedPointerEventsMutationRef.current) {
      const body3 = getDocument(elements.floating).body;
      body3.style.pointerEvents = "";
      body3.removeAttribute(safePolygonIdentifier);
      performedPointerEventsMutationRef.current = false;
    }
  });
  const isClickLikeOpenEvent = useEffectEvent(() => {
    return dataRef.current.openEvent ? ["click", "mousedown"].includes(dataRef.current.openEvent.type) : false;
  });
  React3.useEffect(() => {
    if (!enabled) return;
    function onReferenceMouseEnter(event) {
      clearTimeoutIfSet(timeoutRef);
      blockMouseMoveRef.current = false;
      if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current) || getRestMs(restMsRef.current) > 0 && !getDelay(delayRef.current, "open")) {
        return;
      }
      const openDelay = getDelay(delayRef.current, "open", pointerTypeRef.current);
      if (openDelay) {
        timeoutRef.current = window.setTimeout(() => {
          if (!openRef.current) {
            onOpenChange(true, event, "hover");
          }
        }, openDelay);
      } else if (!open) {
        onOpenChange(true, event, "hover");
      }
    }
    function onReferenceMouseLeave(event) {
      if (isClickLikeOpenEvent()) {
        clearPointerEvents();
        return;
      }
      unbindMouseMoveRef.current();
      const doc4 = getDocument(elements.floating);
      clearTimeoutIfSet(restTimeoutRef);
      restTimeoutPendingRef.current = false;
      if (handleCloseRef.current && dataRef.current.floatingContext) {
        if (!open) {
          clearTimeoutIfSet(timeoutRef);
        }
        handlerRef.current = handleCloseRef.current({
          ...dataRef.current.floatingContext,
          tree,
          x: event.clientX,
          y: event.clientY,
          onClose() {
            clearPointerEvents();
            cleanupMouseMoveHandler();
            if (!isClickLikeOpenEvent()) {
              closeWithDelay(event, true, "safe-polygon");
            }
          }
        });
        const handler = handlerRef.current;
        doc4.addEventListener("mousemove", handler);
        unbindMouseMoveRef.current = () => {
          doc4.removeEventListener("mousemove", handler);
        };
        return;
      }
      const shouldClose = pointerTypeRef.current === "touch" ? !contains(elements.floating, event.relatedTarget) : true;
      if (shouldClose) {
        closeWithDelay(event);
      }
    }
    function onScrollMouseLeave(event) {
      if (isClickLikeOpenEvent()) return;
      if (!dataRef.current.floatingContext) return;
      handleCloseRef.current == null || handleCloseRef.current({
        ...dataRef.current.floatingContext,
        tree,
        x: event.clientX,
        y: event.clientY,
        onClose() {
          clearPointerEvents();
          cleanupMouseMoveHandler();
          if (!isClickLikeOpenEvent()) {
            closeWithDelay(event);
          }
        }
      })(event);
    }
    function onFloatingMouseEnter() {
      clearTimeoutIfSet(timeoutRef);
    }
    function onFloatingMouseLeave(event) {
      if (!isClickLikeOpenEvent()) {
        closeWithDelay(event, false);
      }
    }
    if (isElement2(elements.domReference)) {
      const reference2 = elements.domReference;
      const floating = elements.floating;
      if (open) {
        reference2.addEventListener("mouseleave", onScrollMouseLeave);
      }
      if (move) {
        reference2.addEventListener("mousemove", onReferenceMouseEnter, {
          once: true
        });
      }
      reference2.addEventListener("mouseenter", onReferenceMouseEnter);
      reference2.addEventListener("mouseleave", onReferenceMouseLeave);
      if (floating) {
        floating.addEventListener("mouseleave", onScrollMouseLeave);
        floating.addEventListener("mouseenter", onFloatingMouseEnter);
        floating.addEventListener("mouseleave", onFloatingMouseLeave);
      }
      return () => {
        if (open) {
          reference2.removeEventListener("mouseleave", onScrollMouseLeave);
        }
        if (move) {
          reference2.removeEventListener("mousemove", onReferenceMouseEnter);
        }
        reference2.removeEventListener("mouseenter", onReferenceMouseEnter);
        reference2.removeEventListener("mouseleave", onReferenceMouseLeave);
        if (floating) {
          floating.removeEventListener("mouseleave", onScrollMouseLeave);
          floating.removeEventListener("mouseenter", onFloatingMouseEnter);
          floating.removeEventListener("mouseleave", onFloatingMouseLeave);
        }
      };
    }
  }, [elements, enabled, context, mouseOnly, move, closeWithDelay, cleanupMouseMoveHandler, clearPointerEvents, onOpenChange, open, openRef, tree, delayRef, handleCloseRef, dataRef, isClickLikeOpenEvent, restMsRef]);
  index2(() => {
    var _handleCloseRef$curre;
    if (!enabled) return;
    if (open && (_handleCloseRef$curre = handleCloseRef.current) != null && (_handleCloseRef$curre = _handleCloseRef$curre.__options) != null && _handleCloseRef$curre.blockPointerEvents && isHoverOpen()) {
      performedPointerEventsMutationRef.current = true;
      const floatingEl = elements.floating;
      if (isElement2(elements.domReference) && floatingEl) {
        var _tree$nodesRef$curren;
        const body3 = getDocument(elements.floating).body;
        body3.setAttribute(safePolygonIdentifier, "");
        const ref = elements.domReference;
        const parentFloating = tree == null || (_tree$nodesRef$curren = tree.nodesRef.current.find((node2) => node2.id === parentId)) == null || (_tree$nodesRef$curren = _tree$nodesRef$curren.context) == null ? void 0 : _tree$nodesRef$curren.elements.floating;
        if (parentFloating) {
          parentFloating.style.pointerEvents = "";
        }
        body3.style.pointerEvents = "none";
        ref.style.pointerEvents = "auto";
        floatingEl.style.pointerEvents = "auto";
        return () => {
          body3.style.pointerEvents = "";
          ref.style.pointerEvents = "";
          floatingEl.style.pointerEvents = "";
        };
      }
    }
  }, [enabled, open, parentId, elements, tree, handleCloseRef, isHoverOpen]);
  index2(() => {
    if (!open) {
      pointerTypeRef.current = void 0;
      restTimeoutPendingRef.current = false;
      cleanupMouseMoveHandler();
      clearPointerEvents();
    }
  }, [open, cleanupMouseMoveHandler, clearPointerEvents]);
  React3.useEffect(() => {
    return () => {
      cleanupMouseMoveHandler();
      clearTimeoutIfSet(timeoutRef);
      clearTimeoutIfSet(restTimeoutRef);
      clearPointerEvents();
    };
  }, [enabled, elements.domReference, cleanupMouseMoveHandler, clearPointerEvents]);
  const reference = React3.useMemo(() => {
    function setPointerRef(event) {
      pointerTypeRef.current = event.pointerType;
    }
    return {
      onPointerDown: setPointerRef,
      onPointerEnter: setPointerRef,
      onMouseMove(event) {
        const {
          nativeEvent
        } = event;
        function handleMouseMove2() {
          if (!blockMouseMoveRef.current && !openRef.current) {
            onOpenChange(true, nativeEvent, "hover");
          }
        }
        if (mouseOnly && !isMouseLikePointerType(pointerTypeRef.current)) {
          return;
        }
        if (open || getRestMs(restMsRef.current) === 0) {
          return;
        }
        if (restTimeoutPendingRef.current && event.movementX ** 2 + event.movementY ** 2 < 2) {
          return;
        }
        clearTimeoutIfSet(restTimeoutRef);
        if (pointerTypeRef.current === "touch") {
          handleMouseMove2();
        } else {
          restTimeoutPendingRef.current = true;
          restTimeoutRef.current = window.setTimeout(handleMouseMove2, getRestMs(restMsRef.current));
        }
      }
    };
  }, [mouseOnly, onOpenChange, open, openRef, restMsRef]);
  return React3.useMemo(() => enabled ? {
    reference
  } : {}, [enabled, reference]);
}
var NOOP = () => {
};
var FloatingDelayGroupContext = React3.createContext({
  delay: 0,
  initialDelay: 0,
  timeoutMs: 0,
  currentId: null,
  setCurrentId: NOOP,
  setState: NOOP,
  isInstantPhase: false
});
var NextFloatingDelayGroupContext = React3.createContext({
  hasProvider: false,
  timeoutMs: 0,
  delayRef: {
    current: 0
  },
  initialDelayRef: {
    current: 0
  },
  timeoutIdRef: {
    current: -1
  },
  currentIdRef: {
    current: null
  },
  currentContextRef: {
    current: null
  }
});
function contains2(parent, child) {
  if (!parent || !child) {
    return false;
  }
  const rootNode = child.getRootNode == null ? void 0 : child.getRootNode();
  if (parent.contains(child)) {
    return true;
  }
  if (rootNode && isShadowRoot(rootNode)) {
    let next2 = child;
    while (next2) {
      if (parent === next2) {
        return true;
      }
      next2 = next2.parentNode || next2.host;
    }
  }
  return false;
}
function getTarget2(event) {
  if ("composedPath" in event) {
    return event.composedPath()[0];
  }
  return event.target;
}
var HIDDEN_STYLES = {
  border: 0,
  clip: "rect(0 0 0 0)",
  height: "1px",
  margin: "-1px",
  overflow: "hidden",
  padding: 0,
  position: "fixed",
  whiteSpace: "nowrap",
  width: "1px",
  top: 0,
  left: 0
};
var FocusGuard = React3.forwardRef(function FocusGuard2(props, ref) {
  const [role, setRole] = React3.useState();
  index2(() => {
    if (isSafari()) {
      setRole("button");
    }
  }, []);
  const restProps = {
    ref,
    tabIndex: 0,
    // Role is only for VoiceOver
    role,
    "aria-hidden": role ? void 0 : true,
    [createAttribute("focus-guard")]: "",
    style: HIDDEN_STYLES
  };
  return (0, import_jsx_runtime2.jsx)("span", {
    ...props,
    ...restProps
  });
});
var PortalContext = React3.createContext(null);
var attr = createAttribute("portal");
var VisuallyHiddenDismiss = React3.forwardRef(function VisuallyHiddenDismiss2(props, ref) {
  return (0, import_jsx_runtime2.jsx)("button", {
    ...props,
    type: "button",
    ref,
    tabIndex: -1,
    style: HIDDEN_STYLES
  });
});
var lockCount = 0;
var scrollbarProperty = "--floating-ui-scrollbar-width";
function enableScrollLock() {
  const platform2 = getPlatform();
  const isIOS = /iP(hone|ad|od)|iOS/.test(platform2) || // iPads can claim to be MacIntel
  platform2 === "MacIntel" && navigator.maxTouchPoints > 1;
  const bodyStyle = document.body.style;
  const scrollbarX = Math.round(document.documentElement.getBoundingClientRect().left) + document.documentElement.scrollLeft;
  const paddingProp = scrollbarX ? "paddingLeft" : "paddingRight";
  const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
  const scrollX = bodyStyle.left ? parseFloat(bodyStyle.left) : window.scrollX;
  const scrollY = bodyStyle.top ? parseFloat(bodyStyle.top) : window.scrollY;
  bodyStyle.overflow = "hidden";
  bodyStyle.setProperty(scrollbarProperty, scrollbarWidth + "px");
  if (scrollbarWidth) {
    bodyStyle[paddingProp] = scrollbarWidth + "px";
  }
  if (isIOS) {
    var _window$visualViewpor, _window$visualViewpor2;
    const offsetLeft = ((_window$visualViewpor = window.visualViewport) == null ? void 0 : _window$visualViewpor.offsetLeft) || 0;
    const offsetTop = ((_window$visualViewpor2 = window.visualViewport) == null ? void 0 : _window$visualViewpor2.offsetTop) || 0;
    Object.assign(bodyStyle, {
      position: "fixed",
      top: -(scrollY - Math.floor(offsetTop)) + "px",
      left: -(scrollX - Math.floor(offsetLeft)) + "px",
      right: "0"
    });
  }
  return () => {
    Object.assign(bodyStyle, {
      overflow: "",
      [paddingProp]: ""
    });
    bodyStyle.removeProperty(scrollbarProperty);
    if (isIOS) {
      Object.assign(bodyStyle, {
        position: "",
        top: "",
        left: "",
        right: ""
      });
      window.scrollTo(scrollX, scrollY);
    }
  };
}
var cleanup = () => {
};
var FloatingOverlay = React3.forwardRef(function FloatingOverlay2(props, ref) {
  const {
    lockScroll = false,
    ...rest
  } = props;
  index2(() => {
    if (!lockScroll) return;
    lockCount++;
    if (lockCount === 1) {
      cleanup = enableScrollLock();
    }
    return () => {
      lockCount--;
      if (lockCount === 0) {
        cleanup();
      }
    };
  }, [lockScroll]);
  return (0, import_jsx_runtime2.jsx)("div", {
    ref,
    ...rest,
    style: {
      position: "fixed",
      overflow: "auto",
      top: 0,
      right: 0,
      bottom: 0,
      left: 0,
      ...rest.style
    }
  });
});
var bubbleHandlerKeys = {
  pointerdown: "onPointerDown",
  mousedown: "onMouseDown",
  click: "onClick"
};
var captureHandlerKeys = {
  pointerdown: "onPointerDownCapture",
  mousedown: "onMouseDownCapture",
  click: "onClickCapture"
};
var normalizeProp = (normalizable) => {
  var _normalizable$escapeK, _normalizable$outside;
  return {
    escapeKey: typeof normalizable === "boolean" ? normalizable : (_normalizable$escapeK = normalizable == null ? void 0 : normalizable.escapeKey) != null ? _normalizable$escapeK : false,
    outsidePress: typeof normalizable === "boolean" ? normalizable : (_normalizable$outside = normalizable == null ? void 0 : normalizable.outsidePress) != null ? _normalizable$outside : true
  };
};
function useDismiss(context, props) {
  if (props === void 0) {
    props = {};
  }
  const {
    open,
    onOpenChange,
    elements,
    dataRef
  } = context;
  const {
    enabled = true,
    escapeKey = true,
    outsidePress: unstable_outsidePress = true,
    outsidePressEvent = "pointerdown",
    referencePress = false,
    referencePressEvent = "pointerdown",
    ancestorScroll = false,
    bubbles,
    capture
  } = props;
  const tree = useFloatingTree();
  const outsidePressFn = useEffectEvent(typeof unstable_outsidePress === "function" ? unstable_outsidePress : () => false);
  const outsidePress = typeof unstable_outsidePress === "function" ? outsidePressFn : unstable_outsidePress;
  const endedOrStartedInsideRef = React3.useRef(false);
  const {
    escapeKey: escapeKeyBubbles,
    outsidePress: outsidePressBubbles
  } = normalizeProp(bubbles);
  const {
    escapeKey: escapeKeyCapture,
    outsidePress: outsidePressCapture
  } = normalizeProp(capture);
  const isComposingRef = React3.useRef(false);
  const closeOnEscapeKeyDown = useEffectEvent((event) => {
    var _dataRef$current$floa;
    if (!open || !enabled || !escapeKey || event.key !== "Escape") {
      return;
    }
    if (isComposingRef.current) {
      return;
    }
    const nodeId = (_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.nodeId;
    const children = tree ? getNodeChildren(tree.nodesRef.current, nodeId) : [];
    if (!escapeKeyBubbles) {
      event.stopPropagation();
      if (children.length > 0) {
        let shouldDismiss = true;
        children.forEach((child) => {
          var _child$context;
          if ((_child$context = child.context) != null && _child$context.open && !child.context.dataRef.current.__escapeKeyBubbles) {
            shouldDismiss = false;
            return;
          }
        });
        if (!shouldDismiss) {
          return;
        }
      }
    }
    onOpenChange(false, isReactEvent(event) ? event.nativeEvent : event, "escape-key");
  });
  const closeOnEscapeKeyDownCapture = useEffectEvent((event) => {
    var _getTarget2;
    const callback = () => {
      var _getTarget;
      closeOnEscapeKeyDown(event);
      (_getTarget = getTarget(event)) == null || _getTarget.removeEventListener("keydown", callback);
    };
    (_getTarget2 = getTarget(event)) == null || _getTarget2.addEventListener("keydown", callback);
  });
  const closeOnPressOutside = useEffectEvent((event) => {
    var _dataRef$current$floa2;
    const insideReactTree = dataRef.current.insideReactTree;
    dataRef.current.insideReactTree = false;
    const endedOrStartedInside = endedOrStartedInsideRef.current;
    endedOrStartedInsideRef.current = false;
    if (outsidePressEvent === "click" && endedOrStartedInside) {
      return;
    }
    if (insideReactTree) {
      return;
    }
    if (typeof outsidePress === "function" && !outsidePress(event)) {
      return;
    }
    const target = getTarget(event);
    const inertSelector = "[" + createAttribute("inert") + "]";
    const markers = getDocument(elements.floating).querySelectorAll(inertSelector);
    let targetRootAncestor = isElement2(target) ? target : null;
    while (targetRootAncestor && !isLastTraversableNode(targetRootAncestor)) {
      const nextParent = getParentNode(targetRootAncestor);
      if (isLastTraversableNode(nextParent) || !isElement2(nextParent)) {
        break;
      }
      targetRootAncestor = nextParent;
    }
    if (markers.length && isElement2(target) && !isRootElement(target) && // Clicked on a direct ancestor (e.g. FloatingOverlay).
    !contains(target, elements.floating) && // If the target root element contains none of the markers, then the
    // element was injected after the floating element rendered.
    Array.from(markers).every((marker) => !contains(targetRootAncestor, marker))) {
      return;
    }
    if (isHTMLElement(target) && floating) {
      const lastTraversableNode = isLastTraversableNode(target);
      const style3 = getComputedStyle2(target);
      const scrollRe = /auto|scroll/;
      const isScrollableX = lastTraversableNode || scrollRe.test(style3.overflowX);
      const isScrollableY = lastTraversableNode || scrollRe.test(style3.overflowY);
      const canScrollX = isScrollableX && target.clientWidth > 0 && target.scrollWidth > target.clientWidth;
      const canScrollY = isScrollableY && target.clientHeight > 0 && target.scrollHeight > target.clientHeight;
      const isRTL2 = style3.direction === "rtl";
      const pressedVerticalScrollbar = canScrollY && (isRTL2 ? event.offsetX <= target.offsetWidth - target.clientWidth : event.offsetX > target.clientWidth);
      const pressedHorizontalScrollbar = canScrollX && event.offsetY > target.clientHeight;
      if (pressedVerticalScrollbar || pressedHorizontalScrollbar) {
        return;
      }
    }
    const nodeId = (_dataRef$current$floa2 = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa2.nodeId;
    const targetIsInsideChildren = tree && getNodeChildren(tree.nodesRef.current, nodeId).some((node2) => {
      var _node$context;
      return isEventTargetWithin(event, (_node$context = node2.context) == null ? void 0 : _node$context.elements.floating);
    });
    if (isEventTargetWithin(event, elements.floating) || isEventTargetWithin(event, elements.domReference) || targetIsInsideChildren) {
      return;
    }
    const children = tree ? getNodeChildren(tree.nodesRef.current, nodeId) : [];
    if (children.length > 0) {
      let shouldDismiss = true;
      children.forEach((child) => {
        var _child$context2;
        if ((_child$context2 = child.context) != null && _child$context2.open && !child.context.dataRef.current.__outsidePressBubbles) {
          shouldDismiss = false;
          return;
        }
      });
      if (!shouldDismiss) {
        return;
      }
    }
    onOpenChange(false, event, "outside-press");
  });
  const closeOnPressOutsideCapture = useEffectEvent((event) => {
    var _getTarget4;
    const callback = () => {
      var _getTarget3;
      closeOnPressOutside(event);
      (_getTarget3 = getTarget(event)) == null || _getTarget3.removeEventListener(outsidePressEvent, callback);
    };
    (_getTarget4 = getTarget(event)) == null || _getTarget4.addEventListener(outsidePressEvent, callback);
  });
  React3.useEffect(() => {
    if (!open || !enabled) {
      return;
    }
    dataRef.current.__escapeKeyBubbles = escapeKeyBubbles;
    dataRef.current.__outsidePressBubbles = outsidePressBubbles;
    let compositionTimeout = -1;
    function onScroll(event) {
      onOpenChange(false, event, "ancestor-scroll");
    }
    function handleCompositionStart() {
      window.clearTimeout(compositionTimeout);
      isComposingRef.current = true;
    }
    function handleCompositionEnd() {
      compositionTimeout = window.setTimeout(
        () => {
          isComposingRef.current = false;
        },
        // 0ms or 1ms don't work in Safari. 5ms appears to consistently work.
        // Only apply to WebKit for the test to remain 0ms.
        isWebKit() ? 5 : 0
      );
    }
    const doc4 = getDocument(elements.floating);
    if (escapeKey) {
      doc4.addEventListener("keydown", escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
      doc4.addEventListener("compositionstart", handleCompositionStart);
      doc4.addEventListener("compositionend", handleCompositionEnd);
    }
    outsidePress && doc4.addEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
    let ancestors = [];
    if (ancestorScroll) {
      if (isElement2(elements.domReference)) {
        ancestors = getOverflowAncestors(elements.domReference);
      }
      if (isElement2(elements.floating)) {
        ancestors = ancestors.concat(getOverflowAncestors(elements.floating));
      }
      if (!isElement2(elements.reference) && elements.reference && elements.reference.contextElement) {
        ancestors = ancestors.concat(getOverflowAncestors(elements.reference.contextElement));
      }
    }
    ancestors = ancestors.filter((ancestor) => {
      var _doc$defaultView;
      return ancestor !== ((_doc$defaultView = doc4.defaultView) == null ? void 0 : _doc$defaultView.visualViewport);
    });
    ancestors.forEach((ancestor) => {
      ancestor.addEventListener("scroll", onScroll, {
        passive: true
      });
    });
    return () => {
      if (escapeKey) {
        doc4.removeEventListener("keydown", escapeKeyCapture ? closeOnEscapeKeyDownCapture : closeOnEscapeKeyDown, escapeKeyCapture);
        doc4.removeEventListener("compositionstart", handleCompositionStart);
        doc4.removeEventListener("compositionend", handleCompositionEnd);
      }
      outsidePress && doc4.removeEventListener(outsidePressEvent, outsidePressCapture ? closeOnPressOutsideCapture : closeOnPressOutside, outsidePressCapture);
      ancestors.forEach((ancestor) => {
        ancestor.removeEventListener("scroll", onScroll);
      });
      window.clearTimeout(compositionTimeout);
    };
  }, [dataRef, elements, escapeKey, outsidePress, outsidePressEvent, open, onOpenChange, ancestorScroll, enabled, escapeKeyBubbles, outsidePressBubbles, closeOnEscapeKeyDown, escapeKeyCapture, closeOnEscapeKeyDownCapture, closeOnPressOutside, outsidePressCapture, closeOnPressOutsideCapture]);
  React3.useEffect(() => {
    dataRef.current.insideReactTree = false;
  }, [dataRef, outsidePress, outsidePressEvent]);
  const reference = React3.useMemo(() => ({
    onKeyDown: closeOnEscapeKeyDown,
    ...referencePress && {
      [bubbleHandlerKeys[referencePressEvent]]: (event) => {
        onOpenChange(false, event.nativeEvent, "reference-press");
      },
      ...referencePressEvent !== "click" && {
        onClick(event) {
          onOpenChange(false, event.nativeEvent, "reference-press");
        }
      }
    }
  }), [closeOnEscapeKeyDown, onOpenChange, referencePress, referencePressEvent]);
  const floating = React3.useMemo(() => ({
    onKeyDown: closeOnEscapeKeyDown,
    onMouseDown() {
      endedOrStartedInsideRef.current = true;
    },
    onMouseUp() {
      endedOrStartedInsideRef.current = true;
    },
    [captureHandlerKeys[outsidePressEvent]]: () => {
      dataRef.current.insideReactTree = true;
    }
  }), [closeOnEscapeKeyDown, outsidePressEvent, dataRef]);
  return React3.useMemo(() => enabled ? {
    reference,
    floating
  } : {}, [enabled, reference, floating]);
}
function useFloatingRootContext(options2) {
  const {
    open = false,
    onOpenChange: onOpenChangeProp,
    elements: elementsProp
  } = options2;
  const floatingId = useId();
  const dataRef = React3.useRef({});
  const [events] = React3.useState(() => createEventEmitter());
  const nested = useFloatingParentNodeId() != null;
  if (true) {
    const optionDomReference = elementsProp.reference;
    if (optionDomReference && !isElement2(optionDomReference)) {
      error("Cannot pass a virtual element to the `elements.reference` option,", "as it must be a real DOM element. Use `refs.setPositionReference()`", "instead.");
    }
  }
  const [positionReference, setPositionReference] = React3.useState(elementsProp.reference);
  const onOpenChange = useEffectEvent((open2, event, reason) => {
    dataRef.current.openEvent = open2 ? event : void 0;
    events.emit("openchange", {
      open: open2,
      event,
      reason,
      nested
    });
    onOpenChangeProp == null || onOpenChangeProp(open2, event, reason);
  });
  const refs = React3.useMemo(() => ({
    setPositionReference
  }), []);
  const elements = React3.useMemo(() => ({
    reference: positionReference || elementsProp.reference || null,
    floating: elementsProp.floating || null,
    domReference: elementsProp.reference
  }), [positionReference, elementsProp.reference, elementsProp.floating]);
  return React3.useMemo(() => ({
    dataRef,
    open,
    onOpenChange,
    elements,
    events,
    floatingId,
    refs
  }), [open, onOpenChange, elements, events, floatingId, refs]);
}
function useFloating2(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  const {
    nodeId
  } = options2;
  const internalRootContext = useFloatingRootContext({
    ...options2,
    elements: {
      reference: null,
      floating: null,
      ...options2.elements
    }
  });
  const rootContext = options2.rootContext || internalRootContext;
  const computedElements = rootContext.elements;
  const [_domReference, setDomReference] = React3.useState(null);
  const [positionReference, _setPositionReference] = React3.useState(null);
  const optionDomReference = computedElements == null ? void 0 : computedElements.domReference;
  const domReference = optionDomReference || _domReference;
  const domReferenceRef = React3.useRef(null);
  const tree = useFloatingTree();
  index2(() => {
    if (domReference) {
      domReferenceRef.current = domReference;
    }
  }, [domReference]);
  const position4 = useFloating({
    ...options2,
    elements: {
      ...computedElements,
      ...positionReference && {
        reference: positionReference
      }
    }
  });
  const setPositionReference = React3.useCallback((node2) => {
    const computedPositionReference = isElement2(node2) ? {
      getBoundingClientRect: () => node2.getBoundingClientRect(),
      getClientRects: () => node2.getClientRects(),
      contextElement: node2
    } : node2;
    _setPositionReference(computedPositionReference);
    position4.refs.setReference(computedPositionReference);
  }, [position4.refs]);
  const setReference = React3.useCallback((node2) => {
    if (isElement2(node2) || node2 === null) {
      domReferenceRef.current = node2;
      setDomReference(node2);
    }
    if (isElement2(position4.refs.reference.current) || position4.refs.reference.current === null || // Don't allow setting virtual elements using the old technique back to
    // `null` to support `positionReference` + an unstable `reference`
    // callback ref.
    node2 !== null && !isElement2(node2)) {
      position4.refs.setReference(node2);
    }
  }, [position4.refs]);
  const refs = React3.useMemo(() => ({
    ...position4.refs,
    setReference,
    setPositionReference,
    domReference: domReferenceRef
  }), [position4.refs, setReference, setPositionReference]);
  const elements = React3.useMemo(() => ({
    ...position4.elements,
    domReference
  }), [position4.elements, domReference]);
  const context = React3.useMemo(() => ({
    ...position4,
    ...rootContext,
    refs,
    elements,
    nodeId
  }), [position4, refs, elements, nodeId, rootContext]);
  index2(() => {
    rootContext.dataRef.current.floatingContext = context;
    const node2 = tree == null ? void 0 : tree.nodesRef.current.find((node3) => node3.id === nodeId);
    if (node2) {
      node2.context = context;
    }
  });
  return React3.useMemo(() => ({
    ...position4,
    context,
    refs,
    elements
  }), [position4, refs, elements, context]);
}
function mergeProps(userProps, propsList, elementKey) {
  const map7 = /* @__PURE__ */ new Map();
  const isItem = elementKey === "item";
  let domUserProps = userProps;
  if (isItem && userProps) {
    const {
      [ACTIVE_KEY]: _2,
      [SELECTED_KEY]: __,
      ...validProps
    } = userProps;
    domUserProps = validProps;
  }
  return {
    ...elementKey === "floating" && {
      tabIndex: -1,
      [FOCUSABLE_ATTRIBUTE]: ""
    },
    ...domUserProps,
    ...propsList.map((value) => {
      const propsOrGetProps = value ? value[elementKey] : null;
      if (typeof propsOrGetProps === "function") {
        return userProps ? propsOrGetProps(userProps) : null;
      }
      return propsOrGetProps;
    }).concat(userProps).reduce((acc, props) => {
      if (!props) {
        return acc;
      }
      Object.entries(props).forEach((_ref) => {
        let [key2, value] = _ref;
        if (isItem && [ACTIVE_KEY, SELECTED_KEY].includes(key2)) {
          return;
        }
        if (key2.indexOf("on") === 0) {
          if (!map7.has(key2)) {
            map7.set(key2, []);
          }
          if (typeof value === "function") {
            var _map$get;
            (_map$get = map7.get(key2)) == null || _map$get.push(value);
            acc[key2] = function() {
              var _map$get2;
              for (var _len = arguments.length, args2 = new Array(_len), _key = 0; _key < _len; _key++) {
                args2[_key] = arguments[_key];
              }
              return (_map$get2 = map7.get(key2)) == null ? void 0 : _map$get2.map((fn4) => fn4(...args2)).find((val) => val !== void 0);
            };
          }
        } else {
          acc[key2] = value;
        }
      });
      return acc;
    }, {})
  };
}
function useInteractions(propsList) {
  if (propsList === void 0) {
    propsList = [];
  }
  const referenceDeps = propsList.map((key2) => key2 == null ? void 0 : key2.reference);
  const floatingDeps = propsList.map((key2) => key2 == null ? void 0 : key2.floating);
  const itemDeps = propsList.map((key2) => key2 == null ? void 0 : key2.item);
  const getReferenceProps = React3.useCallback(
    (userProps) => mergeProps(userProps, propsList, "reference"),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    referenceDeps
  );
  const getFloatingProps = React3.useCallback(
    (userProps) => mergeProps(userProps, propsList, "floating"),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    floatingDeps
  );
  const getItemProps = React3.useCallback(
    (userProps) => mergeProps(userProps, propsList, "item"),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    itemDeps
  );
  return React3.useMemo(() => ({
    getReferenceProps,
    getFloatingProps,
    getItemProps
  }), [getReferenceProps, getFloatingProps, getItemProps]);
}
var camelCaseToKebabCase = (str) => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($6, ofs) => (ofs ? "-" : "") + $6.toLowerCase());
function execWithArgsOrReturn(valueOrFn, args2) {
  return typeof valueOrFn === "function" ? valueOrFn(args2) : valueOrFn;
}
function useDelayUnmount(open, durationMs) {
  const [isMounted, setIsMounted] = React3.useState(open);
  if (open && !isMounted) {
    setIsMounted(true);
  }
  React3.useEffect(() => {
    if (!open && isMounted) {
      const timeout2 = setTimeout(() => setIsMounted(false), durationMs);
      return () => clearTimeout(timeout2);
    }
  }, [open, isMounted, durationMs]);
  return isMounted;
}
function useTransitionStatus(context, props) {
  if (props === void 0) {
    props = {};
  }
  const {
    open,
    elements: {
      floating
    }
  } = context;
  const {
    duration = 250
  } = props;
  const isNumberDuration = typeof duration === "number";
  const closeDuration = (isNumberDuration ? duration : duration.close) || 0;
  const [status, setStatus] = React3.useState("unmounted");
  const isMounted = useDelayUnmount(open, closeDuration);
  if (!isMounted && status === "close") {
    setStatus("unmounted");
  }
  index2(() => {
    if (!floating) return;
    if (open) {
      setStatus("initial");
      const frame = requestAnimationFrame(() => {
        ReactDOM2.flushSync(() => {
          setStatus("open");
        });
      });
      return () => {
        cancelAnimationFrame(frame);
      };
    }
    setStatus("close");
  }, [open, floating]);
  return {
    isMounted,
    status
  };
}
function useTransitionStyles(context, props) {
  if (props === void 0) {
    props = {};
  }
  const {
    initial: unstable_initial = {
      opacity: 0
    },
    open: unstable_open,
    close: unstable_close,
    common: unstable_common,
    duration = 250
  } = props;
  const placement = context.placement;
  const side = placement.split("-")[0];
  const fnArgs = React3.useMemo(() => ({
    side,
    placement
  }), [side, placement]);
  const isNumberDuration = typeof duration === "number";
  const openDuration = (isNumberDuration ? duration : duration.open) || 0;
  const closeDuration = (isNumberDuration ? duration : duration.close) || 0;
  const [styles, setStyles] = React3.useState(() => ({
    ...execWithArgsOrReturn(unstable_common, fnArgs),
    ...execWithArgsOrReturn(unstable_initial, fnArgs)
  }));
  const {
    isMounted,
    status
  } = useTransitionStatus(context, {
    duration
  });
  const initialRef = useLatestRef(unstable_initial);
  const openRef = useLatestRef(unstable_open);
  const closeRef = useLatestRef(unstable_close);
  const commonRef = useLatestRef(unstable_common);
  index2(() => {
    const initialStyles = execWithArgsOrReturn(initialRef.current, fnArgs);
    const closeStyles = execWithArgsOrReturn(closeRef.current, fnArgs);
    const commonStyles = execWithArgsOrReturn(commonRef.current, fnArgs);
    const openStyles = execWithArgsOrReturn(openRef.current, fnArgs) || Object.keys(initialStyles).reduce((acc, key2) => {
      acc[key2] = "";
      return acc;
    }, {});
    if (status === "initial") {
      setStyles((styles2) => ({
        transitionProperty: styles2.transitionProperty,
        ...commonStyles,
        ...initialStyles
      }));
    }
    if (status === "open") {
      setStyles({
        transitionProperty: Object.keys(openStyles).map(camelCaseToKebabCase).join(","),
        transitionDuration: openDuration + "ms",
        ...commonStyles,
        ...openStyles
      });
    }
    if (status === "close") {
      const styles2 = closeStyles || initialStyles;
      setStyles({
        transitionProperty: Object.keys(styles2).map(camelCaseToKebabCase).join(","),
        transitionDuration: closeDuration + "ms",
        ...commonStyles,
        ...styles2
      });
    }
  }, [closeDuration, closeRef, initialRef, openRef, commonRef, openDuration, status, fnArgs]);
  return {
    isMounted,
    styles
  };
}
function getNodeChildren2(nodes, id2, onlyOpenChildren) {
  if (onlyOpenChildren === void 0) {
    onlyOpenChildren = true;
  }
  const directChildren = nodes.filter((node2) => {
    var _node$context;
    return node2.parentId === id2 && (!onlyOpenChildren || ((_node$context = node2.context) == null ? void 0 : _node$context.open));
  });
  return directChildren.flatMap((child) => [child, ...getNodeChildren2(nodes, child.id, onlyOpenChildren)]);
}
function isPointInPolygon(point5, polygon) {
  const [x5, y3] = point5;
  let isInside2 = false;
  const length2 = polygon.length;
  for (let i3 = 0, j4 = length2 - 1; i3 < length2; j4 = i3++) {
    const [xi2, yi2] = polygon[i3] || [0, 0];
    const [xj, yj] = polygon[j4] || [0, 0];
    const intersect = yi2 >= y3 !== yj >= y3 && x5 <= (xj - xi2) * (y3 - yi2) / (yj - yi2) + xi2;
    if (intersect) {
      isInside2 = !isInside2;
    }
  }
  return isInside2;
}
function isInside(point5, rect) {
  return point5[0] >= rect.x && point5[0] <= rect.x + rect.width && point5[1] >= rect.y && point5[1] <= rect.y + rect.height;
}
function safePolygon(options2) {
  if (options2 === void 0) {
    options2 = {};
  }
  const {
    buffer = 0.5,
    blockPointerEvents = false,
    requireIntent = true
  } = options2;
  const timeoutRef = {
    current: -1
  };
  let hasLanded = false;
  let lastX = null;
  let lastY = null;
  let lastCursorTime = typeof performance !== "undefined" ? performance.now() : 0;
  function getCursorSpeed(x5, y3) {
    const currentTime = performance.now();
    const elapsedTime = currentTime - lastCursorTime;
    if (lastX === null || lastY === null || elapsedTime === 0) {
      lastX = x5;
      lastY = y3;
      lastCursorTime = currentTime;
      return null;
    }
    const deltaX = x5 - lastX;
    const deltaY = y3 - lastY;
    const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
    const speed = distance / elapsedTime;
    lastX = x5;
    lastY = y3;
    lastCursorTime = currentTime;
    return speed;
  }
  const fn4 = (_ref) => {
    let {
      x: x5,
      y: y3,
      placement,
      elements,
      onClose,
      nodeId,
      tree
    } = _ref;
    return function onMouseMove(event) {
      function close2() {
        clearTimeoutIfSet(timeoutRef);
        onClose();
      }
      clearTimeoutIfSet(timeoutRef);
      if (!elements.domReference || !elements.floating || placement == null || x5 == null || y3 == null) {
        return;
      }
      const {
        clientX,
        clientY
      } = event;
      const clientPoint = [clientX, clientY];
      const target = getTarget2(event);
      const isLeave = event.type === "mouseleave";
      const isOverFloatingEl = contains2(elements.floating, target);
      const isOverReferenceEl = contains2(elements.domReference, target);
      const refRect = elements.domReference.getBoundingClientRect();
      const rect = elements.floating.getBoundingClientRect();
      const side = placement.split("-")[0];
      const cursorLeaveFromRight = x5 > rect.right - rect.width / 2;
      const cursorLeaveFromBottom = y3 > rect.bottom - rect.height / 2;
      const isOverReferenceRect = isInside(clientPoint, refRect);
      const isFloatingWider = rect.width > refRect.width;
      const isFloatingTaller = rect.height > refRect.height;
      const left = (isFloatingWider ? refRect : rect).left;
      const right = (isFloatingWider ? refRect : rect).right;
      const top = (isFloatingTaller ? refRect : rect).top;
      const bottom = (isFloatingTaller ? refRect : rect).bottom;
      if (isOverFloatingEl) {
        hasLanded = true;
        if (!isLeave) {
          return;
        }
      }
      if (isOverReferenceEl) {
        hasLanded = false;
      }
      if (isOverReferenceEl && !isLeave) {
        hasLanded = true;
        return;
      }
      if (isLeave && isElement2(event.relatedTarget) && contains2(elements.floating, event.relatedTarget)) {
        return;
      }
      if (tree && getNodeChildren2(tree.nodesRef.current, nodeId).length) {
        return;
      }
      if (side === "top" && y3 >= refRect.bottom - 1 || side === "bottom" && y3 <= refRect.top + 1 || side === "left" && x5 >= refRect.right - 1 || side === "right" && x5 <= refRect.left + 1) {
        return close2();
      }
      let rectPoly = [];
      switch (side) {
        case "top":
          rectPoly = [[left, refRect.top + 1], [left, rect.bottom - 1], [right, rect.bottom - 1], [right, refRect.top + 1]];
          break;
        case "bottom":
          rectPoly = [[left, rect.top + 1], [left, refRect.bottom - 1], [right, refRect.bottom - 1], [right, rect.top + 1]];
          break;
        case "left":
          rectPoly = [[rect.right - 1, bottom], [rect.right - 1, top], [refRect.left + 1, top], [refRect.left + 1, bottom]];
          break;
        case "right":
          rectPoly = [[refRect.right - 1, bottom], [refRect.right - 1, top], [rect.left + 1, top], [rect.left + 1, bottom]];
          break;
      }
      function getPolygon(_ref2) {
        let [x6, y4] = _ref2;
        switch (side) {
          case "top": {
            const cursorPointOne = [isFloatingWider ? x6 + buffer / 2 : cursorLeaveFromRight ? x6 + buffer * 4 : x6 - buffer * 4, y4 + buffer + 1];
            const cursorPointTwo = [isFloatingWider ? x6 - buffer / 2 : cursorLeaveFromRight ? x6 + buffer * 4 : x6 - buffer * 4, y4 + buffer + 1];
            const commonPoints = [[rect.left, cursorLeaveFromRight ? rect.bottom - buffer : isFloatingWider ? rect.bottom - buffer : rect.top], [rect.right, cursorLeaveFromRight ? isFloatingWider ? rect.bottom - buffer : rect.top : rect.bottom - buffer]];
            return [cursorPointOne, cursorPointTwo, ...commonPoints];
          }
          case "bottom": {
            const cursorPointOne = [isFloatingWider ? x6 + buffer / 2 : cursorLeaveFromRight ? x6 + buffer * 4 : x6 - buffer * 4, y4 - buffer];
            const cursorPointTwo = [isFloatingWider ? x6 - buffer / 2 : cursorLeaveFromRight ? x6 + buffer * 4 : x6 - buffer * 4, y4 - buffer];
            const commonPoints = [[rect.left, cursorLeaveFromRight ? rect.top + buffer : isFloatingWider ? rect.top + buffer : rect.bottom], [rect.right, cursorLeaveFromRight ? isFloatingWider ? rect.top + buffer : rect.bottom : rect.top + buffer]];
            return [cursorPointOne, cursorPointTwo, ...commonPoints];
          }
          case "left": {
            const cursorPointOne = [x6 + buffer + 1, isFloatingTaller ? y4 + buffer / 2 : cursorLeaveFromBottom ? y4 + buffer * 4 : y4 - buffer * 4];
            const cursorPointTwo = [x6 + buffer + 1, isFloatingTaller ? y4 - buffer / 2 : cursorLeaveFromBottom ? y4 + buffer * 4 : y4 - buffer * 4];
            const commonPoints = [[cursorLeaveFromBottom ? rect.right - buffer : isFloatingTaller ? rect.right - buffer : rect.left, rect.top], [cursorLeaveFromBottom ? isFloatingTaller ? rect.right - buffer : rect.left : rect.right - buffer, rect.bottom]];
            return [...commonPoints, cursorPointOne, cursorPointTwo];
          }
          case "right": {
            const cursorPointOne = [x6 - buffer, isFloatingTaller ? y4 + buffer / 2 : cursorLeaveFromBottom ? y4 + buffer * 4 : y4 - buffer * 4];
            const cursorPointTwo = [x6 - buffer, isFloatingTaller ? y4 - buffer / 2 : cursorLeaveFromBottom ? y4 + buffer * 4 : y4 - buffer * 4];
            const commonPoints = [[cursorLeaveFromBottom ? rect.left + buffer : isFloatingTaller ? rect.left + buffer : rect.right, rect.top], [cursorLeaveFromBottom ? isFloatingTaller ? rect.left + buffer : rect.right : rect.left + buffer, rect.bottom]];
            return [cursorPointOne, cursorPointTwo, ...commonPoints];
          }
        }
      }
      if (isPointInPolygon([clientX, clientY], rectPoly)) {
        return;
      }
      if (hasLanded && !isOverReferenceRect) {
        return close2();
      }
      if (!isLeave && requireIntent) {
        const cursorSpeed = getCursorSpeed(event.clientX, event.clientY);
        const cursorSpeedThreshold = 0.1;
        if (cursorSpeed !== null && cursorSpeed < cursorSpeedThreshold) {
          return close2();
        }
      }
      if (!isPointInPolygon([clientX, clientY], getPolygon([x5, y3]))) {
        close2();
      } else if (!hasLanded && requireIntent) {
        timeoutRef.current = window.setTimeout(close2, 40);
      }
    };
  };
  fn4.__options = {
    blockPointerEvents
  };
  return fn4;
}

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/BlockNoteSchema-BOW16JHv.js
var u = Object.defineProperty;
var k = (t2, e2, n) => e2 in t2 ? u(t2, e2, { enumerable: true, configurable: true, writable: true, value: n }) : t2[e2] = n;
var i2 = (t2, e2, n) => k(t2, typeof e2 != "symbol" ? e2 + "" : e2, n);
function E2(t2) {
  const e2 = v6(t2);
  let { roots: n, nonRoots: r4 } = f5(e2);
  const s2 = [];
  for (; n.size; ) {
    s2.push(n);
    const o2 = /* @__PURE__ */ new Set();
    for (const c3 of n) {
      const a3 = t2.get(c3);
      if (a3)
        for (const l2 of a3) {
          const p4 = e2.get(l2);
          if (p4 === void 0)
            continue;
          const d = p4 - 1;
          e2.set(l2, d), d === 0 && o2.add(l2);
        }
    }
    n = o2;
  }
  if (r4 = f5(e2).nonRoots, r4.size)
    throw new Error(
      `Cycle(s) detected; toposort only works on acyclic graphs. Cyclic nodes: ${Array.from(r4).join(", ")}`
    );
  return s2;
}
function D4(t2) {
  const e2 = I3(t2);
  return E2(e2);
}
function v6(t2) {
  const e2 = /* @__PURE__ */ new Map();
  for (const [n, r4] of t2.entries()) {
    e2.has(n) || e2.set(n, 0);
    for (const s2 of r4) {
      const o2 = e2.get(s2) ?? 0;
      e2.set(s2, o2 + 1);
    }
  }
  return e2;
}
function f5(t2) {
  const e2 = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set();
  for (const [r4, s2] of t2.entries())
    s2 === 0 ? e2.add(r4) : n.add(r4);
  return { roots: e2, nonRoots: n };
}
function I3(t2) {
  const e2 = /* @__PURE__ */ new Map();
  for (const [n, r4] of t2.entries()) {
    e2.has(n) || e2.set(n, /* @__PURE__ */ new Set());
    for (const s2 of r4)
      e2.has(s2) || e2.set(s2, /* @__PURE__ */ new Set()), e2.get(s2).add(n);
  }
  return e2;
}
function A3() {
  return /* @__PURE__ */ new Map();
}
function m(t2, e2, n) {
  return t2.has(e2) || t2.set(e2, /* @__PURE__ */ new Set()), t2.get(e2).add(n), t2;
}
function P2(t2) {
  const e2 = A3();
  for (const s2 of t2)
    Array.isArray(s2.runsBefore) && s2.runsBefore.length > 0 ? s2.runsBefore.forEach((o2) => {
      m(e2, s2.key, o2);
    }) : m(e2, "default", s2.key);
  const n = D4(e2), r4 = n.findIndex((s2) => s2.has("default"));
  return (s2) => 91 + (n.findIndex((c3) => c3.has(s2)) + r4) * 10;
}
function S2(t2) {
  return t2 && Object.fromEntries(
    Object.entries(t2).filter(([, e2]) => e2 !== void 0)
  );
}
var N2 = class {
  constructor(e2) {
    i2(this, "BlockNoteEditor", "only for types");
    i2(this, "Block", "only for types");
    i2(this, "PartialBlock", "only for types");
    i2(this, "inlineContentSpecs");
    i2(this, "styleSpecs");
    i2(this, "blockSpecs");
    i2(this, "blockSchema");
    i2(this, "inlineContentSchema");
    i2(this, "styleSchema");
    this.opts = e2;
    const {
      blockSpecs: n,
      inlineContentSpecs: r4,
      styleSpecs: s2,
      blockSchema: o2,
      inlineContentSchema: c3,
      styleSchema: a3
    } = this.init();
    this.blockSpecs = n, this.styleSpecs = s2, this.styleSchema = a3, this.inlineContentSpecs = r4, this.blockSchema = o2, this.inlineContentSchema = c3;
  }
  init() {
    const e2 = P2(
      Object.entries({
        ...this.opts.blockSpecs,
        ...this.opts.inlineContentSpecs,
        ...this.opts.styleSpecs
      }).map(([o2, c3]) => {
        var a3;
        return {
          key: o2,
          runsBefore: ((a3 = c3.implementation) == null ? void 0 : a3.runsBefore) ?? []
        };
      })
    ), n = Object.fromEntries(
      Object.entries(this.opts.blockSpecs).map(([o2, c3]) => [
        o2,
        ho(
          c3.config,
          c3.implementation,
          c3.extensions,
          e2(o2)
        )
      ])
    ), r4 = Object.fromEntries(
      Object.entries(this.opts.inlineContentSpecs).map(
        ([o2, c3]) => {
          var a3;
          return typeof c3.config != "object" ? [o2, c3] : [
            o2,
            {
              ...c3,
              implementation: {
                ...c3.implementation,
                node: (a3 = c3.implementation) == null ? void 0 : a3.node.extend({
                  priority: e2(o2)
                })
              }
            }
          ];
        }
      )
    ), s2 = Object.fromEntries(
      Object.entries(this.opts.styleSpecs).map(([o2, c3]) => {
        var a3;
        return [
          o2,
          {
            ...c3,
            implementation: {
              ...c3.implementation,
              mark: (a3 = c3.implementation) == null ? void 0 : a3.mark.extend({
                priority: e2(o2)
              })
            }
          }
        ];
      })
    );
    return {
      blockSpecs: n,
      blockSchema: Object.fromEntries(
        Object.entries(n).map(([o2, c3]) => [o2, c3.config])
      ),
      inlineContentSpecs: S2(r4),
      styleSpecs: S2(s2),
      inlineContentSchema: wt2(
        r4
      ),
      styleSchema: Mt2(s2)
    };
  }
  /**
   * Adds additional block specs to the current schema in a builder pattern.
   * This method allows extending the schema after it has been created.
   *
   * @param additionalBlockSpecs - Additional block specs to add to the schema
   * @returns The current schema instance for chaining
   */
  extend(e2) {
    Object.assign(this.opts.blockSpecs, e2.blockSpecs), Object.assign(this.opts.inlineContentSpecs, e2.inlineContentSpecs), Object.assign(this.opts.styleSpecs, e2.styleSpecs);
    const {
      blockSpecs: n,
      inlineContentSpecs: r4,
      styleSpecs: s2,
      blockSchema: o2,
      inlineContentSchema: c3,
      styleSchema: a3
    } = this.init();
    return this.blockSpecs = n, this.styleSpecs = s2, this.styleSchema = a3, this.inlineContentSpecs = r4, this.blockSchema = o2, this.inlineContentSchema = c3, this;
  }
};
var R3 = mo(
  () => ({
    type: "pageBreak",
    propSchema: {},
    content: "none"
  })
);
var M5 = v2(
  R3,
  {
    parse(t2) {
      if (t2.tagName === "DIV" && t2.hasAttribute("data-page-break"))
        return {};
    },
    render() {
      const t2 = document.createElement("div");
      return t2.setAttribute("data-page-break", ""), {
        dom: t2
      };
    },
    toExternalHTML() {
      const t2 = document.createElement("div");
      return t2.setAttribute("data-page-break", ""), {
        dom: t2
      };
    }
  }
);
function F4(t2) {
  return "pageBreak" in t2.schema.blockSchema;
}
function U3(t2) {
  const e2 = [];
  return F4(t2) && e2.push({
    ...t2.dictionary.slash_menu.page_break,
    onItemClick: () => {
      C(t2, {
        type: "pageBreak"
      });
    },
    key: "page_break"
  }), e2;
}
var h5 = class _h extends N2 {
  static create(e2) {
    return new _h({
      blockSpecs: (e2 == null ? void 0 : e2.blockSpecs) ?? Po,
      inlineContentSpecs: (e2 == null ? void 0 : e2.inlineContentSpecs) ?? $n,
      styleSpecs: (e2 == null ? void 0 : e2.styleSpecs) ?? Fn
    });
  }
};

// ../../node_modules/.pnpm/@handlewithcare+prosemirror-inputrules@0.1.4_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1.41.4/node_modules/@handlewithcare/prosemirror-inputrules/dist/inputrules.js
var InputRule2 = class {
  /// Create an input rule. The rule applies when the user typed
  /// something and the text directly in front of the cursor matches
  /// `match`, which should end with `$`.
  ///
  /// The `handler` can be a string, in which case the matched text, or
  /// the first matched group in the regexp, is replaced by that
  /// string.
  ///
  /// Or a it can be a function, which will be called with the match
  /// array produced by
  /// [`RegExp.exec`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec),
  /// as well as the start and end of the matched range, and which can
  /// return a [transaction](#state.Transaction) that describes the
  /// rule's effect, or null to indicate the input was not handled.
  constructor(match2, handler, options2 = {}) {
    __publicField(this, "match");
    /// @internal
    __publicField(this, "handler");
    /// @internal
    __publicField(this, "undoable");
    __publicField(this, "inCode");
    __publicField(this, "inCodeMark");
    this.match = match2;
    this.match = match2;
    this.handler = typeof handler == "string" ? stringHandler(handler) : handler;
    this.undoable = options2.undoable !== false;
    this.inCode = options2.inCode || false;
    this.inCodeMark = options2.inCodeMark !== false;
  }
};
function stringHandler(string3) {
  return function(state, match2, start, end) {
    let insert = string3;
    if (match2[1]) {
      let offset4 = match2[0].lastIndexOf(match2[1]);
      insert += match2[0].slice(offset4 + match2[1].length);
      start += offset4;
      let cutOff = start - end;
      if (cutOff > 0) {
        insert = match2[0].slice(offset4 - cutOff, offset4) + insert;
        start = end;
      }
    }
    return state.tr.insertText(insert, start, end);
  };
}
var MAX_MATCH = 500;
function inputRules({ rules }) {
  let plugin = new Plugin({
    state: {
      init() {
        return null;
      },
      apply(tr4, prev) {
        let stored = tr4.getMeta(this);
        if (stored)
          return stored;
        return tr4.selectionSet || tr4.docChanged ? null : prev;
      }
    },
    props: {
      handleTextInput(view, from4, to2, text10) {
        return run3(view, from4, to2, text10, rules, plugin);
      },
      handleDOMEvents: {
        compositionend: (view) => {
          setTimeout(() => {
            let { $cursor } = view.state.selection;
            if ($cursor)
              run3(view, $cursor.pos, $cursor.pos, "", rules, plugin);
          });
        }
      }
    },
    isInputRules: true
  });
  return plugin;
}
function run3(view, from4, to2, text10, rules, plugin) {
  if (view.composing)
    return false;
  const insertTr = view.state.tr.insertText(text10, from4, to2);
  const mappedFrom = insertTr.mapping.map(from4);
  const mappedTo = insertTr.mapping.map(to2);
  let state = null, $from = insertTr.doc.resolve(mappedFrom);
  let textBefore = $from.parent.textBetween(Math.max(0, $from.parentOffset - MAX_MATCH), $from.parentOffset, null, "￼");
  for (let i3 = 0; i3 < rules.length; i3++) {
    let rule = rules[i3];
    if (!rule.inCodeMark && $from.marks().some((m2) => m2.type.spec.code))
      continue;
    if ($from.parent.type.spec.code) {
      if (!rule.inCode)
        continue;
    } else if (rule.inCode === "only") {
      continue;
    }
    let match2 = rule.match.exec(textBefore);
    if (!match2 || match2[0].length < text10.length)
      continue;
    state ?? (state = view.state.apply(insertTr));
    let tr4 = rule.handler(state, match2, mappedFrom - match2[0].length, mappedTo);
    if (!tr4)
      continue;
    view.dispatch(insertTr);
    view.dispatch(closeHistory(view.state.tr));
    if (rule.undoable)
      tr4.setMeta(plugin, {
        transform: tr4,
        from: mappedFrom,
        to: mappedTo,
        text: text10
      });
    view.dispatch(tr4);
    return true;
  }
  return false;
}

// ../../node_modules/.pnpm/@handlewithcare+prosemirror-inputrules@0.1.4_prosemirror-model@1.25.4_prosemirror-state@1.4.4_prosemirror-view@1.41.4/node_modules/@handlewithcare/prosemirror-inputrules/dist/rules.js
var emDash = new InputRule2(/--$/, "—", { inCodeMark: false });
var ellipsis = new InputRule2(/\.\.\.$/, "…", { inCodeMark: false });
var openDoubleQuote = new InputRule2(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(")$/, "“", { inCodeMark: false });
var closeDoubleQuote = new InputRule2(/"$/, "”", { inCodeMark: false });
var openSingleQuote = new InputRule2(/(?:^|[\s\{\[\(\<'"\u2018\u201C])(')$/, "‘", { inCodeMark: false });
var closeSingleQuote = new InputRule2(/'$/, "’", { inCodeMark: false });

// ../../node_modules/.pnpm/prosemirror-gapcursor@1.4.0/node_modules/prosemirror-gapcursor/dist/index.js
var GapCursor = class _GapCursor extends Selection {
  /**
  Create a gap cursor.
  */
  constructor($pos) {
    super($pos, $pos);
  }
  map(doc4, mapping) {
    let $pos = doc4.resolve(mapping.map(this.head));
    return _GapCursor.valid($pos) ? new _GapCursor($pos) : Selection.near($pos);
  }
  content() {
    return Slice.empty;
  }
  eq(other) {
    return other instanceof _GapCursor && other.head == this.head;
  }
  toJSON() {
    return { type: "gapcursor", pos: this.head };
  }
  /**
  @internal
  */
  static fromJSON(doc4, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for GapCursor.fromJSON");
    return new _GapCursor(doc4.resolve(json.pos));
  }
  /**
  @internal
  */
  getBookmark() {
    return new GapBookmark(this.anchor);
  }
  /**
  @internal
  */
  static valid($pos) {
    let parent = $pos.parent;
    if (parent.isTextblock || !closedBefore($pos) || !closedAfter($pos))
      return false;
    let override = parent.type.spec.allowGapCursor;
    if (override != null)
      return override;
    let deflt = parent.contentMatchAt($pos.index()).defaultType;
    return deflt && deflt.isTextblock;
  }
  /**
  @internal
  */
  static findGapCursorFrom($pos, dir, mustMove = false) {
    search: for (; ; ) {
      if (!mustMove && _GapCursor.valid($pos))
        return $pos;
      let pos = $pos.pos, next2 = null;
      for (let d = $pos.depth; ; d--) {
        let parent = $pos.node(d);
        if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) {
          next2 = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1);
          break;
        } else if (d == 0) {
          return null;
        }
        pos += dir;
        let $cur = $pos.doc.resolve(pos);
        if (_GapCursor.valid($cur))
          return $cur;
      }
      for (; ; ) {
        let inside = dir > 0 ? next2.firstChild : next2.lastChild;
        if (!inside) {
          if (next2.isAtom && !next2.isText && !NodeSelection.isSelectable(next2)) {
            $pos = $pos.doc.resolve(pos + next2.nodeSize * dir);
            mustMove = false;
            continue search;
          }
          break;
        }
        next2 = inside;
        pos += dir;
        let $cur = $pos.doc.resolve(pos);
        if (_GapCursor.valid($cur))
          return $cur;
      }
      return null;
    }
  }
};
GapCursor.prototype.visible = false;
GapCursor.findFrom = GapCursor.findGapCursorFrom;
Selection.jsonID("gapcursor", GapCursor);
var GapBookmark = class _GapBookmark {
  constructor(pos) {
    this.pos = pos;
  }
  map(mapping) {
    return new _GapBookmark(mapping.map(this.pos));
  }
  resolve(doc4) {
    let $pos = doc4.resolve(this.pos);
    return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);
  }
};
function needsGap(type) {
  return type.isAtom || type.spec.isolating || type.spec.createGapCursor;
}
function closedBefore($pos) {
  for (let d = $pos.depth; d >= 0; d--) {
    let index4 = $pos.index(d), parent = $pos.node(d);
    if (index4 == 0) {
      if (parent.type.spec.isolating)
        return true;
      continue;
    }
    for (let before = parent.child(index4 - 1); ; before = before.lastChild) {
      if (before.childCount == 0 && !before.inlineContent || needsGap(before.type))
        return true;
      if (before.inlineContent)
        return false;
    }
  }
  return true;
}
function closedAfter($pos) {
  for (let d = $pos.depth; d >= 0; d--) {
    let index4 = $pos.indexAfter(d), parent = $pos.node(d);
    if (index4 == parent.childCount) {
      if (parent.type.spec.isolating)
        return true;
      continue;
    }
    for (let after = parent.child(index4); ; after = after.firstChild) {
      if (after.childCount == 0 && !after.inlineContent || needsGap(after.type))
        return true;
      if (after.inlineContent)
        return false;
    }
  }
  return true;
}
function gapCursor() {
  return new Plugin({
    props: {
      decorations: drawGapCursor,
      createSelectionBetween(_view, $anchor, $head) {
        return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null;
      },
      handleClick,
      handleKeyDown: handleKeyDown2,
      handleDOMEvents: { beforeinput }
    }
  });
}
var handleKeyDown2 = keydownHandler({
  "ArrowLeft": arrow5("horiz", -1),
  "ArrowRight": arrow5("horiz", 1),
  "ArrowUp": arrow5("vert", -1),
  "ArrowDown": arrow5("vert", 1)
});
function arrow5(axis, dir) {
  const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left";
  return function(state, dispatch, view) {
    let sel = state.selection;
    let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty;
    if (sel instanceof TextSelection) {
      if (!view.endOfTextblock(dirStr) || $start.depth == 0)
        return false;
      mustMove = false;
      $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());
    }
    let $found = GapCursor.findGapCursorFrom($start, dir, mustMove);
    if (!$found)
      return false;
    if (dispatch)
      dispatch(state.tr.setSelection(new GapCursor($found)));
    return true;
  };
}
function handleClick(view, pos, event) {
  if (!view || !view.editable)
    return false;
  let $pos = view.state.doc.resolve(pos);
  if (!GapCursor.valid($pos))
    return false;
  let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY });
  if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside)))
    return false;
  view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));
  return true;
}
function beforeinput(view, event) {
  if (event.inputType != "insertCompositionText" || !(view.state.selection instanceof GapCursor))
    return false;
  let { $from } = view.state.selection;
  let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text);
  if (!insert)
    return false;
  let frag = Fragment.empty;
  for (let i3 = insert.length - 1; i3 >= 0; i3--)
    frag = Fragment.from(insert[i3].createAndFill(null, frag));
  let tr4 = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0));
  tr4.setSelection(TextSelection.near(tr4.doc.resolve($from.pos + 1)));
  view.dispatch(tr4);
  return false;
}
function drawGapCursor(state) {
  if (!(state.selection instanceof GapCursor))
    return null;
  let node2 = document.createElement("div");
  node2.className = "ProseMirror-gapcursor";
  return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node2, { key: "gapcursor" })]);
}

// ../../node_modules/.pnpm/@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__@tiptap+pm@3.14.0/node_modules/@tiptap/extensions/dist/index.js
var CharacterCount = Extension.create({
  name: "characterCount",
  addOptions() {
    return {
      limit: null,
      mode: "textSize",
      textCounter: (text10) => text10.length,
      wordCounter: (text10) => text10.split(" ").filter((word2) => word2 !== "").length
    };
  },
  addStorage() {
    return {
      characters: () => 0,
      words: () => 0
    };
  },
  onBeforeCreate() {
    this.storage.characters = (options2) => {
      const node2 = (options2 == null ? void 0 : options2.node) || this.editor.state.doc;
      const mode = (options2 == null ? void 0 : options2.mode) || this.options.mode;
      if (mode === "textSize") {
        const text10 = node2.textBetween(0, node2.content.size, void 0, " ");
        return this.options.textCounter(text10);
      }
      return node2.nodeSize;
    };
    this.storage.words = (options2) => {
      const node2 = (options2 == null ? void 0 : options2.node) || this.editor.state.doc;
      const text10 = node2.textBetween(0, node2.content.size, " ", " ");
      return this.options.wordCounter(text10);
    };
  },
  addProseMirrorPlugins() {
    let initialEvaluationDone = false;
    return [
      new Plugin({
        key: new PluginKey("characterCount"),
        appendTransaction: (transactions, oldState, newState) => {
          if (initialEvaluationDone) {
            return;
          }
          const limit = this.options.limit;
          if (limit === null || limit === void 0 || limit === 0) {
            initialEvaluationDone = true;
            return;
          }
          const initialContentSize = this.storage.characters({ node: newState.doc });
          if (initialContentSize > limit) {
            const over = initialContentSize - limit;
            const from4 = 0;
            const to2 = over;
            console.warn(
              `[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.`
            );
            const tr4 = newState.tr.deleteRange(from4, to2);
            initialEvaluationDone = true;
            return tr4;
          }
          initialEvaluationDone = true;
        },
        filterTransaction: (transaction, state) => {
          const limit = this.options.limit;
          if (!transaction.docChanged || limit === 0 || limit === null || limit === void 0) {
            return true;
          }
          const oldSize = this.storage.characters({ node: state.doc });
          const newSize = this.storage.characters({ node: transaction.doc });
          if (newSize <= limit) {
            return true;
          }
          if (oldSize > limit && newSize > limit && newSize <= oldSize) {
            return true;
          }
          if (oldSize > limit && newSize > limit && newSize > oldSize) {
            return false;
          }
          const isPaste = transaction.getMeta("paste");
          if (!isPaste) {
            return false;
          }
          const pos = transaction.selection.$head.pos;
          const over = newSize - limit;
          const from4 = pos - over;
          const to2 = pos;
          transaction.deleteRange(from4, to2);
          const updatedSize = this.storage.characters({ node: transaction.doc });
          if (updatedSize > limit) {
            return false;
          }
          return true;
        }
      })
    ];
  }
});
var Dropcursor = Extension.create({
  name: "dropCursor",
  addOptions() {
    return {
      color: "currentColor",
      width: 1,
      class: void 0
    };
  },
  addProseMirrorPlugins() {
    return [dropCursor(this.options)];
  }
});
var Focus = Extension.create({
  name: "focus",
  addOptions() {
    return {
      className: "has-focus",
      mode: "all"
    };
  },
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("focus"),
        props: {
          decorations: ({ doc: doc4, selection }) => {
            const { isEditable, isFocused } = this.editor;
            const { anchor } = selection;
            const decorations = [];
            if (!isEditable || !isFocused) {
              return DecorationSet.create(doc4, []);
            }
            let maxLevels = 0;
            if (this.options.mode === "deepest") {
              doc4.descendants((node2, pos) => {
                if (node2.isText) {
                  return;
                }
                const isCurrent = anchor >= pos && anchor <= pos + node2.nodeSize - 1;
                if (!isCurrent) {
                  return false;
                }
                maxLevels += 1;
              });
            }
            let currentLevel = 0;
            doc4.descendants((node2, pos) => {
              if (node2.isText) {
                return false;
              }
              const isCurrent = anchor >= pos && anchor <= pos + node2.nodeSize - 1;
              if (!isCurrent) {
                return false;
              }
              currentLevel += 1;
              const outOfScope = this.options.mode === "deepest" && maxLevels - currentLevel > 0 || this.options.mode === "shallowest" && currentLevel > 1;
              if (outOfScope) {
                return this.options.mode === "deepest";
              }
              decorations.push(
                Decoration.node(pos, pos + node2.nodeSize, {
                  class: this.options.className
                })
              );
            });
            return DecorationSet.create(doc4, decorations);
          }
        }
      })
    ];
  }
});
var Gapcursor = Extension.create({
  name: "gapCursor",
  addProseMirrorPlugins() {
    return [gapCursor()];
  },
  extendNodeSchema(extension2) {
    var _a2;
    const context = {
      name: extension2.name,
      options: extension2.options,
      storage: extension2.storage
    };
    return {
      allowGapCursor: (_a2 = callOrReturn(getExtensionField(extension2, "allowGapCursor", context))) != null ? _a2 : null
    };
  }
});
var Placeholder = Extension.create({
  name: "placeholder",
  addOptions() {
    return {
      emptyEditorClass: "is-editor-empty",
      emptyNodeClass: "is-empty",
      placeholder: "Write something …",
      showOnlyWhenEditable: true,
      showOnlyCurrent: true,
      includeChildren: false
    };
  },
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("placeholder"),
        props: {
          decorations: ({ doc: doc4, selection }) => {
            const active = this.editor.isEditable || !this.options.showOnlyWhenEditable;
            const { anchor } = selection;
            const decorations = [];
            if (!active) {
              return null;
            }
            const isEmptyDoc = this.editor.isEmpty;
            doc4.descendants((node2, pos) => {
              const hasAnchor = anchor >= pos && anchor <= pos + node2.nodeSize;
              const isEmpty3 = !node2.isLeaf && isNodeEmpty(node2);
              if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty3) {
                const classes = [this.options.emptyNodeClass];
                if (isEmptyDoc) {
                  classes.push(this.options.emptyEditorClass);
                }
                const decoration = Decoration.node(pos, pos + node2.nodeSize, {
                  class: classes.join(" "),
                  "data-placeholder": typeof this.options.placeholder === "function" ? this.options.placeholder({
                    editor: this.editor,
                    node: node2,
                    pos,
                    hasAnchor
                  }) : this.options.placeholder
                });
                decorations.push(decoration);
              }
              return this.options.includeChildren;
            });
            return DecorationSet.create(doc4, decorations);
          }
        }
      })
    ];
  }
});
var Selection2 = Extension.create({
  name: "selection",
  addOptions() {
    return {
      className: "selection"
    };
  },
  addProseMirrorPlugins() {
    const { editor, options: options2 } = this;
    return [
      new Plugin({
        key: new PluginKey("selection"),
        props: {
          decorations(state) {
            if (state.selection.empty || editor.isFocused || !editor.isEditable || isNodeSelection(state.selection) || editor.view.dragging) {
              return null;
            }
            return DecorationSet.create(state.doc, [
              Decoration.inline(state.selection.from, state.selection.to, {
                class: options2.className
              })
            ]);
          }
        }
      })
    ];
  }
});
function nodeEqualsType({ types: types2, node: node2 }) {
  return node2 && Array.isArray(types2) && types2.includes(node2.type) || (node2 == null ? void 0 : node2.type) === types2;
}
var TrailingNode = Extension.create({
  name: "trailingNode",
  addOptions() {
    return {
      node: void 0,
      notAfter: []
    };
  },
  addProseMirrorPlugins() {
    var _a2;
    const plugin = new PluginKey(this.name);
    const defaultNode = this.options.node || ((_a2 = this.editor.schema.topNodeType.contentMatch.defaultType) == null ? void 0 : _a2.name) || "paragraph";
    const disabledNodes = Object.entries(this.editor.schema.nodes).map(([, value]) => value).filter((node2) => (this.options.notAfter || []).concat(defaultNode).includes(node2.name));
    return [
      new Plugin({
        key: plugin,
        appendTransaction: (_2, __, state) => {
          const { doc: doc4, tr: tr4, schema } = state;
          const shouldInsertNodeAtEnd = plugin.getState(state);
          const endPosition = doc4.content.size;
          const type = schema.nodes[defaultNode];
          if (!shouldInsertNodeAtEnd) {
            return;
          }
          return tr4.insert(endPosition, type.create());
        },
        state: {
          init: (_2, state) => {
            const lastNode = state.tr.doc.lastChild;
            return !nodeEqualsType({ node: lastNode, types: disabledNodes });
          },
          apply: (tr4, value) => {
            if (!tr4.docChanged) {
              return value;
            }
            if (tr4.getMeta("__uniqueIDTransaction")) {
              return value;
            }
            const lastNode = tr4.doc.lastChild;
            return !nodeEqualsType({ node: lastNode, types: disabledNodes });
          }
        }
      })
    ];
  }
});
var UndoRedo = Extension.create({
  name: "undoRedo",
  addOptions() {
    return {
      depth: 100,
      newGroupDelay: 500
    };
  },
  addCommands() {
    return {
      undo: () => ({ state, dispatch }) => {
        return undo2(state, dispatch);
      },
      redo: () => ({ state, dispatch }) => {
        return redo2(state, dispatch);
      }
    };
  },
  addProseMirrorPlugins() {
    return [history(this.options)];
  },
  addKeyboardShortcuts() {
    return {
      "Mod-z": () => this.editor.commands.undo(),
      "Shift-Mod-z": () => this.editor.commands.redo(),
      "Mod-y": () => this.editor.commands.redo(),
      // Russian keyboard layouts
      "Mod-я": () => this.editor.commands.undo(),
      "Shift-Mod-я": () => this.editor.commands.redo()
    };
  }
});

// ../../node_modules/.pnpm/linkifyjs@4.3.2/node_modules/linkifyjs/dist/linkify.mjs
var encodedTlds = " ögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2";
var encodedUtlds = "ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2";
var numeric = "numeric";
var ascii = "ascii";
var alpha = "alpha";
var asciinumeric = "asciinumeric";
var alphanumeric = "alphanumeric";
var domain2 = "domain";
var emoji = "emoji";
var scheme = "scheme";
var slashscheme = "slashscheme";
var whitespace2 = "whitespace";
function registerGroup(name, groups) {
  if (!(name in groups)) {
    groups[name] = [];
  }
  return groups[name];
}
function addToGroups(t2, flags, groups) {
  if (flags[numeric]) {
    flags[asciinumeric] = true;
    flags[alphanumeric] = true;
  }
  if (flags[ascii]) {
    flags[asciinumeric] = true;
    flags[alpha] = true;
  }
  if (flags[asciinumeric]) {
    flags[alphanumeric] = true;
  }
  if (flags[alpha]) {
    flags[alphanumeric] = true;
  }
  if (flags[alphanumeric]) {
    flags[domain2] = true;
  }
  if (flags[emoji]) {
    flags[domain2] = true;
  }
  for (const k3 in flags) {
    const group = registerGroup(k3, groups);
    if (group.indexOf(t2) < 0) {
      group.push(t2);
    }
  }
}
function flagsForToken(t2, groups) {
  const result = {};
  for (const c3 in groups) {
    if (groups[c3].indexOf(t2) >= 0) {
      result[c3] = true;
    }
  }
  return result;
}
function State2(token = null) {
  this.j = {};
  this.jr = [];
  this.jd = null;
  this.t = token;
}
State2.groups = {};
State2.prototype = {
  accepts() {
    return !!this.t;
  },
  /**
   * Follow an existing transition from the given input to the next state.
   * Does not mutate.
   * @param {string} input character or token type to transition on
   * @returns {?State<T>} the next state, if any
   */
  go(input2) {
    const state = this;
    const nextState = state.j[input2];
    if (nextState) {
      return nextState;
    }
    for (let i3 = 0; i3 < state.jr.length; i3++) {
      const regex = state.jr[i3][0];
      const nextState2 = state.jr[i3][1];
      if (nextState2 && regex.test(input2)) {
        return nextState2;
      }
    }
    return state.jd;
  },
  /**
   * Whether the state has a transition for the given input. Set the second
   * argument to true to only look for an exact match (and not a default or
   * regular-expression-based transition)
   * @param {string} input
   * @param {boolean} exactOnly
   */
  has(input2, exactOnly = false) {
    return exactOnly ? input2 in this.j : !!this.go(input2);
  },
  /**
   * Short for "transition all"; create a transition from the array of items
   * in the given list to the same final resulting state.
   * @param {string | string[]} inputs Group of inputs to transition on
   * @param {Transition<T> | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   */
  ta(inputs, next2, flags, groups) {
    for (let i3 = 0; i3 < inputs.length; i3++) {
      this.tt(inputs[i3], next2, flags, groups);
    }
  },
  /**
   * Short for "take regexp transition"; defines a transition for this state
   * when it encounters a token which matches the given regular expression
   * @param {RegExp} regexp Regular expression transition (populate first)
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   * @returns {State<T>} taken after the given input
   */
  tr(regexp2, next2, flags, groups) {
    groups = groups || State2.groups;
    let nextState;
    if (next2 && next2.j) {
      nextState = next2;
    } else {
      nextState = new State2(next2);
      if (flags && groups) {
        addToGroups(next2, flags, groups);
      }
    }
    this.jr.push([regexp2, nextState]);
    return nextState;
  },
  /**
   * Short for "take transitions", will take as many sequential transitions as
   * the length of the given input and returns the
   * resulting final state.
   * @param {string | string[]} input
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   * @returns {State<T>} taken after the given input
   */
  ts(input2, next2, flags, groups) {
    let state = this;
    const len = input2.length;
    if (!len) {
      return state;
    }
    for (let i3 = 0; i3 < len - 1; i3++) {
      state = state.tt(input2[i3]);
    }
    return state.tt(input2[len - 1], next2, flags, groups);
  },
  /**
   * Short for "take transition", this is a method for building/working with
   * state machines.
   *
   * If a state already exists for the given input, returns it.
   *
   * If a token is specified, that state will emit that token when reached by
   * the linkify engine.
   *
   * If no state exists, it will be initialized with some default transitions
   * that resemble existing default transitions.
   *
   * If a state is given for the second argument, that state will be
   * transitioned to on the given input regardless of what that input
   * previously did.
   *
   * Specify a token group flags to define groups that this token belongs to.
   * The token will be added to corresponding entires in the given groups
   * object.
   *
   * @param {string} input character, token type to transition on
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of groups
   * @returns {State<T>} taken after the given input
   */
  tt(input2, next2, flags, groups) {
    groups = groups || State2.groups;
    const state = this;
    if (next2 && next2.j) {
      state.j[input2] = next2;
      return next2;
    }
    const t2 = next2;
    let nextState, templateState = state.go(input2);
    if (templateState) {
      nextState = new State2();
      Object.assign(nextState.j, templateState.j);
      nextState.jr.push.apply(nextState.jr, templateState.jr);
      nextState.jd = templateState.jd;
      nextState.t = templateState.t;
    } else {
      nextState = new State2();
    }
    if (t2) {
      if (groups) {
        if (nextState.t && typeof nextState.t === "string") {
          const allFlags = Object.assign(flagsForToken(nextState.t, groups), flags);
          addToGroups(t2, allFlags, groups);
        } else if (flags) {
          addToGroups(t2, flags, groups);
        }
      }
      nextState.t = t2;
    }
    state.j[input2] = nextState;
    return nextState;
  }
};
var ta = (state, input2, next2, flags, groups) => state.ta(input2, next2, flags, groups);
var tr = (state, regexp2, next2, flags, groups) => state.tr(regexp2, next2, flags, groups);
var ts = (state, input2, next2, flags, groups) => state.ts(input2, next2, flags, groups);
var tt2 = (state, input2, next2, flags, groups) => state.tt(input2, next2, flags, groups);
var WORD = "WORD";
var UWORD = "UWORD";
var ASCIINUMERICAL = "ASCIINUMERICAL";
var ALPHANUMERICAL = "ALPHANUMERICAL";
var LOCALHOST = "LOCALHOST";
var TLD = "TLD";
var UTLD = "UTLD";
var SCHEME = "SCHEME";
var SLASH_SCHEME = "SLASH_SCHEME";
var NUM = "NUM";
var WS = "WS";
var NL = "NL";
var OPENBRACE = "OPENBRACE";
var CLOSEBRACE = "CLOSEBRACE";
var OPENBRACKET = "OPENBRACKET";
var CLOSEBRACKET = "CLOSEBRACKET";
var OPENPAREN = "OPENPAREN";
var CLOSEPAREN = "CLOSEPAREN";
var OPENANGLEBRACKET = "OPENANGLEBRACKET";
var CLOSEANGLEBRACKET = "CLOSEANGLEBRACKET";
var FULLWIDTHLEFTPAREN = "FULLWIDTHLEFTPAREN";
var FULLWIDTHRIGHTPAREN = "FULLWIDTHRIGHTPAREN";
var LEFTCORNERBRACKET = "LEFTCORNERBRACKET";
var RIGHTCORNERBRACKET = "RIGHTCORNERBRACKET";
var LEFTWHITECORNERBRACKET = "LEFTWHITECORNERBRACKET";
var RIGHTWHITECORNERBRACKET = "RIGHTWHITECORNERBRACKET";
var FULLWIDTHLESSTHAN = "FULLWIDTHLESSTHAN";
var FULLWIDTHGREATERTHAN = "FULLWIDTHGREATERTHAN";
var AMPERSAND = "AMPERSAND";
var APOSTROPHE = "APOSTROPHE";
var ASTERISK = "ASTERISK";
var AT = "AT";
var BACKSLASH = "BACKSLASH";
var BACKTICK = "BACKTICK";
var CARET = "CARET";
var COLON = "COLON";
var COMMA = "COMMA";
var DOLLAR = "DOLLAR";
var DOT = "DOT";
var EQUALS = "EQUALS";
var EXCLAMATION = "EXCLAMATION";
var HYPHEN = "HYPHEN";
var PERCENT = "PERCENT";
var PIPE = "PIPE";
var PLUS = "PLUS";
var POUND = "POUND";
var QUERY = "QUERY";
var QUOTE = "QUOTE";
var FULLWIDTHMIDDLEDOT = "FULLWIDTHMIDDLEDOT";
var SEMI = "SEMI";
var SLASH = "SLASH";
var TILDE = "TILDE";
var UNDERSCORE = "UNDERSCORE";
var EMOJI$1 = "EMOJI";
var SYM = "SYM";
var tk = Object.freeze({
  __proto__: null,
  ALPHANUMERICAL,
  AMPERSAND,
  APOSTROPHE,
  ASCIINUMERICAL,
  ASTERISK,
  AT,
  BACKSLASH,
  BACKTICK,
  CARET,
  CLOSEANGLEBRACKET,
  CLOSEBRACE,
  CLOSEBRACKET,
  CLOSEPAREN,
  COLON,
  COMMA,
  DOLLAR,
  DOT,
  EMOJI: EMOJI$1,
  EQUALS,
  EXCLAMATION,
  FULLWIDTHGREATERTHAN,
  FULLWIDTHLEFTPAREN,
  FULLWIDTHLESSTHAN,
  FULLWIDTHMIDDLEDOT,
  FULLWIDTHRIGHTPAREN,
  HYPHEN,
  LEFTCORNERBRACKET,
  LEFTWHITECORNERBRACKET,
  LOCALHOST,
  NL,
  NUM,
  OPENANGLEBRACKET,
  OPENBRACE,
  OPENBRACKET,
  OPENPAREN,
  PERCENT,
  PIPE,
  PLUS,
  POUND,
  QUERY,
  QUOTE,
  RIGHTCORNERBRACKET,
  RIGHTWHITECORNERBRACKET,
  SCHEME,
  SEMI,
  SLASH,
  SLASH_SCHEME,
  SYM,
  TILDE,
  TLD,
  UNDERSCORE,
  UTLD,
  UWORD,
  WORD,
  WS
});
var ASCII_LETTER = /[a-z]/;
var LETTER = new RegExp("\\p{L}", "u");
var EMOJI = new RegExp("\\p{Emoji}", "u");
var EMOJI_VARIATION$1 = /\ufe0f/;
var DIGIT = /\d/;
var SPACE = /\s/;
var regexp = Object.freeze({
  __proto__: null,
  ASCII_LETTER,
  DIGIT,
  EMOJI,
  EMOJI_VARIATION: EMOJI_VARIATION$1,
  LETTER,
  SPACE
});
var CR = "\r";
var LF = "\n";
var EMOJI_VARIATION = "️";
var EMOJI_JOINER = "‍";
var OBJECT_REPLACEMENT = "￼";
var tlds = null;
var utlds = null;
function init$2(customSchemes = []) {
  const groups = {};
  State2.groups = groups;
  const Start = new State2();
  if (tlds == null) {
    tlds = decodeTlds(encodedTlds);
  }
  if (utlds == null) {
    utlds = decodeTlds(encodedUtlds);
  }
  tt2(Start, "'", APOSTROPHE);
  tt2(Start, "{", OPENBRACE);
  tt2(Start, "}", CLOSEBRACE);
  tt2(Start, "[", OPENBRACKET);
  tt2(Start, "]", CLOSEBRACKET);
  tt2(Start, "(", OPENPAREN);
  tt2(Start, ")", CLOSEPAREN);
  tt2(Start, "<", OPENANGLEBRACKET);
  tt2(Start, ">", CLOSEANGLEBRACKET);
  tt2(Start, "（", FULLWIDTHLEFTPAREN);
  tt2(Start, "）", FULLWIDTHRIGHTPAREN);
  tt2(Start, "「", LEFTCORNERBRACKET);
  tt2(Start, "」", RIGHTCORNERBRACKET);
  tt2(Start, "『", LEFTWHITECORNERBRACKET);
  tt2(Start, "』", RIGHTWHITECORNERBRACKET);
  tt2(Start, "＜", FULLWIDTHLESSTHAN);
  tt2(Start, "＞", FULLWIDTHGREATERTHAN);
  tt2(Start, "&", AMPERSAND);
  tt2(Start, "*", ASTERISK);
  tt2(Start, "@", AT);
  tt2(Start, "`", BACKTICK);
  tt2(Start, "^", CARET);
  tt2(Start, ":", COLON);
  tt2(Start, ",", COMMA);
  tt2(Start, "$", DOLLAR);
  tt2(Start, ".", DOT);
  tt2(Start, "=", EQUALS);
  tt2(Start, "!", EXCLAMATION);
  tt2(Start, "-", HYPHEN);
  tt2(Start, "%", PERCENT);
  tt2(Start, "|", PIPE);
  tt2(Start, "+", PLUS);
  tt2(Start, "#", POUND);
  tt2(Start, "?", QUERY);
  tt2(Start, '"', QUOTE);
  tt2(Start, "/", SLASH);
  tt2(Start, ";", SEMI);
  tt2(Start, "~", TILDE);
  tt2(Start, "_", UNDERSCORE);
  tt2(Start, "\\", BACKSLASH);
  tt2(Start, "・", FULLWIDTHMIDDLEDOT);
  const Num = tr(Start, DIGIT, NUM, {
    [numeric]: true
  });
  tr(Num, DIGIT, Num);
  const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, {
    [asciinumeric]: true
  });
  const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, {
    [alphanumeric]: true
  });
  const Word = tr(Start, ASCII_LETTER, WORD, {
    [ascii]: true
  });
  tr(Word, DIGIT, Asciinumeric);
  tr(Word, ASCII_LETTER, Word);
  tr(Asciinumeric, DIGIT, Asciinumeric);
  tr(Asciinumeric, ASCII_LETTER, Asciinumeric);
  const UWord = tr(Start, LETTER, UWORD, {
    [alpha]: true
  });
  tr(UWord, ASCII_LETTER);
  tr(UWord, DIGIT, Alphanumeric);
  tr(UWord, LETTER, UWord);
  tr(Alphanumeric, DIGIT, Alphanumeric);
  tr(Alphanumeric, ASCII_LETTER);
  tr(Alphanumeric, LETTER, Alphanumeric);
  const Nl3 = tt2(Start, LF, NL, {
    [whitespace2]: true
  });
  const Cr2 = tt2(Start, CR, WS, {
    [whitespace2]: true
  });
  const Ws = tr(Start, SPACE, WS, {
    [whitespace2]: true
  });
  tt2(Start, OBJECT_REPLACEMENT, Ws);
  tt2(Cr2, LF, Nl3);
  tt2(Cr2, OBJECT_REPLACEMENT, Ws);
  tr(Cr2, SPACE, Ws);
  tt2(Ws, CR);
  tt2(Ws, LF);
  tr(Ws, SPACE, Ws);
  tt2(Ws, OBJECT_REPLACEMENT, Ws);
  const Emoji = tr(Start, EMOJI, EMOJI$1, {
    [emoji]: true
  });
  tt2(Emoji, "#");
  tr(Emoji, EMOJI, Emoji);
  tt2(Emoji, EMOJI_VARIATION, Emoji);
  const EmojiJoiner = tt2(Emoji, EMOJI_JOINER);
  tt2(EmojiJoiner, "#");
  tr(EmojiJoiner, EMOJI, Emoji);
  const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]];
  const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]];
  for (let i3 = 0; i3 < tlds.length; i3++) {
    fastts(Start, tlds[i3], TLD, WORD, wordjr);
  }
  for (let i3 = 0; i3 < utlds.length; i3++) {
    fastts(Start, utlds[i3], UTLD, UWORD, uwordjr);
  }
  addToGroups(TLD, {
    tld: true,
    ascii: true
  }, groups);
  addToGroups(UTLD, {
    utld: true,
    alpha: true
  }, groups);
  fastts(Start, "file", SCHEME, WORD, wordjr);
  fastts(Start, "mailto", SCHEME, WORD, wordjr);
  fastts(Start, "http", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "https", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "ftp", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "ftps", SLASH_SCHEME, WORD, wordjr);
  addToGroups(SCHEME, {
    scheme: true,
    ascii: true
  }, groups);
  addToGroups(SLASH_SCHEME, {
    slashscheme: true,
    ascii: true
  }, groups);
  customSchemes = customSchemes.sort((a3, b4) => a3[0] > b4[0] ? 1 : -1);
  for (let i3 = 0; i3 < customSchemes.length; i3++) {
    const sch = customSchemes[i3][0];
    const optionalSlashSlash = customSchemes[i3][1];
    const flags = optionalSlashSlash ? {
      [scheme]: true
    } : {
      [slashscheme]: true
    };
    if (sch.indexOf("-") >= 0) {
      flags[domain2] = true;
    } else if (!ASCII_LETTER.test(sch)) {
      flags[numeric] = true;
    } else if (DIGIT.test(sch)) {
      flags[asciinumeric] = true;
    } else {
      flags[ascii] = true;
    }
    ts(Start, sch, sch, flags);
  }
  ts(Start, "localhost", LOCALHOST, {
    ascii: true
  });
  Start.jd = new State2(SYM);
  return {
    start: Start,
    tokens: Object.assign({
      groups
    }, tk)
  };
}
function run$1(start, str) {
  const iterable = stringToArray(str.replace(/[A-Z]/g, (c3) => c3.toLowerCase()));
  const charCount = iterable.length;
  const tokens = [];
  let cursor = 0;
  let charCursor = 0;
  while (charCursor < charCount) {
    let state = start;
    let nextState = null;
    let tokenLength = 0;
    let latestAccepting = null;
    let sinceAccepts = -1;
    let charsSinceAccepts = -1;
    while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) {
      state = nextState;
      if (state.accepts()) {
        sinceAccepts = 0;
        charsSinceAccepts = 0;
        latestAccepting = state;
      } else if (sinceAccepts >= 0) {
        sinceAccepts += iterable[charCursor].length;
        charsSinceAccepts++;
      }
      tokenLength += iterable[charCursor].length;
      cursor += iterable[charCursor].length;
      charCursor++;
    }
    cursor -= sinceAccepts;
    charCursor -= charsSinceAccepts;
    tokenLength -= sinceAccepts;
    tokens.push({
      t: latestAccepting.t,
      // token type/name
      v: str.slice(cursor - tokenLength, cursor),
      // string value
      s: cursor - tokenLength,
      // start index
      e: cursor
      // end index (excluding)
    });
  }
  return tokens;
}
function stringToArray(str) {
  const result = [];
  const len = str.length;
  let index4 = 0;
  while (index4 < len) {
    let first2 = str.charCodeAt(index4);
    let second;
    let char = first2 < 55296 || first2 > 56319 || index4 + 1 === len || (second = str.charCodeAt(index4 + 1)) < 56320 || second > 57343 ? str[index4] : str.slice(index4, index4 + 2);
    result.push(char);
    index4 += char.length;
  }
  return result;
}
function fastts(state, input2, t2, defaultt, jr2) {
  let next2;
  const len = input2.length;
  for (let i3 = 0; i3 < len - 1; i3++) {
    const char = input2[i3];
    if (state.j[char]) {
      next2 = state.j[char];
    } else {
      next2 = new State2(defaultt);
      next2.jr = jr2.slice();
      state.j[char] = next2;
    }
    state = next2;
  }
  next2 = new State2(t2);
  next2.jr = jr2.slice();
  state.j[input2[len - 1]] = next2;
  return next2;
}
function decodeTlds(encoded) {
  const words = [];
  const stack = [];
  let i3 = 0;
  let digits = "0123456789";
  while (i3 < encoded.length) {
    let popDigitCount = 0;
    while (digits.indexOf(encoded[i3 + popDigitCount]) >= 0) {
      popDigitCount++;
    }
    if (popDigitCount > 0) {
      words.push(stack.join(""));
      for (let popCount = parseInt(encoded.substring(i3, i3 + popDigitCount), 10); popCount > 0; popCount--) {
        stack.pop();
      }
      i3 += popDigitCount;
    } else {
      stack.push(encoded[i3]);
      i3++;
    }
  }
  return words;
}
var defaults2 = {
  defaultProtocol: "http",
  events: null,
  format: noop5,
  formatHref: noop5,
  nl2br: false,
  tagName: "a",
  target: null,
  rel: null,
  validate: true,
  truncate: Infinity,
  className: null,
  attributes: null,
  ignoreTags: [],
  render: null
};
function Options(opts, defaultRender = null) {
  let o2 = Object.assign({}, defaults2);
  if (opts) {
    o2 = Object.assign(o2, opts instanceof Options ? opts.o : opts);
  }
  const ignoredTags = o2.ignoreTags;
  const uppercaseIgnoredTags = [];
  for (let i3 = 0; i3 < ignoredTags.length; i3++) {
    uppercaseIgnoredTags.push(ignoredTags[i3].toUpperCase());
  }
  this.o = o2;
  if (defaultRender) {
    this.defaultRender = defaultRender;
  }
  this.ignoreTags = uppercaseIgnoredTags;
}
Options.prototype = {
  o: defaults2,
  /**
   * @type string[]
   */
  ignoreTags: [],
  /**
   * @param {IntermediateRepresentation} ir
   * @returns {any}
   */
  defaultRender(ir2) {
    return ir2;
  },
  /**
   * Returns true or false based on whether a token should be displayed as a
   * link based on the user options.
   * @param {MultiToken} token
   * @returns {boolean}
   */
  check(token) {
    return this.get("validate", token.toString(), token);
  },
  // Private methods
  /**
   * Resolve an option's value based on the value of the option and the given
   * params. If operator and token are specified and the target option is
   * callable, automatically calls the function with the given argument.
   * @template {keyof Opts} K
   * @param {K} key Name of option to use
   * @param {string} [operator] will be passed to the target option if it's a
   * function. If not specified, RAW function value gets returned
   * @param {MultiToken} [token] The token from linkify.tokenize
   * @returns {Opts[K] | any}
   */
  get(key2, operator, token) {
    const isCallable = operator != null;
    let option2 = this.o[key2];
    if (!option2) {
      return option2;
    }
    if (typeof option2 === "object") {
      option2 = token.t in option2 ? option2[token.t] : defaults2[key2];
      if (typeof option2 === "function" && isCallable) {
        option2 = option2(operator, token);
      }
    } else if (typeof option2 === "function" && isCallable) {
      option2 = option2(operator, token.t, token);
    }
    return option2;
  },
  /**
   * @template {keyof Opts} L
   * @param {L} key Name of options object to use
   * @param {string} [operator]
   * @param {MultiToken} [token]
   * @returns {Opts[L] | any}
   */
  getObj(key2, operator, token) {
    let obj = this.o[key2];
    if (typeof obj === "function" && operator != null) {
      obj = obj(operator, token.t, token);
    }
    return obj;
  },
  /**
   * Convert the given token to a rendered element that may be added to the
   * calling-interface's DOM
   * @param {MultiToken} token Token to render to an HTML element
   * @returns {any} Render result; e.g., HTML string, DOM element, React
   *   Component, etc.
   */
  render(token) {
    const ir2 = token.render(this);
    const renderFn = this.get("render", null, token) || this.defaultRender;
    return renderFn(ir2, token.t, token);
  }
};
function noop5(val) {
  return val;
}
var options = Object.freeze({
  __proto__: null,
  Options,
  defaults: defaults2
});
function MultiToken(value, tokens) {
  this.t = "token";
  this.v = value;
  this.tk = tokens;
}
MultiToken.prototype = {
  isLink: false,
  /**
   * Return the string this token represents.
   * @return {string}
   */
  toString() {
    return this.v;
  },
  /**
   * What should the value for this token be in the `href` HTML attribute?
   * Returns the `.toString` value by default.
   * @param {string} [scheme]
   * @return {string}
   */
  toHref(scheme2) {
    return this.toString();
  },
  /**
   * @param {Options} options Formatting options
   * @returns {string}
   */
  toFormattedString(options2) {
    const val = this.toString();
    const truncate = options2.get("truncate", val, this);
    const formatted = options2.get("format", val, this);
    return truncate && formatted.length > truncate ? formatted.substring(0, truncate) + "…" : formatted;
  },
  /**
   *
   * @param {Options} options
   * @returns {string}
   */
  toFormattedHref(options2) {
    return options2.get("formatHref", this.toHref(options2.get("defaultProtocol")), this);
  },
  /**
   * The start index of this token in the original input string
   * @returns {number}
   */
  startIndex() {
    return this.tk[0].s;
  },
  /**
   * The end index of this token in the original input string (up to this
   * index but not including it)
   * @returns {number}
   */
  endIndex() {
    return this.tk[this.tk.length - 1].e;
  },
  /**
  	Returns an object  of relevant values for this token, which includes keys
  	* type - Kind of token ('url', 'email', etc.)
  	* value - Original text
  	* href - The value that should be added to the anchor tag's href
  		attribute
  		@method toObject
  	@param {string} [protocol] `'http'` by default
  */
  toObject(protocol = defaults2.defaultProtocol) {
    return {
      type: this.t,
      value: this.toString(),
      isLink: this.isLink,
      href: this.toHref(protocol),
      start: this.startIndex(),
      end: this.endIndex()
    };
  },
  /**
   *
   * @param {Options} options Formatting option
   */
  toFormattedObject(options2) {
    return {
      type: this.t,
      value: this.toFormattedString(options2),
      isLink: this.isLink,
      href: this.toFormattedHref(options2),
      start: this.startIndex(),
      end: this.endIndex()
    };
  },
  /**
   * Whether this token should be rendered as a link according to the given options
   * @param {Options} options
   * @returns {boolean}
   */
  validate(options2) {
    return options2.get("validate", this.toString(), this);
  },
  /**
   * Return an object that represents how this link should be rendered.
   * @param {Options} options Formattinng options
   */
  render(options2) {
    const token = this;
    const href = this.toHref(options2.get("defaultProtocol"));
    const formattedHref = options2.get("formatHref", href, this);
    const tagName = options2.get("tagName", href, token);
    const content5 = this.toFormattedString(options2);
    const attributes = {};
    const className = options2.get("className", href, token);
    const target = options2.get("target", href, token);
    const rel = options2.get("rel", href, token);
    const attrs = options2.getObj("attributes", href, token);
    const eventListeners = options2.getObj("events", href, token);
    attributes.href = formattedHref;
    if (className) {
      attributes.class = className;
    }
    if (target) {
      attributes.target = target;
    }
    if (rel) {
      attributes.rel = rel;
    }
    if (attrs) {
      Object.assign(attributes, attrs);
    }
    return {
      tagName,
      attributes,
      content: content5,
      eventListeners
    };
  }
};
function createTokenClass(type, props) {
  class Token extends MultiToken {
    constructor(value, tokens) {
      super(value, tokens);
      this.t = type;
    }
  }
  for (const p4 in props) {
    Token.prototype[p4] = props[p4];
  }
  Token.t = type;
  return Token;
}
var Email = createTokenClass("email", {
  isLink: true,
  toHref() {
    return "mailto:" + this.toString();
  }
});
var Text = createTokenClass("text");
var Nl = createTokenClass("nl");
var Url = createTokenClass("url", {
  isLink: true,
  /**
  	Lowercases relevant parts of the domain and adds the protocol if
  	required. Note that this will not escape unsafe HTML characters in the
  	URL.
  		@param {string} [scheme] default scheme (e.g., 'https')
  	@return {string} the full href
  */
  toHref(scheme2 = defaults2.defaultProtocol) {
    return this.hasProtocol() ? this.v : `${scheme2}://${this.v}`;
  },
  /**
   * Check whether this URL token has a protocol
   * @return {boolean}
   */
  hasProtocol() {
    const tokens = this.tk;
    return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON;
  }
});
var multi = Object.freeze({
  __proto__: null,
  Base: MultiToken,
  Email,
  MultiToken,
  Nl,
  Text,
  Url,
  createTokenClass
});
var makeState = (arg) => new State2(arg);
function init$1({
  groups
}) {
  const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]);
  const qsNonAccepting = [APOSTROPHE, COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN];
  const localpartAccepting = [AMPERSAND, APOSTROPHE, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE];
  const Start = makeState();
  const Localpart = tt2(Start, TILDE);
  ta(Localpart, localpartAccepting, Localpart);
  ta(Localpart, groups.domain, Localpart);
  const Domain = makeState(), Scheme = makeState(), SlashScheme = makeState();
  ta(Start, groups.domain, Domain);
  ta(Start, groups.scheme, Scheme);
  ta(Start, groups.slashscheme, SlashScheme);
  ta(Domain, localpartAccepting, Localpart);
  ta(Domain, groups.domain, Domain);
  const LocalpartAt = tt2(Domain, AT);
  tt2(Localpart, AT, LocalpartAt);
  tt2(Scheme, AT, LocalpartAt);
  tt2(SlashScheme, AT, LocalpartAt);
  const LocalpartDot = tt2(Localpart, DOT);
  ta(LocalpartDot, localpartAccepting, Localpart);
  ta(LocalpartDot, groups.domain, Localpart);
  const EmailDomain = makeState();
  ta(LocalpartAt, groups.domain, EmailDomain);
  ta(EmailDomain, groups.domain, EmailDomain);
  const EmailDomainDot = tt2(EmailDomain, DOT);
  ta(EmailDomainDot, groups.domain, EmailDomain);
  const Email$1 = makeState(Email);
  ta(EmailDomainDot, groups.tld, Email$1);
  ta(EmailDomainDot, groups.utld, Email$1);
  tt2(LocalpartAt, LOCALHOST, Email$1);
  const EmailDomainHyphen = tt2(EmailDomain, HYPHEN);
  tt2(EmailDomainHyphen, HYPHEN, EmailDomainHyphen);
  ta(EmailDomainHyphen, groups.domain, EmailDomain);
  ta(Email$1, groups.domain, EmailDomain);
  tt2(Email$1, DOT, EmailDomainDot);
  tt2(Email$1, HYPHEN, EmailDomainHyphen);
  const EmailColon = tt2(Email$1, COLON);
  ta(EmailColon, groups.numeric, Email);
  const DomainHyphen = tt2(Domain, HYPHEN);
  const DomainDot = tt2(Domain, DOT);
  tt2(DomainHyphen, HYPHEN, DomainHyphen);
  ta(DomainHyphen, groups.domain, Domain);
  ta(DomainDot, localpartAccepting, Localpart);
  ta(DomainDot, groups.domain, Domain);
  const DomainDotTld = makeState(Url);
  ta(DomainDot, groups.tld, DomainDotTld);
  ta(DomainDot, groups.utld, DomainDotTld);
  ta(DomainDotTld, groups.domain, Domain);
  ta(DomainDotTld, localpartAccepting, Localpart);
  tt2(DomainDotTld, DOT, DomainDot);
  tt2(DomainDotTld, HYPHEN, DomainHyphen);
  tt2(DomainDotTld, AT, LocalpartAt);
  const DomainDotTldColon = tt2(DomainDotTld, COLON);
  const DomainDotTldColonPort = makeState(Url);
  ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort);
  const Url$1 = makeState(Url);
  const UrlNonaccept = makeState();
  ta(Url$1, qsAccepting, Url$1);
  ta(Url$1, qsNonAccepting, UrlNonaccept);
  ta(UrlNonaccept, qsAccepting, Url$1);
  ta(UrlNonaccept, qsNonAccepting, UrlNonaccept);
  tt2(DomainDotTld, SLASH, Url$1);
  tt2(DomainDotTldColonPort, SLASH, Url$1);
  const SchemeColon = tt2(Scheme, COLON);
  const SlashSchemeColon = tt2(SlashScheme, COLON);
  const SlashSchemeColonSlash = tt2(SlashSchemeColon, SLASH);
  const UriPrefix = tt2(SlashSchemeColonSlash, SLASH);
  ta(Scheme, groups.domain, Domain);
  tt2(Scheme, DOT, DomainDot);
  tt2(Scheme, HYPHEN, DomainHyphen);
  ta(SlashScheme, groups.domain, Domain);
  tt2(SlashScheme, DOT, DomainDot);
  tt2(SlashScheme, HYPHEN, DomainHyphen);
  ta(SchemeColon, groups.domain, Url$1);
  tt2(SchemeColon, SLASH, Url$1);
  tt2(SchemeColon, QUERY, Url$1);
  ta(UriPrefix, groups.domain, Url$1);
  ta(UriPrefix, qsAccepting, Url$1);
  tt2(UriPrefix, SLASH, Url$1);
  const bracketPairs = [
    [OPENBRACE, CLOSEBRACE],
    // {}
    [OPENBRACKET, CLOSEBRACKET],
    // []
    [OPENPAREN, CLOSEPAREN],
    // ()
    [OPENANGLEBRACKET, CLOSEANGLEBRACKET],
    // <>
    [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN],
    // （）
    [LEFTCORNERBRACKET, RIGHTCORNERBRACKET],
    // 「」
    [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET],
    // 『』
    [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN]
    // ＜＞
  ];
  for (let i3 = 0; i3 < bracketPairs.length; i3++) {
    const [OPEN, CLOSE] = bracketPairs[i3];
    const UrlOpen = tt2(Url$1, OPEN);
    tt2(UrlNonaccept, OPEN, UrlOpen);
    tt2(UrlOpen, CLOSE, Url$1);
    const UrlOpenQ = makeState(Url);
    ta(UrlOpen, qsAccepting, UrlOpenQ);
    const UrlOpenSyms = makeState();
    ta(UrlOpen, qsNonAccepting);
    ta(UrlOpenQ, qsAccepting, UrlOpenQ);
    ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms);
    ta(UrlOpenSyms, qsAccepting, UrlOpenQ);
    ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms);
    tt2(UrlOpenQ, CLOSE, Url$1);
    tt2(UrlOpenSyms, CLOSE, Url$1);
  }
  tt2(Start, LOCALHOST, DomainDotTld);
  tt2(Start, NL, Nl);
  return {
    start: Start,
    tokens: tk
  };
}
function run4(start, input2, tokens) {
  let len = tokens.length;
  let cursor = 0;
  let multis = [];
  let textTokens = [];
  while (cursor < len) {
    let state = start;
    let secondState = null;
    let nextState = null;
    let multiLength = 0;
    let latestAccepting = null;
    let sinceAccepts = -1;
    while (cursor < len && !(secondState = state.go(tokens[cursor].t))) {
      textTokens.push(tokens[cursor++]);
    }
    while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) {
      secondState = null;
      state = nextState;
      if (state.accepts()) {
        sinceAccepts = 0;
        latestAccepting = state;
      } else if (sinceAccepts >= 0) {
        sinceAccepts++;
      }
      cursor++;
      multiLength++;
    }
    if (sinceAccepts < 0) {
      cursor -= multiLength;
      if (cursor < len) {
        textTokens.push(tokens[cursor]);
        cursor++;
      }
    } else {
      if (textTokens.length > 0) {
        multis.push(initMultiToken(Text, input2, textTokens));
        textTokens = [];
      }
      cursor -= sinceAccepts;
      multiLength -= sinceAccepts;
      const Multi = latestAccepting.t;
      const subtokens = tokens.slice(cursor - multiLength, cursor);
      multis.push(initMultiToken(Multi, input2, subtokens));
    }
  }
  if (textTokens.length > 0) {
    multis.push(initMultiToken(Text, input2, textTokens));
  }
  return multis;
}
function initMultiToken(Multi, input2, tokens) {
  const startIdx = tokens[0].s;
  const endIdx = tokens[tokens.length - 1].e;
  const value = input2.slice(startIdx, endIdx);
  return new Multi(value, tokens);
}
var warn3 = typeof console !== "undefined" && console && console.warn || (() => {
});
var warnAdvice = "until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.";
var INIT = {
  scanner: null,
  parser: null,
  tokenQueue: [],
  pluginQueue: [],
  customSchemes: [],
  initialized: false
};
function reset() {
  State2.groups = {};
  INIT.scanner = null;
  INIT.parser = null;
  INIT.tokenQueue = [];
  INIT.pluginQueue = [];
  INIT.customSchemes = [];
  INIT.initialized = false;
  return INIT;
}
function registerCustomProtocol(scheme2, optionalSlashSlash = false) {
  if (INIT.initialized) {
    warn3(`linkifyjs: already initialized - will not register custom scheme "${scheme2}" ${warnAdvice}`);
  }
  if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme2)) {
    throw new Error(`linkifyjs: incorrect scheme format.
1. Must only contain digits, lowercase ASCII letters or "-"
2. Cannot start or end with "-"
3. "-" cannot repeat`);
  }
  INIT.customSchemes.push([scheme2, optionalSlashSlash]);
}
function init() {
  INIT.scanner = init$2(INIT.customSchemes);
  for (let i3 = 0; i3 < INIT.tokenQueue.length; i3++) {
    INIT.tokenQueue[i3][1]({
      scanner: INIT.scanner
    });
  }
  INIT.parser = init$1(INIT.scanner.tokens);
  for (let i3 = 0; i3 < INIT.pluginQueue.length; i3++) {
    INIT.pluginQueue[i3][1]({
      scanner: INIT.scanner,
      parser: INIT.parser
    });
  }
  INIT.initialized = true;
  return INIT;
}
function tokenize(str) {
  if (!INIT.initialized) {
    init();
  }
  return run4(INIT.parser.start, str, run$1(INIT.scanner.start, str));
}
tokenize.scan = run$1;
function find3(str, type = null, opts = null) {
  if (type && typeof type === "object") {
    if (opts) {
      throw Error(`linkifyjs: Invalid link type ${type}; must be a string`);
    }
    opts = type;
    type = null;
  }
  const options2 = new Options(opts);
  const tokens = tokenize(str);
  const filtered = [];
  for (let i3 = 0; i3 < tokens.length; i3++) {
    const token = tokens[i3];
    if (token.isLink && (!type || token.t === type) && options2.check(token)) {
      filtered.push(token.toFormattedObject(options2));
    }
  }
  return filtered;
}

// ../../node_modules/.pnpm/@tiptap+extension-link@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__@tiptap+pm@3.14.0/node_modules/@tiptap/extension-link/dist/index.js
var UNICODE_WHITESPACE_PATTERN = "[\0-   ᠎ -\u2029 　]";
var UNICODE_WHITESPACE_REGEX = new RegExp(UNICODE_WHITESPACE_PATTERN);
var UNICODE_WHITESPACE_REGEX_END = new RegExp(`${UNICODE_WHITESPACE_PATTERN}$`);
var UNICODE_WHITESPACE_REGEX_GLOBAL = new RegExp(UNICODE_WHITESPACE_PATTERN, "g");
function isValidLinkStructure(tokens) {
  if (tokens.length === 1) {
    return tokens[0].isLink;
  }
  if (tokens.length === 3 && tokens[1].isLink) {
    return ["()", "[]"].includes(tokens[0].value + tokens[2].value);
  }
  return false;
}
function autolink2(options2) {
  return new Plugin({
    key: new PluginKey("autolink"),
    appendTransaction: (transactions, oldState, newState) => {
      const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
      const preventAutolink = transactions.some((transaction) => transaction.getMeta("preventAutolink"));
      if (!docChanges || preventAutolink) {
        return;
      }
      const { tr: tr4 } = newState;
      const transform2 = combineTransactionSteps(oldState.doc, [...transactions]);
      const changes = getChangedRanges(transform2);
      changes.forEach(({ newRange }) => {
        const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, (node2) => node2.isTextblock);
        let textBlock;
        let textBeforeWhitespace;
        if (nodesInChangedRanges.length > 1) {
          textBlock = nodesInChangedRanges[0];
          textBeforeWhitespace = newState.doc.textBetween(
            textBlock.pos,
            textBlock.pos + textBlock.node.nodeSize,
            void 0,
            " "
          );
        } else if (nodesInChangedRanges.length) {
          const endText = newState.doc.textBetween(newRange.from, newRange.to, " ", " ");
          if (!UNICODE_WHITESPACE_REGEX_END.test(endText)) {
            return;
          }
          textBlock = nodesInChangedRanges[0];
          textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, void 0, " ");
        }
        if (textBlock && textBeforeWhitespace) {
          const wordsBeforeWhitespace = textBeforeWhitespace.split(UNICODE_WHITESPACE_REGEX).filter(Boolean);
          if (wordsBeforeWhitespace.length <= 0) {
            return false;
          }
          const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1];
          const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace);
          if (!lastWordBeforeSpace) {
            return false;
          }
          const linksBeforeSpace = tokenize(lastWordBeforeSpace).map((t2) => t2.toObject(options2.defaultProtocol));
          if (!isValidLinkStructure(linksBeforeSpace)) {
            return false;
          }
          linksBeforeSpace.filter((link3) => link3.isLink).map((link3) => ({
            ...link3,
            from: lastWordAndBlockOffset + link3.start + 1,
            to: lastWordAndBlockOffset + link3.end + 1
          })).filter((link3) => {
            if (!newState.schema.marks.code) {
              return true;
            }
            return !newState.doc.rangeHasMark(link3.from, link3.to, newState.schema.marks.code);
          }).filter((link3) => options2.validate(link3.value)).filter((link3) => options2.shouldAutoLink(link3.value)).forEach((link3) => {
            if (getMarksBetween(link3.from, link3.to, newState.doc).some((item) => item.mark.type === options2.type)) {
              return;
            }
            tr4.addMark(
              link3.from,
              link3.to,
              options2.type.create({
                href: link3.href
              })
            );
          });
        }
      });
      if (!tr4.steps.length) {
        return;
      }
      return tr4;
    }
  });
}
function clickHandler(options2) {
  return new Plugin({
    key: new PluginKey("handleClickLink"),
    props: {
      handleClick: (view, pos, event) => {
        var _a2, _b;
        if (event.button !== 0) {
          return false;
        }
        if (!view.editable) {
          return false;
        }
        let handled = false;
        if (options2.enableClickSelection) {
          const commandResult = options2.editor.commands.extendMarkRange(options2.type.name);
          handled = commandResult;
        }
        if (options2.openOnClick) {
          let link3 = null;
          if (event.target instanceof HTMLAnchorElement) {
            link3 = event.target;
          } else {
            let a3 = event.target;
            const els = [];
            while (a3.nodeName !== "DIV") {
              els.push(a3);
              a3 = a3.parentNode;
            }
            link3 = els.find((value) => value.nodeName === "A");
          }
          if (!link3) {
            return handled;
          }
          const attrs = getAttributes(view.state, options2.type.name);
          const href = (_a2 = link3 == null ? void 0 : link3.href) != null ? _a2 : attrs.href;
          const target = (_b = link3 == null ? void 0 : link3.target) != null ? _b : attrs.target;
          if (link3 && href) {
            window.open(href, target);
            handled = true;
          }
        }
        return handled;
      }
    }
  });
}
function pasteHandler(options2) {
  return new Plugin({
    key: new PluginKey("handlePasteLink"),
    props: {
      handlePaste: (view, _event, slice2) => {
        const { shouldAutoLink } = options2;
        const { state } = view;
        const { selection } = state;
        const { empty: empty4 } = selection;
        if (empty4) {
          return false;
        }
        let textContent = "";
        slice2.content.forEach((node2) => {
          textContent += node2.textContent;
        });
        const link3 = find3(textContent, { defaultProtocol: options2.defaultProtocol }).find(
          (item) => item.isLink && item.value === textContent
        );
        if (!textContent || !link3 || shouldAutoLink !== void 0 && !shouldAutoLink(link3.href)) {
          return false;
        }
        return options2.editor.commands.setMark(options2.type, {
          href: link3.href
        });
      }
    }
  });
}
function isAllowedUri(uri, protocols) {
  const allowedProtocols = ["http", "https", "ftp", "ftps", "mailto", "tel", "callto", "sms", "cid", "xmpp"];
  if (protocols) {
    protocols.forEach((protocol) => {
      const nextProtocol = typeof protocol === "string" ? protocol : protocol.scheme;
      if (nextProtocol) {
        allowedProtocols.push(nextProtocol);
      }
    });
  }
  return !uri || uri.replace(UNICODE_WHITESPACE_REGEX_GLOBAL, "").match(
    new RegExp(
      // eslint-disable-next-line no-useless-escape
      `^(?:(?:${allowedProtocols.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,
      "i"
    )
  );
}
var Link = Mark2.create({
  name: "link",
  priority: 1e3,
  keepOnSplit: false,
  exitable: true,
  onCreate() {
    if (this.options.validate && !this.options.shouldAutoLink) {
      this.options.shouldAutoLink = this.options.validate;
      console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.");
    }
    this.options.protocols.forEach((protocol) => {
      if (typeof protocol === "string") {
        registerCustomProtocol(protocol);
        return;
      }
      registerCustomProtocol(protocol.scheme, protocol.optionalSlashes);
    });
  },
  onDestroy() {
    reset();
  },
  inclusive() {
    return this.options.autolink;
  },
  addOptions() {
    return {
      openOnClick: true,
      enableClickSelection: false,
      linkOnPaste: true,
      autolink: true,
      protocols: [],
      defaultProtocol: "http",
      HTMLAttributes: {
        target: "_blank",
        rel: "noopener noreferrer nofollow",
        class: null
      },
      isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols),
      validate: (url) => !!url,
      shouldAutoLink: (url) => !!url
    };
  },
  addAttributes() {
    return {
      href: {
        default: null,
        parseHTML(element7) {
          return element7.getAttribute("href");
        }
      },
      target: {
        default: this.options.HTMLAttributes.target
      },
      rel: {
        default: this.options.HTMLAttributes.rel
      },
      class: {
        default: this.options.HTMLAttributes.class
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "a[href]",
        getAttrs: (dom) => {
          const href = dom.getAttribute("href");
          if (!href || !this.options.isAllowedUri(href, {
            defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols),
            protocols: this.options.protocols,
            defaultProtocol: this.options.defaultProtocol
          })) {
            return false;
          }
          return null;
        }
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    if (!this.options.isAllowedUri(HTMLAttributes.href, {
      defaultValidate: (href) => !!isAllowedUri(href, this.options.protocols),
      protocols: this.options.protocols,
      defaultProtocol: this.options.defaultProtocol
    })) {
      return ["a", mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: "" }), 0];
    }
    return ["a", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  markdownTokenName: "link",
  parseMarkdown: (token, helpers) => {
    return helpers.applyMark("link", helpers.parseInline(token.tokens || []), {
      href: token.href,
      title: token.title || null
    });
  },
  renderMarkdown: (node2, h7) => {
    var _a2;
    const href = ((_a2 = node2.attrs) == null ? void 0 : _a2.href) || "";
    const text10 = h7.renderChildren(node2);
    return `[${text10}](${href})`;
  },
  addCommands() {
    return {
      setLink: (attributes) => ({ chain }) => {
        const { href } = attributes;
        if (!this.options.isAllowedUri(href, {
          defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols),
          protocols: this.options.protocols,
          defaultProtocol: this.options.defaultProtocol
        })) {
          return false;
        }
        return chain().setMark(this.name, attributes).setMeta("preventAutolink", true).run();
      },
      toggleLink: (attributes) => ({ chain }) => {
        const { href } = attributes || {};
        if (href && !this.options.isAllowedUri(href, {
          defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols),
          protocols: this.options.protocols,
          defaultProtocol: this.options.defaultProtocol
        })) {
          return false;
        }
        return chain().toggleMark(this.name, attributes, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run();
      },
      unsetLink: () => ({ chain }) => {
        return chain().unsetMark(this.name, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run();
      }
    };
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: (text10) => {
          const foundLinks = [];
          if (text10) {
            const { protocols, defaultProtocol } = this.options;
            const links = find3(text10).filter(
              (item) => item.isLink && this.options.isAllowedUri(item.value, {
                defaultValidate: (href) => !!isAllowedUri(href, protocols),
                protocols,
                defaultProtocol
              })
            );
            if (links.length) {
              links.forEach((link3) => {
                if (!this.options.shouldAutoLink(link3.value)) {
                  return;
                }
                foundLinks.push({
                  text: link3.value,
                  data: {
                    href: link3.href
                  },
                  index: link3.start
                });
              });
            }
          }
          return foundLinks;
        },
        type: this.type,
        getAttributes: (match2) => {
          var _a2;
          return {
            href: (_a2 = match2.data) == null ? void 0 : _a2.href
          };
        }
      })
    ];
  },
  addProseMirrorPlugins() {
    const plugins = [];
    const { protocols, defaultProtocol } = this.options;
    if (this.options.autolink) {
      plugins.push(
        autolink2({
          type: this.type,
          defaultProtocol: this.options.defaultProtocol,
          validate: (url) => this.options.isAllowedUri(url, {
            defaultValidate: (href) => !!isAllowedUri(href, protocols),
            protocols,
            defaultProtocol
          }),
          shouldAutoLink: this.options.shouldAutoLink
        })
      );
    }
    plugins.push(
      clickHandler({
        type: this.type,
        editor: this.editor,
        openOnClick: this.options.openOnClick === "whenNotEditable" ? true : this.options.openOnClick,
        enableClickSelection: this.options.enableClickSelection
      })
    );
    if (this.options.linkOnPaste) {
      plugins.push(
        pasteHandler({
          editor: this.editor,
          defaultProtocol: this.options.defaultProtocol,
          type: this.type,
          shouldAutoLink: this.options.shouldAutoLink
        })
      );
    }
    return plugins;
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-text@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0_/node_modules/@tiptap/extension-text/dist/index.js
var Text2 = Node3.create({
  name: "text",
  group: "inline",
  parseMarkdown: (token) => {
    return {
      type: "text",
      text: token.text || ""
    };
  },
  renderMarkdown: (node2) => node2.text || ""
});

// ../../node_modules/.pnpm/micromark@4.0.2/node_modules/micromark/dev/lib/compile.js
var hasOwnProperty2 = {}.hasOwnProperty;

// ../../node_modules/.pnpm/micromark@4.0.2/node_modules/micromark/dev/lib/initialize/content.js
var content4 = { tokenize: initializeContent };
function initializeContent(effects) {
  const contentStart = effects.attempt(
    this.parser.constructs.contentInitial,
    afterContentStartConstruct,
    paragraphInitial
  );
  let previous3;
  return contentStart;
  function afterContentStartConstruct(code5) {
    ok(
      code5 === codes.eof || markdownLineEnding(code5),
      "expected eol or eof"
    );
    if (code5 === codes.eof) {
      effects.consume(code5);
      return;
    }
    effects.enter(types.lineEnding);
    effects.consume(code5);
    effects.exit(types.lineEnding);
    return factorySpace(effects, contentStart, types.linePrefix);
  }
  function paragraphInitial(code5) {
    ok(
      code5 !== codes.eof && !markdownLineEnding(code5),
      "expected anything other than a line ending or EOF"
    );
    effects.enter(types.paragraph);
    return lineStart(code5);
  }
  function lineStart(code5) {
    const token = effects.enter(types.chunkText, {
      contentType: constants.contentTypeText,
      previous: previous3
    });
    if (previous3) {
      previous3.next = token;
    }
    previous3 = token;
    return data(code5);
  }
  function data(code5) {
    if (code5 === codes.eof) {
      effects.exit(types.chunkText);
      effects.exit(types.paragraph);
      effects.consume(code5);
      return;
    }
    if (markdownLineEnding(code5)) {
      effects.consume(code5);
      effects.exit(types.chunkText);
      return lineStart;
    }
    effects.consume(code5);
    return data;
  }
}

// ../../node_modules/.pnpm/micromark@4.0.2/node_modules/micromark/dev/lib/initialize/document.js
var document2 = { tokenize: initializeDocument };
var containerConstruct = { tokenize: tokenizeContainer };
function initializeDocument(effects) {
  const self2 = this;
  const stack = [];
  let continued = 0;
  let childFlow;
  let childToken;
  let lineStartOffset;
  return start;
  function start(code5) {
    if (continued < stack.length) {
      const item = stack[continued];
      self2.containerState = item[1];
      ok(
        item[0].continuation,
        "expected `continuation` to be defined on container construct"
      );
      return effects.attempt(
        item[0].continuation,
        documentContinue,
        checkNewContainers
      )(code5);
    }
    return checkNewContainers(code5);
  }
  function documentContinue(code5) {
    ok(
      self2.containerState,
      "expected `containerState` to be defined after continuation"
    );
    continued++;
    if (self2.containerState._closeFlow) {
      self2.containerState._closeFlow = void 0;
      if (childFlow) {
        closeFlow();
      }
      const indexBeforeExits = self2.events.length;
      let indexBeforeFlow = indexBeforeExits;
      let point5;
      while (indexBeforeFlow--) {
        if (self2.events[indexBeforeFlow][0] === "exit" && self2.events[indexBeforeFlow][1].type === types.chunkFlow) {
          point5 = self2.events[indexBeforeFlow][1].end;
          break;
        }
      }
      ok(point5, "could not find previous flow chunk");
      exitContainers(continued);
      let index4 = indexBeforeExits;
      while (index4 < self2.events.length) {
        self2.events[index4][1].end = { ...point5 };
        index4++;
      }
      splice(
        self2.events,
        indexBeforeFlow + 1,
        0,
        self2.events.slice(indexBeforeExits)
      );
      self2.events.length = index4;
      return checkNewContainers(code5);
    }
    return start(code5);
  }
  function checkNewContainers(code5) {
    if (continued === stack.length) {
      if (!childFlow) {
        return documentContinued(code5);
      }
      if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) {
        return flowStart(code5);
      }
      self2.interrupt = Boolean(
        childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack
      );
    }
    self2.containerState = {};
    return effects.check(
      containerConstruct,
      thereIsANewContainer,
      thereIsNoNewContainer
    )(code5);
  }
  function thereIsANewContainer(code5) {
    if (childFlow) closeFlow();
    exitContainers(continued);
    return documentContinued(code5);
  }
  function thereIsNoNewContainer(code5) {
    self2.parser.lazy[self2.now().line] = continued !== stack.length;
    lineStartOffset = self2.now().offset;
    return flowStart(code5);
  }
  function documentContinued(code5) {
    self2.containerState = {};
    return effects.attempt(
      containerConstruct,
      containerContinue,
      flowStart
    )(code5);
  }
  function containerContinue(code5) {
    ok(
      self2.currentConstruct,
      "expected `currentConstruct` to be defined on tokenizer"
    );
    ok(
      self2.containerState,
      "expected `containerState` to be defined on tokenizer"
    );
    continued++;
    stack.push([self2.currentConstruct, self2.containerState]);
    return documentContinued(code5);
  }
  function flowStart(code5) {
    if (code5 === codes.eof) {
      if (childFlow) closeFlow();
      exitContainers(0);
      effects.consume(code5);
      return;
    }
    childFlow = childFlow || self2.parser.flow(self2.now());
    effects.enter(types.chunkFlow, {
      _tokenizer: childFlow,
      contentType: constants.contentTypeFlow,
      previous: childToken
    });
    return flowContinue(code5);
  }
  function flowContinue(code5) {
    if (code5 === codes.eof) {
      writeToChild(effects.exit(types.chunkFlow), true);
      exitContainers(0);
      effects.consume(code5);
      return;
    }
    if (markdownLineEnding(code5)) {
      effects.consume(code5);
      writeToChild(effects.exit(types.chunkFlow));
      continued = 0;
      self2.interrupt = void 0;
      return start;
    }
    effects.consume(code5);
    return flowContinue;
  }
  function writeToChild(token, endOfFile) {
    ok(childFlow, "expected `childFlow` to be defined when continuing");
    const stream = self2.sliceStream(token);
    if (endOfFile) stream.push(null);
    token.previous = childToken;
    if (childToken) childToken.next = token;
    childToken = token;
    childFlow.defineSkip(token.start);
    childFlow.write(stream);
    if (self2.parser.lazy[token.start.line]) {
      let index4 = childFlow.events.length;
      while (index4--) {
        if (
          // The token starts before the line ending…
          childFlow.events[index4][1].start.offset < lineStartOffset && // …and either is not ended yet…
          (!childFlow.events[index4][1].end || // …or ends after it.
          childFlow.events[index4][1].end.offset > lineStartOffset)
        ) {
          return;
        }
      }
      const indexBeforeExits = self2.events.length;
      let indexBeforeFlow = indexBeforeExits;
      let seen;
      let point5;
      while (indexBeforeFlow--) {
        if (self2.events[indexBeforeFlow][0] === "exit" && self2.events[indexBeforeFlow][1].type === types.chunkFlow) {
          if (seen) {
            point5 = self2.events[indexBeforeFlow][1].end;
            break;
          }
          seen = true;
        }
      }
      ok(point5, "could not find previous flow chunk");
      exitContainers(continued);
      index4 = indexBeforeExits;
      while (index4 < self2.events.length) {
        self2.events[index4][1].end = { ...point5 };
        index4++;
      }
      splice(
        self2.events,
        indexBeforeFlow + 1,
        0,
        self2.events.slice(indexBeforeExits)
      );
      self2.events.length = index4;
    }
  }
  function exitContainers(size5) {
    let index4 = stack.length;
    while (index4-- > size5) {
      const entry = stack[index4];
      self2.containerState = entry[1];
      ok(
        entry[0].exit,
        "expected `exit` to be defined on container construct"
      );
      entry[0].exit.call(self2, effects);
    }
    stack.length = size5;
  }
  function closeFlow() {
    ok(
      self2.containerState,
      "expected `containerState` to be defined when closing flow"
    );
    ok(childFlow, "expected `childFlow` to be defined when closing it");
    childFlow.write([codes.eof]);
    childToken = void 0;
    childFlow = void 0;
    self2.containerState._closeFlow = void 0;
  }
}
function tokenizeContainer(effects, ok3, nok) {
  ok(
    this.parser.constructs.disable.null,
    "expected `disable.null` to be populated"
  );
  return factorySpace(
    effects,
    effects.attempt(this.parser.constructs.document, ok3, nok),
    types.linePrefix,
    this.parser.constructs.disable.null.includes("codeIndented") ? void 0 : constants.tabSize
  );
}

// ../../node_modules/.pnpm/micromark@4.0.2/node_modules/micromark/dev/lib/initialize/flow.js
var flow2 = { tokenize: initializeFlow };
function initializeFlow(effects) {
  const self2 = this;
  const initial = effects.attempt(
    // Try to parse a blank line.
    blankLine,
    atBlankEnding,
    // Try to parse initial flow (essentially, only code).
    effects.attempt(
      this.parser.constructs.flowInitial,
      afterConstruct,
      factorySpace(
        effects,
        effects.attempt(
          this.parser.constructs.flow,
          afterConstruct,
          effects.attempt(content3, afterConstruct)
        ),
        types.linePrefix
      )
    )
  );
  return initial;
  function atBlankEnding(code5) {
    ok(
      code5 === codes.eof || markdownLineEnding(code5),
      "expected eol or eof"
    );
    if (code5 === codes.eof) {
      effects.consume(code5);
      return;
    }
    effects.enter(types.lineEndingBlank);
    effects.consume(code5);
    effects.exit(types.lineEndingBlank);
    self2.currentConstruct = void 0;
    return initial;
  }
  function afterConstruct(code5) {
    ok(
      code5 === codes.eof || markdownLineEnding(code5),
      "expected eol or eof"
    );
    if (code5 === codes.eof) {
      effects.consume(code5);
      return;
    }
    effects.enter(types.lineEnding);
    effects.consume(code5);
    effects.exit(types.lineEnding);
    self2.currentConstruct = void 0;
    return initial;
  }
}

// ../../node_modules/.pnpm/micromark@4.0.2/node_modules/micromark/dev/lib/initialize/text.js
var resolver = { resolveAll: createResolver() };
var string = initializeFactory("string");
var text6 = initializeFactory("text");
function initializeFactory(field) {
  return {
    resolveAll: createResolver(
      field === "text" ? resolveAllLineSuffixes : void 0
    ),
    tokenize: initializeText
  };
  function initializeText(effects) {
    const self2 = this;
    const constructs2 = this.parser.constructs[field];
    const text10 = effects.attempt(constructs2, start, notText);
    return start;
    function start(code5) {
      return atBreak(code5) ? text10(code5) : notText(code5);
    }
    function notText(code5) {
      if (code5 === codes.eof) {
        effects.consume(code5);
        return;
      }
      effects.enter(types.data);
      effects.consume(code5);
      return data;
    }
    function data(code5) {
      if (atBreak(code5)) {
        effects.exit(types.data);
        return text10(code5);
      }
      effects.consume(code5);
      return data;
    }
    function atBreak(code5) {
      if (code5 === codes.eof) {
        return true;
      }
      const list7 = constructs2[code5];
      let index4 = -1;
      if (list7) {
        ok(Array.isArray(list7), "expected `disable.null` to be populated");
        while (++index4 < list7.length) {
          const item = list7[index4];
          if (!item.previous || item.previous.call(self2, self2.previous)) {
            return true;
          }
        }
      }
      return false;
    }
  }
}
function createResolver(extraResolver) {
  return resolveAllText;
  function resolveAllText(events, context) {
    let index4 = -1;
    let enter2;
    while (++index4 <= events.length) {
      if (enter2 === void 0) {
        if (events[index4] && events[index4][1].type === types.data) {
          enter2 = index4;
          index4++;
        }
      } else if (!events[index4] || events[index4][1].type !== types.data) {
        if (index4 !== enter2 + 2) {
          events[enter2][1].end = events[index4 - 1][1].end;
          events.splice(enter2 + 2, index4 - enter2 - 2);
          index4 = enter2 + 2;
        }
        enter2 = void 0;
      }
    }
    return extraResolver ? extraResolver(events, context) : events;
  }
}
function resolveAllLineSuffixes(events, context) {
  let eventIndex = 0;
  while (++eventIndex <= events.length) {
    if ((eventIndex === events.length || events[eventIndex][1].type === types.lineEnding) && events[eventIndex - 1][1].type === types.data) {
      const data = events[eventIndex - 1][1];
      const chunks = context.sliceStream(data);
      let index4 = chunks.length;
      let bufferIndex = -1;
      let size5 = 0;
      let tabs;
      while (index4--) {
        const chunk = chunks[index4];
        if (typeof chunk === "string") {
          bufferIndex = chunk.length;
          while (chunk.charCodeAt(bufferIndex - 1) === codes.space) {
            size5++;
            bufferIndex--;
          }
          if (bufferIndex) break;
          bufferIndex = -1;
        } else if (chunk === codes.horizontalTab) {
          tabs = true;
          size5++;
        } else if (chunk === codes.virtualSpace) {
        } else {
          index4++;
          break;
        }
      }
      if (context._contentTypeTextTrailing && eventIndex === events.length) {
        size5 = 0;
      }
      if (size5) {
        const token = {
          type: eventIndex === events.length || tabs || size5 < constants.hardBreakPrefixSizeMin ? types.lineSuffix : types.hardBreakTrailing,
          start: {
            _bufferIndex: index4 ? bufferIndex : data.start._bufferIndex + bufferIndex,
            _index: data.start._index + index4,
            line: data.end.line,
            column: data.end.column - size5,
            offset: data.end.offset - size5
          },
          end: { ...data.end }
        };
        data.end = { ...token.start };
        if (data.start.offset === data.end.offset) {
          Object.assign(data, token);
        } else {
          events.splice(
            eventIndex,
            0,
            ["enter", token, context],
            ["exit", token, context]
          );
          eventIndex += 2;
        }
      }
      eventIndex++;
    }
  }
  return events;
}

// ../../node_modules/.pnpm/micromark@4.0.2/node_modules/micromark/dev/lib/constructs.js
var constructs_exports = {};
__export(constructs_exports, {
  attentionMarkers: () => attentionMarkers,
  contentInitial: () => contentInitial,
  disable: () => disable,
  document: () => document3,
  flow: () => flow3,
  flowInitial: () => flowInitial,
  insideSpan: () => insideSpan,
  string: () => string2,
  text: () => text7
});
var document3 = {
  [codes.asterisk]: list5,
  [codes.plusSign]: list5,
  [codes.dash]: list5,
  [codes.digit0]: list5,
  [codes.digit1]: list5,
  [codes.digit2]: list5,
  [codes.digit3]: list5,
  [codes.digit4]: list5,
  [codes.digit5]: list5,
  [codes.digit6]: list5,
  [codes.digit7]: list5,
  [codes.digit8]: list5,
  [codes.digit9]: list5,
  [codes.greaterThan]: blockQuote
};
var contentInitial = {
  [codes.leftSquareBracket]: definition2
};
var flowInitial = {
  [codes.horizontalTab]: codeIndented,
  [codes.virtualSpace]: codeIndented,
  [codes.space]: codeIndented
};
var flow3 = {
  [codes.numberSign]: headingAtx,
  [codes.asterisk]: thematicBreak2,
  [codes.dash]: [setextUnderline, thematicBreak2],
  [codes.lessThan]: htmlFlow,
  [codes.equalsTo]: setextUnderline,
  [codes.underscore]: thematicBreak2,
  [codes.graveAccent]: codeFenced,
  [codes.tilde]: codeFenced
};
var string2 = {
  [codes.ampersand]: characterReference,
  [codes.backslash]: characterEscape
};
var text7 = {
  [codes.carriageReturn]: lineEnding,
  [codes.lineFeed]: lineEnding,
  [codes.carriageReturnLineFeed]: lineEnding,
  [codes.exclamationMark]: labelStartImage,
  [codes.ampersand]: characterReference,
  [codes.asterisk]: attention,
  [codes.lessThan]: [autolink, htmlText],
  [codes.leftSquareBracket]: labelStartLink,
  [codes.backslash]: [hardBreakEscape, characterEscape],
  [codes.rightSquareBracket]: labelEnd,
  [codes.underscore]: attention,
  [codes.graveAccent]: codeText
};
var insideSpan = { null: [attention, resolver] };
var attentionMarkers = { null: [codes.asterisk, codes.underscore] };
var disable = { null: [] };

// ../../node_modules/.pnpm/micromark@4.0.2/node_modules/micromark/dev/lib/create-tokenizer.js
var import_debug = __toESM(require_browser(), 1);
var debug = (0, import_debug.default)("micromark");
function createTokenizer(parser, initialize, from4) {
  let point5 = {
    _bufferIndex: -1,
    _index: 0,
    line: from4 && from4.line || 1,
    column: from4 && from4.column || 1,
    offset: from4 && from4.offset || 0
  };
  const columnStart = {};
  const resolveAllConstructs = [];
  let chunks = [];
  let stack = [];
  let consumed = true;
  const effects = {
    attempt: constructFactory(onsuccessfulconstruct),
    check: constructFactory(onsuccessfulcheck),
    consume,
    enter: enter2,
    exit: exit3,
    interrupt: constructFactory(onsuccessfulcheck, { interrupt: true })
  };
  const context = {
    code: codes.eof,
    containerState: {},
    defineSkip,
    events: [],
    now,
    parser,
    previous: codes.eof,
    sliceSerialize,
    sliceStream,
    write: write2
  };
  let state = initialize.tokenize.call(context, effects);
  let expectedCode;
  if (initialize.resolveAll) {
    resolveAllConstructs.push(initialize);
  }
  return context;
  function write2(slice2) {
    chunks = push(chunks, slice2);
    main();
    if (chunks[chunks.length - 1] !== codes.eof) {
      return [];
    }
    addResult(initialize, 0);
    context.events = resolveAll(resolveAllConstructs, context.events, context);
    return context.events;
  }
  function sliceSerialize(token, expandTabs) {
    return serializeChunks(sliceStream(token), expandTabs);
  }
  function sliceStream(token) {
    return sliceChunks(chunks, token);
  }
  function now() {
    const { _bufferIndex, _index, line, column, offset: offset4 } = point5;
    return { _bufferIndex, _index, line, column, offset: offset4 };
  }
  function defineSkip(value) {
    columnStart[value.line] = value.column;
    accountForPotentialSkip();
    debug("position: define skip: `%j`", point5);
  }
  function main() {
    let chunkIndex;
    while (point5._index < chunks.length) {
      const chunk = chunks[point5._index];
      if (typeof chunk === "string") {
        chunkIndex = point5._index;
        if (point5._bufferIndex < 0) {
          point5._bufferIndex = 0;
        }
        while (point5._index === chunkIndex && point5._bufferIndex < chunk.length) {
          go4(chunk.charCodeAt(point5._bufferIndex));
        }
      } else {
        go4(chunk);
      }
    }
  }
  function go4(code5) {
    ok(consumed === true, "expected character to be consumed");
    consumed = void 0;
    debug("main: passing `%s` to %s", code5, state && state.name);
    expectedCode = code5;
    ok(typeof state === "function", "expected state");
    state = state(code5);
  }
  function consume(code5) {
    ok(code5 === expectedCode, "expected given code to equal expected code");
    debug("consume: `%s`", code5);
    ok(
      consumed === void 0,
      "expected code to not have been consumed: this might be because `return x(code)` instead of `return x` was used"
    );
    ok(
      code5 === null ? context.events.length === 0 || context.events[context.events.length - 1][0] === "exit" : context.events[context.events.length - 1][0] === "enter",
      "expected last token to be open"
    );
    if (markdownLineEnding(code5)) {
      point5.line++;
      point5.column = 1;
      point5.offset += code5 === codes.carriageReturnLineFeed ? 2 : 1;
      accountForPotentialSkip();
      debug("position: after eol: `%j`", point5);
    } else if (code5 !== codes.virtualSpace) {
      point5.column++;
      point5.offset++;
    }
    if (point5._bufferIndex < 0) {
      point5._index++;
    } else {
      point5._bufferIndex++;
      if (point5._bufferIndex === // Points w/ non-negative `_bufferIndex` reference
      // strings.
      /** @type {string} */
      chunks[point5._index].length) {
        point5._bufferIndex = -1;
        point5._index++;
      }
    }
    context.previous = code5;
    consumed = true;
  }
  function enter2(type, fields) {
    const token = fields || {};
    token.type = type;
    token.start = now();
    ok(typeof type === "string", "expected string type");
    ok(type.length > 0, "expected non-empty string");
    debug("enter: `%s`", type);
    context.events.push(["enter", token, context]);
    stack.push(token);
    return token;
  }
  function exit3(type) {
    ok(typeof type === "string", "expected string type");
    ok(type.length > 0, "expected non-empty string");
    const token = stack.pop();
    ok(token, "cannot close w/o open tokens");
    token.end = now();
    ok(type === token.type, "expected exit token to match current token");
    ok(
      !(token.start._index === token.end._index && token.start._bufferIndex === token.end._bufferIndex),
      "expected non-empty token (`" + type + "`)"
    );
    debug("exit: `%s`", token.type);
    context.events.push(["exit", token, context]);
    return token;
  }
  function onsuccessfulconstruct(construct, info) {
    addResult(construct, info.from);
  }
  function onsuccessfulcheck(_2, info) {
    info.restore();
  }
  function constructFactory(onreturn, fields) {
    return hook;
    function hook(constructs2, returnState, bogusState) {
      let listOfConstructs;
      let constructIndex;
      let currentConstruct;
      let info;
      return Array.isArray(constructs2) ? (
        /* c8 ignore next 1 */
        handleListOfConstructs(constructs2)
      ) : "tokenize" in constructs2 ? (
        // Looks like a construct.
        handleListOfConstructs([
          /** @type {Construct} */
          constructs2
        ])
      ) : handleMapOfConstructs(constructs2);
      function handleMapOfConstructs(map7) {
        return start;
        function start(code5) {
          const left = code5 !== null && map7[code5];
          const all9 = code5 !== null && map7.null;
          const list7 = [
            // To do: add more extension tests.
            /* c8 ignore next 2 */
            ...Array.isArray(left) ? left : left ? [left] : [],
            ...Array.isArray(all9) ? all9 : all9 ? [all9] : []
          ];
          return handleListOfConstructs(list7)(code5);
        }
      }
      function handleListOfConstructs(list7) {
        listOfConstructs = list7;
        constructIndex = 0;
        if (list7.length === 0) {
          ok(bogusState, "expected `bogusState` to be given");
          return bogusState;
        }
        return handleConstruct(list7[constructIndex]);
      }
      function handleConstruct(construct) {
        return start;
        function start(code5) {
          info = store();
          currentConstruct = construct;
          if (!construct.partial) {
            context.currentConstruct = construct;
          }
          ok(
            context.parser.constructs.disable.null,
            "expected `disable.null` to be populated"
          );
          if (construct.name && context.parser.constructs.disable.null.includes(construct.name)) {
            return nok(code5);
          }
          return construct.tokenize.call(
            // If we do have fields, create an object w/ `context` as its
            // prototype.
            // This allows a “live binding”, which is needed for `interrupt`.
            fields ? Object.assign(Object.create(context), fields) : context,
            effects,
            ok3,
            nok
          )(code5);
        }
      }
      function ok3(code5) {
        ok(code5 === expectedCode, "expected code");
        consumed = true;
        onreturn(currentConstruct, info);
        return returnState;
      }
      function nok(code5) {
        ok(code5 === expectedCode, "expected code");
        consumed = true;
        info.restore();
        if (++constructIndex < listOfConstructs.length) {
          return handleConstruct(listOfConstructs[constructIndex]);
        }
        return bogusState;
      }
    }
  }
  function addResult(construct, from5) {
    if (construct.resolveAll && !resolveAllConstructs.includes(construct)) {
      resolveAllConstructs.push(construct);
    }
    if (construct.resolve) {
      splice(
        context.events,
        from5,
        context.events.length - from5,
        construct.resolve(context.events.slice(from5), context)
      );
    }
    if (construct.resolveTo) {
      context.events = construct.resolveTo(context.events, context);
    }
    ok(
      construct.partial || context.events.length === 0 || context.events[context.events.length - 1][0] === "exit",
      "expected last token to end"
    );
  }
  function store() {
    const startPoint = now();
    const startPrevious = context.previous;
    const startCurrentConstruct = context.currentConstruct;
    const startEventsIndex = context.events.length;
    const startStack = Array.from(stack);
    return { from: startEventsIndex, restore };
    function restore() {
      point5 = startPoint;
      context.previous = startPrevious;
      context.currentConstruct = startCurrentConstruct;
      context.events.length = startEventsIndex;
      stack = startStack;
      accountForPotentialSkip();
      debug("position: restore: `%j`", point5);
    }
  }
  function accountForPotentialSkip() {
    if (point5.line in columnStart && point5.column < 2) {
      point5.column = columnStart[point5.line];
      point5.offset += columnStart[point5.line] - 1;
    }
  }
}
function sliceChunks(chunks, token) {
  const startIndex = token.start._index;
  const startBufferIndex = token.start._bufferIndex;
  const endIndex = token.end._index;
  const endBufferIndex = token.end._bufferIndex;
  let view;
  if (startIndex === endIndex) {
    ok(endBufferIndex > -1, "expected non-negative end buffer index");
    ok(startBufferIndex > -1, "expected non-negative start buffer index");
    view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)];
  } else {
    view = chunks.slice(startIndex, endIndex);
    if (startBufferIndex > -1) {
      const head2 = view[0];
      if (typeof head2 === "string") {
        view[0] = head2.slice(startBufferIndex);
      } else {
        ok(startBufferIndex === 0, "expected `startBufferIndex` to be `0`");
        view.shift();
      }
    }
    if (endBufferIndex > 0) {
      view.push(chunks[endIndex].slice(0, endBufferIndex));
    }
  }
  return view;
}
function serializeChunks(chunks, expandTabs) {
  let index4 = -1;
  const result = [];
  let atTab;
  while (++index4 < chunks.length) {
    const chunk = chunks[index4];
    let value;
    if (typeof chunk === "string") {
      value = chunk;
    } else
      switch (chunk) {
        case codes.carriageReturn: {
          value = values.cr;
          break;
        }
        case codes.lineFeed: {
          value = values.lf;
          break;
        }
        case codes.carriageReturnLineFeed: {
          value = values.cr + values.lf;
          break;
        }
        case codes.horizontalTab: {
          value = expandTabs ? values.space : values.ht;
          break;
        }
        case codes.virtualSpace: {
          if (!expandTabs && atTab) continue;
          value = values.space;
          break;
        }
        default: {
          ok(typeof chunk === "number", "expected number");
          value = String.fromCharCode(chunk);
        }
      }
    atTab = chunk === codes.horizontalTab;
    result.push(value);
  }
  return result.join("");
}

// ../../node_modules/.pnpm/micromark@4.0.2/node_modules/micromark/dev/lib/parse.js
function parse5(options2) {
  const settings = options2 || {};
  const constructs2 = (
    /** @type {FullNormalizedExtension} */
    combineExtensions([constructs_exports, ...settings.extensions || []])
  );
  const parser = {
    constructs: constructs2,
    content: create11(content4),
    defined: [],
    document: create11(document2),
    flow: create11(flow2),
    lazy: {},
    string: create11(string),
    text: create11(text6)
  };
  return parser;
  function create11(initial) {
    return creator;
    function creator(from4) {
      return createTokenizer(parser, initial, from4);
    }
  }
}

// ../../node_modules/.pnpm/micromark@4.0.2/node_modules/micromark/dev/lib/postprocess.js
function postprocess(events) {
  while (!subtokenize(events)) {
  }
  return events;
}

// ../../node_modules/.pnpm/micromark@4.0.2/node_modules/micromark/dev/lib/preprocess.js
var search2 = /[\0\t\n\r]/g;
function preprocess() {
  let column = 1;
  let buffer = "";
  let start = true;
  let atCarriageReturn;
  return preprocessor;
  function preprocessor(value, encoding, end) {
    const chunks = [];
    let match2;
    let next2;
    let startPosition;
    let endPosition;
    let code5;
    value = buffer + (typeof value === "string" ? value.toString() : new TextDecoder(encoding || void 0).decode(value));
    startPosition = 0;
    buffer = "";
    if (start) {
      if (value.charCodeAt(0) === codes.byteOrderMarker) {
        startPosition++;
      }
      start = void 0;
    }
    while (startPosition < value.length) {
      search2.lastIndex = startPosition;
      match2 = search2.exec(value);
      endPosition = match2 && match2.index !== void 0 ? match2.index : value.length;
      code5 = value.charCodeAt(endPosition);
      if (!match2) {
        buffer = value.slice(startPosition);
        break;
      }
      if (code5 === codes.lf && startPosition === endPosition && atCarriageReturn) {
        chunks.push(codes.carriageReturnLineFeed);
        atCarriageReturn = void 0;
      } else {
        if (atCarriageReturn) {
          chunks.push(codes.carriageReturn);
          atCarriageReturn = void 0;
        }
        if (startPosition < endPosition) {
          chunks.push(value.slice(startPosition, endPosition));
          column += endPosition - startPosition;
        }
        switch (code5) {
          case codes.nul: {
            chunks.push(codes.replacementCharacter);
            column++;
            break;
          }
          case codes.ht: {
            next2 = Math.ceil(column / constants.tabSize) * constants.tabSize;
            chunks.push(codes.horizontalTab);
            while (column++ < next2) chunks.push(codes.virtualSpace);
            break;
          }
          case codes.lf: {
            chunks.push(codes.lineFeed);
            column = 1;
            break;
          }
          default: {
            atCarriageReturn = true;
            column = 1;
          }
        }
      }
      startPosition = endPosition + 1;
    }
    if (end) {
      if (atCarriageReturn) chunks.push(codes.carriageReturn);
      if (buffer) chunks.push(buffer);
      chunks.push(codes.eof);
    }
    return chunks;
  }
}

// ../../node_modules/.pnpm/mdast-util-from-markdown@2.0.2/node_modules/mdast-util-from-markdown/dev/lib/index.js
var own8 = {}.hasOwnProperty;
function fromMarkdown(value, encoding, options2) {
  if (typeof encoding !== "string") {
    options2 = encoding;
    encoding = void 0;
  }
  return compiler(options2)(
    postprocess(
      parse5(options2).document().write(preprocess()(value, encoding, true))
    )
  );
}
function compiler(options2) {
  const config = {
    transforms: [],
    canContainEols: ["emphasis", "fragment", "heading", "paragraph", "strong"],
    enter: {
      autolink: opener(link3),
      autolinkProtocol: onenterdata,
      autolinkEmail: onenterdata,
      atxHeading: opener(heading4),
      blockQuote: opener(blockQuote2),
      characterEscape: onenterdata,
      characterReference: onenterdata,
      codeFenced: opener(codeFlow),
      codeFencedFenceInfo: buffer,
      codeFencedFenceMeta: buffer,
      codeIndented: opener(codeFlow, buffer),
      codeText: opener(codeText2, buffer),
      codeTextData: onenterdata,
      data: onenterdata,
      codeFlowValue: onenterdata,
      definition: opener(definition3),
      definitionDestinationString: buffer,
      definitionLabelString: buffer,
      definitionTitleString: buffer,
      emphasis: opener(emphasis3),
      hardBreakEscape: opener(hardBreak3),
      hardBreakTrailing: opener(hardBreak3),
      htmlFlow: opener(html7, buffer),
      htmlFlowData: onenterdata,
      htmlText: opener(html7, buffer),
      htmlTextData: onenterdata,
      image: opener(image3),
      label: buffer,
      link: opener(link3),
      listItem: opener(listItem3),
      listItemValue: onenterlistitemvalue,
      listOrdered: opener(list7, onenterlistordered),
      listUnordered: opener(list7),
      paragraph: opener(paragraph3),
      reference: onenterreference,
      referenceString: buffer,
      resourceDestinationString: buffer,
      resourceTitleString: buffer,
      setextHeading: opener(heading4),
      strong: opener(strong4),
      thematicBreak: opener(thematicBreak4)
    },
    exit: {
      atxHeading: closer(),
      atxHeadingSequence: onexitatxheadingsequence,
      autolink: closer(),
      autolinkEmail: onexitautolinkemail,
      autolinkProtocol: onexitautolinkprotocol,
      blockQuote: closer(),
      characterEscapeValue: onexitdata,
      characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker,
      characterReferenceMarkerNumeric: onexitcharacterreferencemarker,
      characterReferenceValue: onexitcharacterreferencevalue,
      characterReference: onexitcharacterreference,
      codeFenced: closer(onexitcodefenced),
      codeFencedFence: onexitcodefencedfence,
      codeFencedFenceInfo: onexitcodefencedfenceinfo,
      codeFencedFenceMeta: onexitcodefencedfencemeta,
      codeFlowValue: onexitdata,
      codeIndented: closer(onexitcodeindented),
      codeText: closer(onexitcodetext),
      codeTextData: onexitdata,
      data: onexitdata,
      definition: closer(),
      definitionDestinationString: onexitdefinitiondestinationstring,
      definitionLabelString: onexitdefinitionlabelstring,
      definitionTitleString: onexitdefinitiontitlestring,
      emphasis: closer(),
      hardBreakEscape: closer(onexithardbreak),
      hardBreakTrailing: closer(onexithardbreak),
      htmlFlow: closer(onexithtmlflow),
      htmlFlowData: onexitdata,
      htmlText: closer(onexithtmltext),
      htmlTextData: onexitdata,
      image: closer(onexitimage),
      label: onexitlabel,
      labelText: onexitlabeltext,
      lineEnding: onexitlineending,
      link: closer(onexitlink),
      listItem: closer(),
      listOrdered: closer(),
      listUnordered: closer(),
      paragraph: closer(),
      referenceString: onexitreferencestring,
      resourceDestinationString: onexitresourcedestinationstring,
      resourceTitleString: onexitresourcetitlestring,
      resource: onexitresource,
      setextHeading: closer(onexitsetextheading),
      setextHeadingLineSequence: onexitsetextheadinglinesequence,
      setextHeadingText: onexitsetextheadingtext,
      strong: closer(),
      thematicBreak: closer()
    }
  };
  configure2(config, (options2 || {}).mdastExtensions || []);
  const data = {};
  return compile2;
  function compile2(events) {
    let tree = { type: "root", children: [] };
    const context = {
      stack: [tree],
      tokenStack: [],
      config,
      enter: enter2,
      exit: exit3,
      buffer,
      resume,
      data
    };
    const listStack = [];
    let index4 = -1;
    while (++index4 < events.length) {
      if (events[index4][1].type === types.listOrdered || events[index4][1].type === types.listUnordered) {
        if (events[index4][0] === "enter") {
          listStack.push(index4);
        } else {
          const tail = listStack.pop();
          ok(typeof tail === "number", "expected list ot be open");
          index4 = prepareList(events, tail, index4);
        }
      }
    }
    index4 = -1;
    while (++index4 < events.length) {
      const handler = config[events[index4][0]];
      if (own8.call(handler, events[index4][1].type)) {
        handler[events[index4][1].type].call(
          Object.assign(
            { sliceSerialize: events[index4][2].sliceSerialize },
            context
          ),
          events[index4][1]
        );
      }
    }
    if (context.tokenStack.length > 0) {
      const tail = context.tokenStack[context.tokenStack.length - 1];
      const handler = tail[1] || defaultOnError;
      handler.call(context, void 0, tail[0]);
    }
    tree.position = {
      start: point4(
        events.length > 0 ? events[0][1].start : { line: 1, column: 1, offset: 0 }
      ),
      end: point4(
        events.length > 0 ? events[events.length - 2][1].end : { line: 1, column: 1, offset: 0 }
      )
    };
    index4 = -1;
    while (++index4 < config.transforms.length) {
      tree = config.transforms[index4](tree) || tree;
    }
    return tree;
  }
  function prepareList(events, start, length2) {
    let index4 = start - 1;
    let containerBalance = -1;
    let listSpread = false;
    let listItem4;
    let lineIndex;
    let firstBlankLineIndex;
    let atMarker;
    while (++index4 <= length2) {
      const event = events[index4];
      switch (event[1].type) {
        case types.listUnordered:
        case types.listOrdered:
        case types.blockQuote: {
          if (event[0] === "enter") {
            containerBalance++;
          } else {
            containerBalance--;
          }
          atMarker = void 0;
          break;
        }
        case types.lineEndingBlank: {
          if (event[0] === "enter") {
            if (listItem4 && !atMarker && !containerBalance && !firstBlankLineIndex) {
              firstBlankLineIndex = index4;
            }
            atMarker = void 0;
          }
          break;
        }
        case types.linePrefix:
        case types.listItemValue:
        case types.listItemMarker:
        case types.listItemPrefix:
        case types.listItemPrefixWhitespace: {
          break;
        }
        default: {
          atMarker = void 0;
        }
      }
      if (!containerBalance && event[0] === "enter" && event[1].type === types.listItemPrefix || containerBalance === -1 && event[0] === "exit" && (event[1].type === types.listUnordered || event[1].type === types.listOrdered)) {
        if (listItem4) {
          let tailIndex = index4;
          lineIndex = void 0;
          while (tailIndex--) {
            const tailEvent = events[tailIndex];
            if (tailEvent[1].type === types.lineEnding || tailEvent[1].type === types.lineEndingBlank) {
              if (tailEvent[0] === "exit") continue;
              if (lineIndex) {
                events[lineIndex][1].type = types.lineEndingBlank;
                listSpread = true;
              }
              tailEvent[1].type = types.lineEnding;
              lineIndex = tailIndex;
            } else if (tailEvent[1].type === types.linePrefix || tailEvent[1].type === types.blockQuotePrefix || tailEvent[1].type === types.blockQuotePrefixWhitespace || tailEvent[1].type === types.blockQuoteMarker || tailEvent[1].type === types.listItemIndent) {
            } else {
              break;
            }
          }
          if (firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex)) {
            listItem4._spread = true;
          }
          listItem4.end = Object.assign(
            {},
            lineIndex ? events[lineIndex][1].start : event[1].end
          );
          events.splice(lineIndex || index4, 0, ["exit", listItem4, event[2]]);
          index4++;
          length2++;
        }
        if (event[1].type === types.listItemPrefix) {
          const item = {
            type: "listItem",
            _spread: false,
            start: Object.assign({}, event[1].start),
            // @ts-expect-error: we’ll add `end` in a second.
            end: void 0
          };
          listItem4 = item;
          events.splice(index4, 0, ["enter", item, event[2]]);
          index4++;
          length2++;
          firstBlankLineIndex = void 0;
          atMarker = true;
        }
      }
    }
    events[start][1]._spread = listSpread;
    return length2;
  }
  function opener(create11, and) {
    return open;
    function open(token) {
      enter2.call(this, create11(token), token);
      if (and) and.call(this, token);
    }
  }
  function buffer() {
    this.stack.push({ type: "fragment", children: [] });
  }
  function enter2(node2, token, errorHandler) {
    const parent = this.stack[this.stack.length - 1];
    ok(parent, "expected `parent`");
    ok("children" in parent, "expected `parent`");
    const siblings2 = parent.children;
    siblings2.push(node2);
    this.stack.push(node2);
    this.tokenStack.push([token, errorHandler || void 0]);
    node2.position = {
      start: point4(token.start),
      // @ts-expect-error: `end` will be patched later.
      end: void 0
    };
  }
  function closer(and) {
    return close2;
    function close2(token) {
      if (and) and.call(this, token);
      exit3.call(this, token);
    }
  }
  function exit3(token, onExitError) {
    const node2 = this.stack.pop();
    ok(node2, "expected `node`");
    const open = this.tokenStack.pop();
    if (!open) {
      throw new Error(
        "Cannot close `" + token.type + "` (" + stringifyPosition({ start: token.start, end: token.end }) + "): it’s not open"
      );
    } else if (open[0].type !== token.type) {
      if (onExitError) {
        onExitError.call(this, token, open[0]);
      } else {
        const handler = open[1] || defaultOnError;
        handler.call(this, token, open[0]);
      }
    }
    ok(node2.type !== "fragment", "unexpected fragment `exit`ed");
    ok(node2.position, "expected `position` to be defined");
    node2.position.end = point4(token.end);
  }
  function resume() {
    return toString2(this.stack.pop());
  }
  function onenterlistordered() {
    this.data.expectingFirstListItemValue = true;
  }
  function onenterlistitemvalue(token) {
    if (this.data.expectingFirstListItemValue) {
      const ancestor = this.stack[this.stack.length - 2];
      ok(ancestor, "expected nodes on stack");
      ok(ancestor.type === "list", "expected list on stack");
      ancestor.start = Number.parseInt(
        this.sliceSerialize(token),
        constants.numericBaseDecimal
      );
      this.data.expectingFirstListItemValue = void 0;
    }
  }
  function onexitcodefencedfenceinfo() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "code", "expected code on stack");
    node2.lang = data2;
  }
  function onexitcodefencedfencemeta() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "code", "expected code on stack");
    node2.meta = data2;
  }
  function onexitcodefencedfence() {
    if (this.data.flowCodeInside) return;
    this.buffer();
    this.data.flowCodeInside = true;
  }
  function onexitcodefenced() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "code", "expected code on stack");
    node2.value = data2.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, "");
    this.data.flowCodeInside = void 0;
  }
  function onexitcodeindented() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "code", "expected code on stack");
    node2.value = data2.replace(/(\r?\n|\r)$/g, "");
  }
  function onexitdefinitionlabelstring(token) {
    const label = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "definition", "expected definition on stack");
    node2.label = label;
    node2.identifier = normalizeIdentifier(
      this.sliceSerialize(token)
    ).toLowerCase();
  }
  function onexitdefinitiontitlestring() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "definition", "expected definition on stack");
    node2.title = data2;
  }
  function onexitdefinitiondestinationstring() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "definition", "expected definition on stack");
    node2.url = data2;
  }
  function onexitatxheadingsequence(token) {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "heading", "expected heading on stack");
    if (!node2.depth) {
      const depth = this.sliceSerialize(token).length;
      ok(
        depth === 1 || depth === 2 || depth === 3 || depth === 4 || depth === 5 || depth === 6,
        "expected `depth` between `1` and `6`"
      );
      node2.depth = depth;
    }
  }
  function onexitsetextheadingtext() {
    this.data.setextHeadingSlurpLineEnding = true;
  }
  function onexitsetextheadinglinesequence(token) {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "heading", "expected heading on stack");
    node2.depth = this.sliceSerialize(token).codePointAt(0) === codes.equalsTo ? 1 : 2;
  }
  function onexitsetextheading() {
    this.data.setextHeadingSlurpLineEnding = void 0;
  }
  function onenterdata(token) {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok("children" in node2, "expected parent on stack");
    const siblings2 = node2.children;
    let tail = siblings2[siblings2.length - 1];
    if (!tail || tail.type !== "text") {
      tail = text10();
      tail.position = {
        start: point4(token.start),
        // @ts-expect-error: we’ll add `end` later.
        end: void 0
      };
      siblings2.push(tail);
    }
    this.stack.push(tail);
  }
  function onexitdata(token) {
    const tail = this.stack.pop();
    ok(tail, "expected a `node` to be on the stack");
    ok("value" in tail, "expected a `literal` to be on the stack");
    ok(tail.position, "expected `node` to have an open position");
    tail.value += this.sliceSerialize(token);
    tail.position.end = point4(token.end);
  }
  function onexitlineending(token) {
    const context = this.stack[this.stack.length - 1];
    ok(context, "expected `node`");
    if (this.data.atHardBreak) {
      ok("children" in context, "expected `parent`");
      const tail = context.children[context.children.length - 1];
      ok(tail.position, "expected tail to have a starting position");
      tail.position.end = point4(token.end);
      this.data.atHardBreak = void 0;
      return;
    }
    if (!this.data.setextHeadingSlurpLineEnding && config.canContainEols.includes(context.type)) {
      onenterdata.call(this, token);
      onexitdata.call(this, token);
    }
  }
  function onexithardbreak() {
    this.data.atHardBreak = true;
  }
  function onexithtmlflow() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "html", "expected html on stack");
    node2.value = data2;
  }
  function onexithtmltext() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "html", "expected html on stack");
    node2.value = data2;
  }
  function onexitcodetext() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "inlineCode", "expected inline code on stack");
    node2.value = data2;
  }
  function onexitlink() {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "link", "expected link on stack");
    if (this.data.inReference) {
      const referenceType = this.data.referenceType || "shortcut";
      node2.type += "Reference";
      node2.referenceType = referenceType;
      delete node2.url;
      delete node2.title;
    } else {
      delete node2.identifier;
      delete node2.label;
    }
    this.data.referenceType = void 0;
  }
  function onexitimage() {
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "image", "expected image on stack");
    if (this.data.inReference) {
      const referenceType = this.data.referenceType || "shortcut";
      node2.type += "Reference";
      node2.referenceType = referenceType;
      delete node2.url;
      delete node2.title;
    } else {
      delete node2.identifier;
      delete node2.label;
    }
    this.data.referenceType = void 0;
  }
  function onexitlabeltext(token) {
    const string3 = this.sliceSerialize(token);
    const ancestor = this.stack[this.stack.length - 2];
    ok(ancestor, "expected ancestor on stack");
    ok(
      ancestor.type === "image" || ancestor.type === "link",
      "expected image or link on stack"
    );
    ancestor.label = decodeString(string3);
    ancestor.identifier = normalizeIdentifier(string3).toLowerCase();
  }
  function onexitlabel() {
    const fragment = this.stack[this.stack.length - 1];
    ok(fragment, "expected node on stack");
    ok(fragment.type === "fragment", "expected fragment on stack");
    const value = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(
      node2.type === "image" || node2.type === "link",
      "expected image or link on stack"
    );
    this.data.inReference = true;
    if (node2.type === "link") {
      const children = fragment.children;
      node2.children = children;
    } else {
      node2.alt = value;
    }
  }
  function onexitresourcedestinationstring() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(
      node2.type === "image" || node2.type === "link",
      "expected image or link on stack"
    );
    node2.url = data2;
  }
  function onexitresourcetitlestring() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(
      node2.type === "image" || node2.type === "link",
      "expected image or link on stack"
    );
    node2.title = data2;
  }
  function onexitresource() {
    this.data.inReference = void 0;
  }
  function onenterreference() {
    this.data.referenceType = "collapsed";
  }
  function onexitreferencestring(token) {
    const label = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(
      node2.type === "image" || node2.type === "link",
      "expected image reference or link reference on stack"
    );
    node2.label = label;
    node2.identifier = normalizeIdentifier(
      this.sliceSerialize(token)
    ).toLowerCase();
    this.data.referenceType = "full";
  }
  function onexitcharacterreferencemarker(token) {
    ok(
      token.type === "characterReferenceMarkerNumeric" || token.type === "characterReferenceMarkerHexadecimal"
    );
    this.data.characterReferenceType = token.type;
  }
  function onexitcharacterreferencevalue(token) {
    const data2 = this.sliceSerialize(token);
    const type = this.data.characterReferenceType;
    let value;
    if (type) {
      value = decodeNumericCharacterReference(
        data2,
        type === types.characterReferenceMarkerNumeric ? constants.numericBaseDecimal : constants.numericBaseHexadecimal
      );
      this.data.characterReferenceType = void 0;
    } else {
      const result = decodeNamedCharacterReference(data2);
      ok(result !== false, "expected reference to decode");
      value = result;
    }
    const tail = this.stack[this.stack.length - 1];
    ok(tail, "expected `node`");
    ok("value" in tail, "expected `node.value`");
    tail.value += value;
  }
  function onexitcharacterreference(token) {
    const tail = this.stack.pop();
    ok(tail, "expected `node`");
    ok(tail.position, "expected `node.position`");
    tail.position.end = point4(token.end);
  }
  function onexitautolinkprotocol(token) {
    onexitdata.call(this, token);
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "link", "expected link on stack");
    node2.url = this.sliceSerialize(token);
  }
  function onexitautolinkemail(token) {
    onexitdata.call(this, token);
    const node2 = this.stack[this.stack.length - 1];
    ok(node2, "expected node on stack");
    ok(node2.type === "link", "expected link on stack");
    node2.url = "mailto:" + this.sliceSerialize(token);
  }
  function blockQuote2() {
    return { type: "blockquote", children: [] };
  }
  function codeFlow() {
    return { type: "code", lang: null, meta: null, value: "" };
  }
  function codeText2() {
    return { type: "inlineCode", value: "" };
  }
  function definition3() {
    return {
      type: "definition",
      identifier: "",
      label: null,
      title: null,
      url: ""
    };
  }
  function emphasis3() {
    return { type: "emphasis", children: [] };
  }
  function heading4() {
    return {
      type: "heading",
      // @ts-expect-error `depth` will be set later.
      depth: 0,
      children: []
    };
  }
  function hardBreak3() {
    return { type: "break" };
  }
  function html7() {
    return { type: "html", value: "" };
  }
  function image3() {
    return { type: "image", title: null, url: "", alt: null };
  }
  function link3() {
    return { type: "link", title: null, url: "", children: [] };
  }
  function list7(token) {
    return {
      type: "list",
      ordered: token.type === "listOrdered",
      start: null,
      spread: token._spread,
      children: []
    };
  }
  function listItem3(token) {
    return {
      type: "listItem",
      spread: token._spread,
      checked: null,
      children: []
    };
  }
  function paragraph3() {
    return { type: "paragraph", children: [] };
  }
  function strong4() {
    return { type: "strong", children: [] };
  }
  function text10() {
    return { type: "text", value: "" };
  }
  function thematicBreak4() {
    return { type: "thematicBreak" };
  }
}
function point4(d) {
  return { line: d.line, column: d.column, offset: d.offset };
}
function configure2(combined, extensions) {
  let index4 = -1;
  while (++index4 < extensions.length) {
    const value = extensions[index4];
    if (Array.isArray(value)) {
      configure2(combined, value);
    } else {
      extension(combined, value);
    }
  }
}
function extension(combined, extension2) {
  let key2;
  for (key2 in extension2) {
    if (own8.call(extension2, key2)) {
      switch (key2) {
        case "canContainEols": {
          const right = extension2[key2];
          if (right) {
            combined[key2].push(...right);
          }
          break;
        }
        case "transforms": {
          const right = extension2[key2];
          if (right) {
            combined[key2].push(...right);
          }
          break;
        }
        case "enter":
        case "exit": {
          const right = extension2[key2];
          if (right) {
            Object.assign(combined[key2], right);
          }
          break;
        }
      }
    }
  }
}
function defaultOnError(left, right) {
  if (left) {
    throw new Error(
      "Cannot close `" + left.type + "` (" + stringifyPosition({ start: left.start, end: left.end }) + "): a different token (`" + right.type + "`, " + stringifyPosition({ start: right.start, end: right.end }) + ") is open"
    );
  } else {
    throw new Error(
      "Cannot close document, a token (`" + right.type + "`, " + stringifyPosition({ start: right.start, end: right.end }) + ") is still open"
    );
  }
}

// ../../node_modules/.pnpm/remark-parse@11.0.0/node_modules/remark-parse/lib/index.js
function remarkParse(options2) {
  const self2 = this;
  self2.parser = parser;
  function parser(doc4) {
    return fromMarkdown(doc4, {
      ...self2.data("settings"),
      ...options2,
      // Note: these options are not in the readme.
      // The goal is for them to be set by plugins on `data` instead of being
      // passed by users.
      extensions: self2.data("micromarkExtensions") || [],
      mdastExtensions: self2.data("fromMarkdownExtensions") || []
    });
  }
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/blockquote.js
function blockquote3(state, node2) {
  const result = {
    type: "element",
    tagName: "blockquote",
    properties: {},
    children: state.wrap(state.all(node2), true)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/break.js
function hardBreak2(state, node2) {
  const result = { type: "element", tagName: "br", properties: {}, children: [] };
  state.patch(node2, result);
  return [state.applyData(node2, result), { type: "text", value: "\n" }];
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/code.js
function code4(state, node2) {
  const value = node2.value ? node2.value + "\n" : "";
  const properties = {};
  const language = node2.lang ? node2.lang.split(/\s+/) : [];
  if (language.length > 0) {
    properties.className = ["language-" + language[0]];
  }
  let result = {
    type: "element",
    tagName: "code",
    properties,
    children: [{ type: "text", value }]
  };
  if (node2.meta) {
    result.data = { meta: node2.meta };
  }
  state.patch(node2, result);
  result = state.applyData(node2, result);
  result = { type: "element", tagName: "pre", properties: {}, children: [result] };
  state.patch(node2, result);
  return result;
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/delete.js
function strikethrough(state, node2) {
  const result = {
    type: "element",
    tagName: "del",
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/emphasis.js
function emphasis2(state, node2) {
  const result = {
    type: "element",
    tagName: "em",
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/footnote-reference.js
function footnoteReference2(state, node2) {
  const clobberPrefix = typeof state.options.clobberPrefix === "string" ? state.options.clobberPrefix : "user-content-";
  const id2 = String(node2.identifier).toUpperCase();
  const safeId = normalizeUri(id2.toLowerCase());
  const index4 = state.footnoteOrder.indexOf(id2);
  let counter;
  let reuseCounter = state.footnoteCounts.get(id2);
  if (reuseCounter === void 0) {
    reuseCounter = 0;
    state.footnoteOrder.push(id2);
    counter = state.footnoteOrder.length;
  } else {
    counter = index4 + 1;
  }
  reuseCounter += 1;
  state.footnoteCounts.set(id2, reuseCounter);
  const link3 = {
    type: "element",
    tagName: "a",
    properties: {
      href: "#" + clobberPrefix + "fn-" + safeId,
      id: clobberPrefix + "fnref-" + safeId + (reuseCounter > 1 ? "-" + reuseCounter : ""),
      dataFootnoteRef: true,
      ariaDescribedBy: ["footnote-label"]
    },
    children: [{ type: "text", value: String(counter) }]
  };
  state.patch(node2, link3);
  const sup = {
    type: "element",
    tagName: "sup",
    properties: {},
    children: [link3]
  };
  state.patch(node2, sup);
  return state.applyData(node2, sup);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/heading.js
function heading3(state, node2) {
  const result = {
    type: "element",
    tagName: "h" + node2.depth,
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/html.js
function html4(state, node2) {
  if (state.options.allowDangerousHtml) {
    const result = { type: "raw", value: node2.value };
    state.patch(node2, result);
    return state.applyData(node2, result);
  }
  return void 0;
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/revert.js
function revert(state, node2) {
  const subtype = node2.referenceType;
  let suffix = "]";
  if (subtype === "collapsed") {
    suffix += "[]";
  } else if (subtype === "full") {
    suffix += "[" + (node2.label || node2.identifier) + "]";
  }
  if (node2.type === "imageReference") {
    return [{ type: "text", value: "![" + node2.alt + suffix }];
  }
  const contents = state.all(node2);
  const head2 = contents[0];
  if (head2 && head2.type === "text") {
    head2.value = "[" + head2.value;
  } else {
    contents.unshift({ type: "text", value: "[" });
  }
  const tail = contents[contents.length - 1];
  if (tail && tail.type === "text") {
    tail.value += suffix;
  } else {
    contents.push({ type: "text", value: suffix });
  }
  return contents;
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/image-reference.js
function imageReference2(state, node2) {
  const id2 = String(node2.identifier).toUpperCase();
  const definition3 = state.definitionById.get(id2);
  if (!definition3) {
    return revert(state, node2);
  }
  const properties = { src: normalizeUri(definition3.url || ""), alt: node2.alt };
  if (definition3.title !== null && definition3.title !== void 0) {
    properties.title = definition3.title;
  }
  const result = { type: "element", tagName: "img", properties, children: [] };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/image.js
function image2(state, node2) {
  const properties = { src: normalizeUri(node2.url) };
  if (node2.alt !== null && node2.alt !== void 0) {
    properties.alt = node2.alt;
  }
  if (node2.title !== null && node2.title !== void 0) {
    properties.title = node2.title;
  }
  const result = { type: "element", tagName: "img", properties, children: [] };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/inline-code.js
function inlineCode3(state, node2) {
  const text10 = { type: "text", value: node2.value.replace(/\r?\n|\r/g, " ") };
  state.patch(node2, text10);
  const result = {
    type: "element",
    tagName: "code",
    properties: {},
    children: [text10]
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/link-reference.js
function linkReference2(state, node2) {
  const id2 = String(node2.identifier).toUpperCase();
  const definition3 = state.definitionById.get(id2);
  if (!definition3) {
    return revert(state, node2);
  }
  const properties = { href: normalizeUri(definition3.url || "") };
  if (definition3.title !== null && definition3.title !== void 0) {
    properties.title = definition3.title;
  }
  const result = {
    type: "element",
    tagName: "a",
    properties,
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/link.js
function link2(state, node2) {
  const properties = { href: normalizeUri(node2.url) };
  if (node2.title !== null && node2.title !== void 0) {
    properties.title = node2.title;
  }
  const result = {
    type: "element",
    tagName: "a",
    properties,
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/list-item.js
function listItem2(state, node2, parent) {
  const results = state.all(node2);
  const loose = parent ? listLoose(parent) : listItemLoose(node2);
  const properties = {};
  const children = [];
  if (typeof node2.checked === "boolean") {
    const head2 = results[0];
    let paragraph3;
    if (head2 && head2.type === "element" && head2.tagName === "p") {
      paragraph3 = head2;
    } else {
      paragraph3 = { type: "element", tagName: "p", properties: {}, children: [] };
      results.unshift(paragraph3);
    }
    if (paragraph3.children.length > 0) {
      paragraph3.children.unshift({ type: "text", value: " " });
    }
    paragraph3.children.unshift({
      type: "element",
      tagName: "input",
      properties: { type: "checkbox", checked: node2.checked, disabled: true },
      children: []
    });
    properties.className = ["task-list-item"];
  }
  let index4 = -1;
  while (++index4 < results.length) {
    const child = results[index4];
    if (loose || index4 !== 0 || child.type !== "element" || child.tagName !== "p") {
      children.push({ type: "text", value: "\n" });
    }
    if (child.type === "element" && child.tagName === "p" && !loose) {
      children.push(...child.children);
    } else {
      children.push(child);
    }
  }
  const tail = results[results.length - 1];
  if (tail && (loose || tail.type !== "element" || tail.tagName !== "p")) {
    children.push({ type: "text", value: "\n" });
  }
  const result = { type: "element", tagName: "li", properties, children };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function listLoose(node2) {
  let loose = false;
  if (node2.type === "list") {
    loose = node2.spread || false;
    const children = node2.children;
    let index4 = -1;
    while (!loose && ++index4 < children.length) {
      loose = listItemLoose(children[index4]);
    }
  }
  return loose;
}
function listItemLoose(node2) {
  const spread = node2.spread;
  return spread === null || spread === void 0 ? node2.children.length > 1 : spread;
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/list.js
function list6(state, node2) {
  const properties = {};
  const results = state.all(node2);
  let index4 = -1;
  if (typeof node2.start === "number" && node2.start !== 1) {
    properties.start = node2.start;
  }
  while (++index4 < results.length) {
    const child = results[index4];
    if (child.type === "element" && child.tagName === "li" && child.properties && Array.isArray(child.properties.className) && child.properties.className.includes("task-list-item")) {
      properties.className = ["contains-task-list"];
      break;
    }
  }
  const result = {
    type: "element",
    tagName: node2.ordered ? "ol" : "ul",
    properties,
    children: state.wrap(results, true)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/paragraph.js
function paragraph2(state, node2) {
  const result = {
    type: "element",
    tagName: "p",
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/root.js
function root4(state, node2) {
  const result = { type: "root", children: state.wrap(state.all(node2)) };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/strong.js
function strong3(state, node2) {
  const result = {
    type: "element",
    tagName: "strong",
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/table.js
function table2(state, node2) {
  const rows = state.all(node2);
  const firstRow = rows.shift();
  const tableContent = [];
  if (firstRow) {
    const head2 = {
      type: "element",
      tagName: "thead",
      properties: {},
      children: state.wrap([firstRow], true)
    };
    state.patch(node2.children[0], head2);
    tableContent.push(head2);
  }
  if (rows.length > 0) {
    const body3 = {
      type: "element",
      tagName: "tbody",
      properties: {},
      children: state.wrap(rows, true)
    };
    const start = pointStart(node2.children[1]);
    const end = pointEnd(node2.children[node2.children.length - 1]);
    if (start && end) body3.position = { start, end };
    tableContent.push(body3);
  }
  const result = {
    type: "element",
    tagName: "table",
    properties: {},
    children: state.wrap(tableContent, true)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/table-row.js
function tableRow2(state, node2, parent) {
  const siblings2 = parent ? parent.children : void 0;
  const rowIndex = siblings2 ? siblings2.indexOf(node2) : 1;
  const tagName = rowIndex === 0 ? "th" : "td";
  const align = parent && parent.type === "table" ? parent.align : void 0;
  const length2 = align ? align.length : node2.children.length;
  let cellIndex = -1;
  const cells2 = [];
  while (++cellIndex < length2) {
    const cell2 = node2.children[cellIndex];
    const properties = {};
    const alignValue = align ? align[cellIndex] : void 0;
    if (alignValue) {
      properties.align = alignValue;
    }
    let result2 = { type: "element", tagName, properties, children: [] };
    if (cell2) {
      result2.children = state.all(cell2);
      state.patch(cell2, result2);
      result2 = state.applyData(cell2, result2);
    }
    cells2.push(result2);
  }
  const result = {
    type: "element",
    tagName: "tr",
    properties: {},
    children: state.wrap(cells2, true)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/table-cell.js
function tableCell2(state, node2) {
  const result = {
    type: "element",
    tagName: "td",
    // Assume body cell.
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/trim-lines@3.0.1/node_modules/trim-lines/index.js
var tab = 9;
var space = 32;
function trimLines(value) {
  const source = String(value);
  const search3 = /\r?\n|\r/g;
  let match2 = search3.exec(source);
  let last2 = 0;
  const lines = [];
  while (match2) {
    lines.push(
      trimLine(source.slice(last2, match2.index), last2 > 0, true),
      match2[0]
    );
    last2 = match2.index + match2[0].length;
    match2 = search3.exec(source);
  }
  lines.push(trimLine(source.slice(last2), last2 > 0, false));
  return lines.join("");
}
function trimLine(value, start, end) {
  let startIndex = 0;
  let endIndex = value.length;
  if (start) {
    let code5 = value.codePointAt(startIndex);
    while (code5 === tab || code5 === space) {
      startIndex++;
      code5 = value.codePointAt(startIndex);
    }
  }
  if (end) {
    let code5 = value.codePointAt(endIndex - 1);
    while (code5 === tab || code5 === space) {
      endIndex--;
      code5 = value.codePointAt(endIndex - 1);
    }
  }
  return endIndex > startIndex ? value.slice(startIndex, endIndex) : "";
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/text.js
function text8(state, node2) {
  const result = { type: "text", value: trimLines(String(node2.value)) };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/thematic-break.js
function thematicBreak3(state, node2) {
  const result = {
    type: "element",
    tagName: "hr",
    properties: {},
    children: []
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/handlers/index.js
var handlers3 = {
  blockquote: blockquote3,
  break: hardBreak2,
  code: code4,
  delete: strikethrough,
  emphasis: emphasis2,
  footnoteReference: footnoteReference2,
  heading: heading3,
  html: html4,
  imageReference: imageReference2,
  image: image2,
  inlineCode: inlineCode3,
  linkReference: linkReference2,
  link: link2,
  listItem: listItem2,
  list: list6,
  paragraph: paragraph2,
  // @ts-expect-error: root is different, but hard to type.
  root: root4,
  strong: strong3,
  table: table2,
  tableCell: tableCell2,
  tableRow: tableRow2,
  text: text8,
  thematicBreak: thematicBreak3,
  toml: ignore2,
  yaml: ignore2,
  definition: ignore2,
  footnoteDefinition: ignore2
};
function ignore2() {
  return void 0;
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/footer.js
function defaultFootnoteBackContent(_2, rereferenceIndex) {
  const result = [{ type: "text", value: "↩" }];
  if (rereferenceIndex > 1) {
    result.push({
      type: "element",
      tagName: "sup",
      properties: {},
      children: [{ type: "text", value: String(rereferenceIndex) }]
    });
  }
  return result;
}
function defaultFootnoteBackLabel(referenceIndex, rereferenceIndex) {
  return "Back to reference " + (referenceIndex + 1) + (rereferenceIndex > 1 ? "-" + rereferenceIndex : "");
}
function footer(state) {
  const clobberPrefix = typeof state.options.clobberPrefix === "string" ? state.options.clobberPrefix : "user-content-";
  const footnoteBackContent = state.options.footnoteBackContent || defaultFootnoteBackContent;
  const footnoteBackLabel = state.options.footnoteBackLabel || defaultFootnoteBackLabel;
  const footnoteLabel = state.options.footnoteLabel || "Footnotes";
  const footnoteLabelTagName = state.options.footnoteLabelTagName || "h2";
  const footnoteLabelProperties = state.options.footnoteLabelProperties || {
    className: ["sr-only"]
  };
  const listItems = [];
  let referenceIndex = -1;
  while (++referenceIndex < state.footnoteOrder.length) {
    const definition3 = state.footnoteById.get(
      state.footnoteOrder[referenceIndex]
    );
    if (!definition3) {
      continue;
    }
    const content5 = state.all(definition3);
    const id2 = String(definition3.identifier).toUpperCase();
    const safeId = normalizeUri(id2.toLowerCase());
    let rereferenceIndex = 0;
    const backReferences = [];
    const counts = state.footnoteCounts.get(id2);
    while (counts !== void 0 && ++rereferenceIndex <= counts) {
      if (backReferences.length > 0) {
        backReferences.push({ type: "text", value: " " });
      }
      let children = typeof footnoteBackContent === "string" ? footnoteBackContent : footnoteBackContent(referenceIndex, rereferenceIndex);
      if (typeof children === "string") {
        children = { type: "text", value: children };
      }
      backReferences.push({
        type: "element",
        tagName: "a",
        properties: {
          href: "#" + clobberPrefix + "fnref-" + safeId + (rereferenceIndex > 1 ? "-" + rereferenceIndex : ""),
          dataFootnoteBackref: "",
          ariaLabel: typeof footnoteBackLabel === "string" ? footnoteBackLabel : footnoteBackLabel(referenceIndex, rereferenceIndex),
          className: ["data-footnote-backref"]
        },
        children: Array.isArray(children) ? children : [children]
      });
    }
    const tail = content5[content5.length - 1];
    if (tail && tail.type === "element" && tail.tagName === "p") {
      const tailTail = tail.children[tail.children.length - 1];
      if (tailTail && tailTail.type === "text") {
        tailTail.value += " ";
      } else {
        tail.children.push({ type: "text", value: " " });
      }
      tail.children.push(...backReferences);
    } else {
      content5.push(...backReferences);
    }
    const listItem3 = {
      type: "element",
      tagName: "li",
      properties: { id: clobberPrefix + "fn-" + safeId },
      children: state.wrap(content5, true)
    };
    state.patch(definition3, listItem3);
    listItems.push(listItem3);
  }
  if (listItems.length === 0) {
    return;
  }
  return {
    type: "element",
    tagName: "section",
    properties: { dataFootnotes: true, className: ["footnotes"] },
    children: [
      {
        type: "element",
        tagName: footnoteLabelTagName,
        properties: {
          ...esm_default(footnoteLabelProperties),
          id: "footnote-label"
        },
        children: [{ type: "text", value: footnoteLabel }]
      },
      { type: "text", value: "\n" },
      {
        type: "element",
        tagName: "ol",
        properties: {},
        children: state.wrap(listItems, true)
      },
      { type: "text", value: "\n" }
    ]
  };
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/state.js
var own9 = {}.hasOwnProperty;
var emptyOptions6 = {};
function createState2(tree, options2) {
  const settings = options2 || emptyOptions6;
  const definitionById = /* @__PURE__ */ new Map();
  const footnoteById = /* @__PURE__ */ new Map();
  const footnoteCounts = /* @__PURE__ */ new Map();
  const handlers4 = { ...handlers3, ...settings.handlers };
  const state = {
    all: all9,
    applyData,
    definitionById,
    footnoteById,
    footnoteCounts,
    footnoteOrder: [],
    handlers: handlers4,
    one: one6,
    options: settings,
    patch: patch3,
    wrap: wrap4
  };
  visit(tree, function(node2) {
    if (node2.type === "definition" || node2.type === "footnoteDefinition") {
      const map7 = node2.type === "definition" ? definitionById : footnoteById;
      const id2 = String(node2.identifier).toUpperCase();
      if (!map7.has(id2)) {
        map7.set(id2, node2);
      }
    }
  });
  return state;
  function one6(node2, parent) {
    const type = node2.type;
    const handle4 = state.handlers[type];
    if (own9.call(state.handlers, type) && handle4) {
      return handle4(state, node2, parent);
    }
    if (state.options.passThrough && state.options.passThrough.includes(type)) {
      if ("children" in node2) {
        const { children, ...shallow2 } = node2;
        const result = esm_default(shallow2);
        result.children = state.all(node2);
        return result;
      }
      return esm_default(node2);
    }
    const unknown3 = state.options.unknownHandler || defaultUnknownHandler;
    return unknown3(state, node2, parent);
  }
  function all9(parent) {
    const values2 = [];
    if ("children" in parent) {
      const nodes = parent.children;
      let index4 = -1;
      while (++index4 < nodes.length) {
        const result = state.one(nodes[index4], parent);
        if (result) {
          if (index4 && nodes[index4 - 1].type === "break") {
            if (!Array.isArray(result) && result.type === "text") {
              result.value = trimMarkdownSpaceStart(result.value);
            }
            if (!Array.isArray(result) && result.type === "element") {
              const head2 = result.children[0];
              if (head2 && head2.type === "text") {
                head2.value = trimMarkdownSpaceStart(head2.value);
              }
            }
          }
          if (Array.isArray(result)) {
            values2.push(...result);
          } else {
            values2.push(result);
          }
        }
      }
    }
    return values2;
  }
}
function patch3(from4, to2) {
  if (from4.position) to2.position = position3(from4);
}
function applyData(from4, to2) {
  let result = to2;
  if (from4 && from4.data) {
    const hName = from4.data.hName;
    const hChildren = from4.data.hChildren;
    const hProperties = from4.data.hProperties;
    if (typeof hName === "string") {
      if (result.type === "element") {
        result.tagName = hName;
      } else {
        const children = "children" in result ? result.children : [result];
        result = { type: "element", tagName: hName, properties: {}, children };
      }
    }
    if (result.type === "element" && hProperties) {
      Object.assign(result.properties, esm_default(hProperties));
    }
    if ("children" in result && result.children && hChildren !== null && hChildren !== void 0) {
      result.children = hChildren;
    }
  }
  return result;
}
function defaultUnknownHandler(state, node2) {
  const data = node2.data || {};
  const result = "value" in node2 && !(own9.call(data, "hProperties") || own9.call(data, "hChildren")) ? { type: "text", value: node2.value } : {
    type: "element",
    tagName: "div",
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function wrap4(nodes, loose) {
  const result = [];
  let index4 = -1;
  if (loose) {
    result.push({ type: "text", value: "\n" });
  }
  while (++index4 < nodes.length) {
    if (index4) result.push({ type: "text", value: "\n" });
    result.push(nodes[index4]);
  }
  if (loose && nodes.length > 0) {
    result.push({ type: "text", value: "\n" });
  }
  return result;
}
function trimMarkdownSpaceStart(value) {
  let index4 = 0;
  let code5 = value.charCodeAt(index4);
  while (code5 === 9 || code5 === 32) {
    index4++;
    code5 = value.charCodeAt(index4);
  }
  return value.slice(index4);
}

// ../../node_modules/.pnpm/mdast-util-to-hast@13.2.1/node_modules/mdast-util-to-hast/lib/index.js
function toHast(tree, options2) {
  const state = createState2(tree, options2);
  const node2 = state.one(tree, void 0);
  const foot = footer(state);
  const result = Array.isArray(node2) ? { type: "root", children: node2 } : node2 || { type: "root", children: [] };
  if (foot) {
    ok("children" in result);
    result.children.push({ type: "text", value: "\n" }, foot);
  }
  return result;
}

// ../../node_modules/.pnpm/remark-rehype@11.1.2/node_modules/remark-rehype/lib/index.js
function remarkRehype(destination, options2) {
  if (destination && "run" in destination) {
    return async function(tree, file) {
      const hastTree = (
        /** @type {HastRoot} */
        toHast(tree, { file, ...options2 })
      );
      await destination.run(hastTree, file);
    };
  }
  return function(tree, file) {
    return (
      /** @type {HastRoot} */
      toHast(tree, { file, ...destination || options2 })
    );
  };
}

// ../../node_modules/.pnpm/html-void-elements@3.0.0/node_modules/html-void-elements/index.js
var htmlVoidElements = [
  "area",
  "base",
  "basefont",
  "bgsound",
  "br",
  "col",
  "command",
  "embed",
  "frame",
  "hr",
  "image",
  "img",
  "input",
  "keygen",
  "link",
  "meta",
  "param",
  "source",
  "track",
  "wbr"
];

// ../../node_modules/.pnpm/stringify-entities@4.0.4/node_modules/stringify-entities/lib/core.js
var defaultSubsetRegex = /["&'<>`]/g;
var surrogatePairsRegex = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
var controlCharactersRegex = (
  // eslint-disable-next-line no-control-regex, unicorn/no-hex-escape
  /[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g
);
var regexEscapeRegex = /[|\\{}()[\]^$+*?.]/g;
var subsetToRegexCache = /* @__PURE__ */ new WeakMap();
function core(value, options2) {
  value = value.replace(
    options2.subset ? charactersToExpressionCached(options2.subset) : defaultSubsetRegex,
    basic2
  );
  if (options2.subset || options2.escapeOnly) {
    return value;
  }
  return value.replace(surrogatePairsRegex, surrogate).replace(controlCharactersRegex, basic2);
  function surrogate(pair, index4, all9) {
    return options2.format(
      (pair.charCodeAt(0) - 55296) * 1024 + pair.charCodeAt(1) - 56320 + 65536,
      all9.charCodeAt(index4 + 2),
      options2
    );
  }
  function basic2(character, index4, all9) {
    return options2.format(
      character.charCodeAt(0),
      all9.charCodeAt(index4 + 1),
      options2
    );
  }
}
function charactersToExpressionCached(subset) {
  let cached = subsetToRegexCache.get(subset);
  if (!cached) {
    cached = charactersToExpression(subset);
    subsetToRegexCache.set(subset, cached);
  }
  return cached;
}
function charactersToExpression(subset) {
  const groups = [];
  let index4 = -1;
  while (++index4 < subset.length) {
    groups.push(subset[index4].replace(regexEscapeRegex, "\\$&"));
  }
  return new RegExp("(?:" + groups.join("|") + ")", "g");
}

// ../../node_modules/.pnpm/stringify-entities@4.0.4/node_modules/stringify-entities/lib/util/to-hexadecimal.js
var hexadecimalRegex = /[\dA-Fa-f]/;
function toHexadecimal(code5, next2, omit) {
  const value = "&#x" + code5.toString(16).toUpperCase();
  return omit && next2 && !hexadecimalRegex.test(String.fromCharCode(next2)) ? value : value + ";";
}

// ../../node_modules/.pnpm/stringify-entities@4.0.4/node_modules/stringify-entities/lib/util/to-decimal.js
var decimalRegex = /\d/;
function toDecimal(code5, next2, omit) {
  const value = "&#" + String(code5);
  return omit && next2 && !decimalRegex.test(String.fromCharCode(next2)) ? value : value + ";";
}

// ../../node_modules/.pnpm/character-entities-legacy@3.0.0/node_modules/character-entities-legacy/index.js
var characterEntitiesLegacy = [
  "AElig",
  "AMP",
  "Aacute",
  "Acirc",
  "Agrave",
  "Aring",
  "Atilde",
  "Auml",
  "COPY",
  "Ccedil",
  "ETH",
  "Eacute",
  "Ecirc",
  "Egrave",
  "Euml",
  "GT",
  "Iacute",
  "Icirc",
  "Igrave",
  "Iuml",
  "LT",
  "Ntilde",
  "Oacute",
  "Ocirc",
  "Ograve",
  "Oslash",
  "Otilde",
  "Ouml",
  "QUOT",
  "REG",
  "THORN",
  "Uacute",
  "Ucirc",
  "Ugrave",
  "Uuml",
  "Yacute",
  "aacute",
  "acirc",
  "acute",
  "aelig",
  "agrave",
  "amp",
  "aring",
  "atilde",
  "auml",
  "brvbar",
  "ccedil",
  "cedil",
  "cent",
  "copy",
  "curren",
  "deg",
  "divide",
  "eacute",
  "ecirc",
  "egrave",
  "eth",
  "euml",
  "frac12",
  "frac14",
  "frac34",
  "gt",
  "iacute",
  "icirc",
  "iexcl",
  "igrave",
  "iquest",
  "iuml",
  "laquo",
  "lt",
  "macr",
  "micro",
  "middot",
  "nbsp",
  "not",
  "ntilde",
  "oacute",
  "ocirc",
  "ograve",
  "ordf",
  "ordm",
  "oslash",
  "otilde",
  "ouml",
  "para",
  "plusmn",
  "pound",
  "quot",
  "raquo",
  "reg",
  "sect",
  "shy",
  "sup1",
  "sup2",
  "sup3",
  "szlig",
  "thorn",
  "times",
  "uacute",
  "ucirc",
  "ugrave",
  "uml",
  "uuml",
  "yacute",
  "yen",
  "yuml"
];

// ../../node_modules/.pnpm/character-entities-html4@2.1.0/node_modules/character-entities-html4/index.js
var characterEntitiesHtml4 = {
  nbsp: " ",
  iexcl: "¡",
  cent: "¢",
  pound: "£",
  curren: "¤",
  yen: "¥",
  brvbar: "¦",
  sect: "§",
  uml: "¨",
  copy: "©",
  ordf: "ª",
  laquo: "«",
  not: "¬",
  shy: "­",
  reg: "®",
  macr: "¯",
  deg: "°",
  plusmn: "±",
  sup2: "²",
  sup3: "³",
  acute: "´",
  micro: "µ",
  para: "¶",
  middot: "·",
  cedil: "¸",
  sup1: "¹",
  ordm: "º",
  raquo: "»",
  frac14: "¼",
  frac12: "½",
  frac34: "¾",
  iquest: "¿",
  Agrave: "À",
  Aacute: "Á",
  Acirc: "Â",
  Atilde: "Ã",
  Auml: "Ä",
  Aring: "Å",
  AElig: "Æ",
  Ccedil: "Ç",
  Egrave: "È",
  Eacute: "É",
  Ecirc: "Ê",
  Euml: "Ë",
  Igrave: "Ì",
  Iacute: "Í",
  Icirc: "Î",
  Iuml: "Ï",
  ETH: "Ð",
  Ntilde: "Ñ",
  Ograve: "Ò",
  Oacute: "Ó",
  Ocirc: "Ô",
  Otilde: "Õ",
  Ouml: "Ö",
  times: "×",
  Oslash: "Ø",
  Ugrave: "Ù",
  Uacute: "Ú",
  Ucirc: "Û",
  Uuml: "Ü",
  Yacute: "Ý",
  THORN: "Þ",
  szlig: "ß",
  agrave: "à",
  aacute: "á",
  acirc: "â",
  atilde: "ã",
  auml: "ä",
  aring: "å",
  aelig: "æ",
  ccedil: "ç",
  egrave: "è",
  eacute: "é",
  ecirc: "ê",
  euml: "ë",
  igrave: "ì",
  iacute: "í",
  icirc: "î",
  iuml: "ï",
  eth: "ð",
  ntilde: "ñ",
  ograve: "ò",
  oacute: "ó",
  ocirc: "ô",
  otilde: "õ",
  ouml: "ö",
  divide: "÷",
  oslash: "ø",
  ugrave: "ù",
  uacute: "ú",
  ucirc: "û",
  uuml: "ü",
  yacute: "ý",
  thorn: "þ",
  yuml: "ÿ",
  fnof: "ƒ",
  Alpha: "Α",
  Beta: "Β",
  Gamma: "Γ",
  Delta: "Δ",
  Epsilon: "Ε",
  Zeta: "Ζ",
  Eta: "Η",
  Theta: "Θ",
  Iota: "Ι",
  Kappa: "Κ",
  Lambda: "Λ",
  Mu: "Μ",
  Nu: "Ν",
  Xi: "Ξ",
  Omicron: "Ο",
  Pi: "Π",
  Rho: "Ρ",
  Sigma: "Σ",
  Tau: "Τ",
  Upsilon: "Υ",
  Phi: "Φ",
  Chi: "Χ",
  Psi: "Ψ",
  Omega: "Ω",
  alpha: "α",
  beta: "β",
  gamma: "γ",
  delta: "δ",
  epsilon: "ε",
  zeta: "ζ",
  eta: "η",
  theta: "θ",
  iota: "ι",
  kappa: "κ",
  lambda: "λ",
  mu: "μ",
  nu: "ν",
  xi: "ξ",
  omicron: "ο",
  pi: "π",
  rho: "ρ",
  sigmaf: "ς",
  sigma: "σ",
  tau: "τ",
  upsilon: "υ",
  phi: "φ",
  chi: "χ",
  psi: "ψ",
  omega: "ω",
  thetasym: "ϑ",
  upsih: "ϒ",
  piv: "ϖ",
  bull: "•",
  hellip: "…",
  prime: "′",
  Prime: "″",
  oline: "‾",
  frasl: "⁄",
  weierp: "℘",
  image: "ℑ",
  real: "ℜ",
  trade: "™",
  alefsym: "ℵ",
  larr: "←",
  uarr: "↑",
  rarr: "→",
  darr: "↓",
  harr: "↔",
  crarr: "↵",
  lArr: "⇐",
  uArr: "⇑",
  rArr: "⇒",
  dArr: "⇓",
  hArr: "⇔",
  forall: "∀",
  part: "∂",
  exist: "∃",
  empty: "∅",
  nabla: "∇",
  isin: "∈",
  notin: "∉",
  ni: "∋",
  prod: "∏",
  sum: "∑",
  minus: "−",
  lowast: "∗",
  radic: "√",
  prop: "∝",
  infin: "∞",
  ang: "∠",
  and: "∧",
  or: "∨",
  cap: "∩",
  cup: "∪",
  int: "∫",
  there4: "∴",
  sim: "∼",
  cong: "≅",
  asymp: "≈",
  ne: "≠",
  equiv: "≡",
  le: "≤",
  ge: "≥",
  sub: "⊂",
  sup: "⊃",
  nsub: "⊄",
  sube: "⊆",
  supe: "⊇",
  oplus: "⊕",
  otimes: "⊗",
  perp: "⊥",
  sdot: "⋅",
  lceil: "⌈",
  rceil: "⌉",
  lfloor: "⌊",
  rfloor: "⌋",
  lang: "〈",
  rang: "〉",
  loz: "◊",
  spades: "♠",
  clubs: "♣",
  hearts: "♥",
  diams: "♦",
  quot: '"',
  amp: "&",
  lt: "<",
  gt: ">",
  OElig: "Œ",
  oelig: "œ",
  Scaron: "Š",
  scaron: "š",
  Yuml: "Ÿ",
  circ: "ˆ",
  tilde: "˜",
  ensp: " ",
  emsp: " ",
  thinsp: " ",
  zwnj: "‌",
  zwj: "‍",
  lrm: "‎",
  rlm: "‏",
  ndash: "–",
  mdash: "—",
  lsquo: "‘",
  rsquo: "’",
  sbquo: "‚",
  ldquo: "“",
  rdquo: "”",
  bdquo: "„",
  dagger: "†",
  Dagger: "‡",
  permil: "‰",
  lsaquo: "‹",
  rsaquo: "›",
  euro: "€"
};

// ../../node_modules/.pnpm/stringify-entities@4.0.4/node_modules/stringify-entities/lib/constant/dangerous.js
var dangerous = [
  "cent",
  "copy",
  "divide",
  "gt",
  "lt",
  "not",
  "para",
  "times"
];

// ../../node_modules/.pnpm/stringify-entities@4.0.4/node_modules/stringify-entities/lib/util/to-named.js
var own10 = {}.hasOwnProperty;
var characters = {};
var key;
for (key in characterEntitiesHtml4) {
  if (own10.call(characterEntitiesHtml4, key)) {
    characters[characterEntitiesHtml4[key]] = key;
  }
}
var notAlphanumericRegex = /[^\dA-Za-z]/;
function toNamed(code5, next2, omit, attribute) {
  const character = String.fromCharCode(code5);
  if (own10.call(characters, character)) {
    const name = characters[character];
    const value = "&" + name;
    if (omit && characterEntitiesLegacy.includes(name) && !dangerous.includes(name) && (!attribute || next2 && next2 !== 61 && notAlphanumericRegex.test(String.fromCharCode(next2)))) {
      return value;
    }
    return value + ";";
  }
  return "";
}

// ../../node_modules/.pnpm/stringify-entities@4.0.4/node_modules/stringify-entities/lib/util/format-smart.js
function formatSmart(code5, next2, options2) {
  let numeric2 = toHexadecimal(code5, next2, options2.omitOptionalSemicolons);
  let named;
  if (options2.useNamedReferences || options2.useShortestReferences) {
    named = toNamed(
      code5,
      next2,
      options2.omitOptionalSemicolons,
      options2.attribute
    );
  }
  if ((options2.useShortestReferences || !named) && options2.useShortestReferences) {
    const decimal = toDecimal(code5, next2, options2.omitOptionalSemicolons);
    if (decimal.length < numeric2.length) {
      numeric2 = decimal;
    }
  }
  return named && (!options2.useShortestReferences || named.length < numeric2.length) ? named : numeric2;
}

// ../../node_modules/.pnpm/stringify-entities@4.0.4/node_modules/stringify-entities/lib/index.js
function stringifyEntities(value, options2) {
  return core(value, Object.assign({ format: formatSmart }, options2));
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/handle/comment.js
var htmlCommentRegex = /^>|^->|<!--|-->|--!>|<!-$/g;
var bogusCommentEntitySubset = [">"];
var commentEntitySubset = ["<", ">"];
function comment3(node2, _1, _2, state) {
  return state.settings.bogusComments ? "<?" + stringifyEntities(
    node2.value,
    Object.assign({}, state.settings.characterReferences, {
      subset: bogusCommentEntitySubset
    })
  ) + ">" : "<!--" + node2.value.replace(htmlCommentRegex, encode3) + "-->";
  function encode3($0) {
    return stringifyEntities(
      $0,
      Object.assign({}, state.settings.characterReferences, {
        subset: commentEntitySubset
      })
    );
  }
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/handle/doctype.js
function doctype2(_1, _2, _3, state) {
  return "<!" + (state.settings.upperDoctype ? "DOCTYPE" : "doctype") + (state.settings.tightDoctype ? "" : " ") + "html>";
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/omission/util/siblings.js
var siblingAfter = siblings(1);
var siblingBefore = siblings(-1);
var emptyChildren = [];
function siblings(increment2) {
  return sibling;
  function sibling(parent, index4, includeWhitespace) {
    const siblings2 = parent ? parent.children : emptyChildren;
    let offset4 = (index4 || 0) + increment2;
    let next2 = siblings2[offset4];
    if (!includeWhitespace) {
      while (next2 && whitespace(next2)) {
        offset4 += increment2;
        next2 = siblings2[offset4];
      }
    }
    return next2;
  }
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/omission/omission.js
var own11 = {}.hasOwnProperty;
function omission(handlers4) {
  return omit;
  function omit(node2, index4, parent) {
    return own11.call(handlers4, node2.tagName) && handlers4[node2.tagName](node2, index4, parent);
  }
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/omission/closing.js
var closing = omission({
  body,
  caption: headOrColgroupOrCaption,
  colgroup: headOrColgroupOrCaption,
  dd,
  dt: dt2,
  head: headOrColgroupOrCaption,
  html: html5,
  li: li2,
  optgroup,
  option,
  p: p3,
  rp: rubyElement,
  rt: rubyElement,
  tbody,
  td: cells,
  tfoot,
  th: cells,
  thead,
  tr: tr2
});
function headOrColgroupOrCaption(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4, true);
  return !next2 || next2.type !== "comment" && !(next2.type === "text" && whitespace(next2.value.charAt(0)));
}
function html5(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return !next2 || next2.type !== "comment";
}
function body(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return !next2 || next2.type !== "comment";
}
function p3(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return next2 ? next2.type === "element" && (next2.tagName === "address" || next2.tagName === "article" || next2.tagName === "aside" || next2.tagName === "blockquote" || next2.tagName === "details" || next2.tagName === "div" || next2.tagName === "dl" || next2.tagName === "fieldset" || next2.tagName === "figcaption" || next2.tagName === "figure" || next2.tagName === "footer" || next2.tagName === "form" || next2.tagName === "h1" || next2.tagName === "h2" || next2.tagName === "h3" || next2.tagName === "h4" || next2.tagName === "h5" || next2.tagName === "h6" || next2.tagName === "header" || next2.tagName === "hgroup" || next2.tagName === "hr" || next2.tagName === "main" || next2.tagName === "menu" || next2.tagName === "nav" || next2.tagName === "ol" || next2.tagName === "p" || next2.tagName === "pre" || next2.tagName === "section" || next2.tagName === "table" || next2.tagName === "ul") : !parent || // Confusing parent.
  !(parent.type === "element" && (parent.tagName === "a" || parent.tagName === "audio" || parent.tagName === "del" || parent.tagName === "ins" || parent.tagName === "map" || parent.tagName === "noscript" || parent.tagName === "video"));
}
function li2(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return !next2 || next2.type === "element" && next2.tagName === "li";
}
function dt2(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return Boolean(
    next2 && next2.type === "element" && (next2.tagName === "dt" || next2.tagName === "dd")
  );
}
function dd(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return !next2 || next2.type === "element" && (next2.tagName === "dt" || next2.tagName === "dd");
}
function rubyElement(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return !next2 || next2.type === "element" && (next2.tagName === "rp" || next2.tagName === "rt");
}
function optgroup(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return !next2 || next2.type === "element" && next2.tagName === "optgroup";
}
function option(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return !next2 || next2.type === "element" && (next2.tagName === "option" || next2.tagName === "optgroup");
}
function thead(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return Boolean(
    next2 && next2.type === "element" && (next2.tagName === "tbody" || next2.tagName === "tfoot")
  );
}
function tbody(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return !next2 || next2.type === "element" && (next2.tagName === "tbody" || next2.tagName === "tfoot");
}
function tfoot(_2, index4, parent) {
  return !siblingAfter(parent, index4);
}
function tr2(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return !next2 || next2.type === "element" && next2.tagName === "tr";
}
function cells(_2, index4, parent) {
  const next2 = siblingAfter(parent, index4);
  return !next2 || next2.type === "element" && (next2.tagName === "td" || next2.tagName === "th");
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/omission/opening.js
var opening = omission({
  body: body2,
  colgroup,
  head,
  html: html6,
  tbody: tbody2
});
function html6(node2) {
  const head2 = siblingAfter(node2, -1);
  return !head2 || head2.type !== "comment";
}
function head(node2) {
  const seen = /* @__PURE__ */ new Set();
  for (const child2 of node2.children) {
    if (child2.type === "element" && (child2.tagName === "base" || child2.tagName === "title")) {
      if (seen.has(child2.tagName)) return false;
      seen.add(child2.tagName);
    }
  }
  const child = node2.children[0];
  return !child || child.type === "element";
}
function body2(node2) {
  const head2 = siblingAfter(node2, -1, true);
  return !head2 || head2.type !== "comment" && !(head2.type === "text" && whitespace(head2.value.charAt(0))) && !(head2.type === "element" && (head2.tagName === "meta" || head2.tagName === "link" || head2.tagName === "script" || head2.tagName === "style" || head2.tagName === "template"));
}
function colgroup(node2, index4, parent) {
  const previous3 = siblingBefore(parent, index4);
  const head2 = siblingAfter(node2, -1, true);
  if (parent && previous3 && previous3.type === "element" && previous3.tagName === "colgroup" && closing(previous3, parent.children.indexOf(previous3), parent)) {
    return false;
  }
  return Boolean(head2 && head2.type === "element" && head2.tagName === "col");
}
function tbody2(node2, index4, parent) {
  const previous3 = siblingBefore(parent, index4);
  const head2 = siblingAfter(node2, -1);
  if (parent && previous3 && previous3.type === "element" && (previous3.tagName === "thead" || previous3.tagName === "tbody") && closing(previous3, parent.children.indexOf(previous3), parent)) {
    return false;
  }
  return Boolean(head2 && head2.type === "element" && head2.tagName === "tr");
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/handle/element.js
var constants2 = {
  // See: <https://html.spec.whatwg.org/#attribute-name-state>.
  name: [
    ["	\n\f\r &/=>".split(""), "	\n\f\r \"&'/=>`".split("")],
    [`\0	
\f\r "&'/<=>`.split(""), "\0	\n\f\r \"&'/<=>`".split("")]
  ],
  // See: <https://html.spec.whatwg.org/#attribute-value-(unquoted)-state>.
  unquoted: [
    ["	\n\f\r &>".split(""), "\0	\n\f\r \"&'<=>`".split("")],
    ["\0	\n\f\r \"&'<=>`".split(""), "\0	\n\f\r \"&'<=>`".split("")]
  ],
  // See: <https://html.spec.whatwg.org/#attribute-value-(single-quoted)-state>.
  single: [
    ["&'".split(""), "\"&'`".split("")],
    ["\0&'".split(""), "\0\"&'`".split("")]
  ],
  // See: <https://html.spec.whatwg.org/#attribute-value-(double-quoted)-state>.
  double: [
    ['"&'.split(""), "\"&'`".split("")],
    ['\0"&'.split(""), "\0\"&'`".split("")]
  ]
};
function element6(node2, index4, parent, state) {
  const schema = state.schema;
  const omit = schema.space === "svg" ? false : state.settings.omitOptionalTags;
  let selfClosing = schema.space === "svg" ? state.settings.closeEmptyElements : state.settings.voids.includes(node2.tagName.toLowerCase());
  const parts = [];
  let last2;
  if (schema.space === "html" && node2.tagName === "svg") {
    state.schema = svg2;
  }
  const attributes = serializeAttributes2(state, node2.properties);
  const content5 = state.all(
    schema.space === "html" && node2.tagName === "template" ? node2.content : node2
  );
  state.schema = schema;
  if (content5) selfClosing = false;
  if (attributes || !omit || !opening(node2, index4, parent)) {
    parts.push("<", node2.tagName, attributes ? " " + attributes : "");
    if (selfClosing && (schema.space === "svg" || state.settings.closeSelfClosing)) {
      last2 = attributes.charAt(attributes.length - 1);
      if (!state.settings.tightSelfClosing || last2 === "/" || last2 && last2 !== '"' && last2 !== "'") {
        parts.push(" ");
      }
      parts.push("/");
    }
    parts.push(">");
  }
  parts.push(content5);
  if (!selfClosing && (!omit || !closing(node2, index4, parent))) {
    parts.push("</" + node2.tagName + ">");
  }
  return parts.join("");
}
function serializeAttributes2(state, properties) {
  const values2 = [];
  let index4 = -1;
  let key2;
  if (properties) {
    for (key2 in properties) {
      if (properties[key2] !== null && properties[key2] !== void 0) {
        const value = serializeAttribute(state, key2, properties[key2]);
        if (value) values2.push(value);
      }
    }
  }
  while (++index4 < values2.length) {
    const last2 = state.settings.tightAttributes ? values2[index4].charAt(values2[index4].length - 1) : void 0;
    if (index4 !== values2.length - 1 && last2 !== '"' && last2 !== "'") {
      values2[index4] += " ";
    }
  }
  return values2.join("");
}
function serializeAttribute(state, key2, value) {
  const info = find2(state.schema, key2);
  const x5 = state.settings.allowParseErrors && state.schema.space === "html" ? 0 : 1;
  const y3 = state.settings.allowDangerousCharacters ? 0 : 1;
  let quote = state.quote;
  let result;
  if (info.overloadedBoolean && (value === info.attribute || value === "")) {
    value = true;
  } else if ((info.boolean || info.overloadedBoolean) && (typeof value !== "string" || value === info.attribute || value === "")) {
    value = Boolean(value);
  }
  if (value === null || value === void 0 || value === false || typeof value === "number" && Number.isNaN(value)) {
    return "";
  }
  const name = stringifyEntities(
    info.attribute,
    Object.assign({}, state.settings.characterReferences, {
      // Always encode without parse errors in non-HTML.
      subset: constants2.name[x5][y3]
    })
  );
  if (value === true) return name;
  value = Array.isArray(value) ? (info.commaSeparated ? stringify3 : stringify4)(value, {
    padLeft: !state.settings.tightCommaSeparatedLists
  }) : String(value);
  if (state.settings.collapseEmptyAttributes && !value) return name;
  if (state.settings.preferUnquoted) {
    result = stringifyEntities(
      value,
      Object.assign({}, state.settings.characterReferences, {
        attribute: true,
        subset: constants2.unquoted[x5][y3]
      })
    );
  }
  if (result !== value) {
    if (state.settings.quoteSmart && ccount(value, quote) > ccount(value, state.alternative)) {
      quote = state.alternative;
    }
    result = quote + stringifyEntities(
      value,
      Object.assign({}, state.settings.characterReferences, {
        // Always encode without parse errors in non-HTML.
        subset: (quote === "'" ? constants2.single : constants2.double)[x5][y3],
        attribute: true
      })
    ) + quote;
  }
  return name + (result ? "=" + result : result);
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/handle/text.js
var textEntitySubset = ["<", "&"];
function text9(node2, _2, parent, state) {
  return parent && parent.type === "element" && (parent.tagName === "script" || parent.tagName === "style") ? node2.value : stringifyEntities(
    node2.value,
    Object.assign({}, state.settings.characterReferences, {
      subset: textEntitySubset
    })
  );
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/handle/raw.js
function raw(node2, index4, parent, state) {
  return state.settings.allowDangerousHtml ? node2.value : text9(node2, index4, parent, state);
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/handle/root.js
function root5(node2, _1, _2, state) {
  return state.all(node2);
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/handle/index.js
var handle3 = zwitch("type", {
  invalid: invalid2,
  unknown: unknown2,
  handlers: { comment: comment3, doctype: doctype2, element: element6, raw, root: root5, text: text9 }
});
function invalid2(node2) {
  throw new Error("Expected node, not `" + node2 + "`");
}
function unknown2(node_) {
  const node2 = (
    /** @type {Nodes} */
    node_
  );
  throw new Error("Cannot compile unknown node `" + node2.type + "`");
}

// ../../node_modules/.pnpm/hast-util-to-html@9.0.5/node_modules/hast-util-to-html/lib/index.js
var emptyOptions7 = {};
var emptyCharacterReferences = {};
var emptyChildren2 = [];
function toHtml(tree, options2) {
  const options_ = options2 || emptyOptions7;
  const quote = options_.quote || '"';
  const alternative = quote === '"' ? "'" : '"';
  if (quote !== '"' && quote !== "'") {
    throw new Error("Invalid quote `" + quote + "`, expected `'` or `\"`");
  }
  const state = {
    one: one5,
    all: all8,
    settings: {
      omitOptionalTags: options_.omitOptionalTags || false,
      allowParseErrors: options_.allowParseErrors || false,
      allowDangerousCharacters: options_.allowDangerousCharacters || false,
      quoteSmart: options_.quoteSmart || false,
      preferUnquoted: options_.preferUnquoted || false,
      tightAttributes: options_.tightAttributes || false,
      upperDoctype: options_.upperDoctype || false,
      tightDoctype: options_.tightDoctype || false,
      bogusComments: options_.bogusComments || false,
      tightCommaSeparatedLists: options_.tightCommaSeparatedLists || false,
      tightSelfClosing: options_.tightSelfClosing || false,
      collapseEmptyAttributes: options_.collapseEmptyAttributes || false,
      allowDangerousHtml: options_.allowDangerousHtml || false,
      voids: options_.voids || htmlVoidElements,
      characterReferences: options_.characterReferences || emptyCharacterReferences,
      closeSelfClosing: options_.closeSelfClosing || false,
      closeEmptyElements: options_.closeEmptyElements || false
    },
    schema: options_.space === "svg" ? svg2 : html2,
    quote,
    alternative
  };
  return state.one(
    Array.isArray(tree) ? { type: "root", children: tree } : tree,
    void 0,
    void 0
  );
}
function one5(node2, index4, parent) {
  return handle3(node2, index4, parent, this);
}
function all8(parent) {
  const results = [];
  const children = parent && parent.children || emptyChildren2;
  let index4 = -1;
  while (++index4 < children.length) {
    results[index4] = this.one(children[index4], index4, parent);
  }
  return results.join("");
}

// ../../node_modules/.pnpm/rehype-stringify@10.0.1/node_modules/rehype-stringify/lib/index.js
function rehypeStringify(options2) {
  const self2 = this;
  const settings = { ...self2.data("settings"), ...options2 };
  self2.compiler = compiler2;
  function compiler2(tree) {
    return toHtml(tree, settings);
  }
}

// ../../node_modules/.pnpm/@blocknote+core@0.45.0_@tiptap+extensions@3.14.0_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__f23d443be271153d169671d52d4cc932/node_modules/@blocknote/core/dist/blocknote.js
var Oe3 = Object.defineProperty;
var Fe = (o2, e2, t2) => e2 in o2 ? Oe3(o2, e2, { enumerable: true, configurable: true, writable: true, value: t2 }) : o2[e2] = t2;
var h6 = (o2, e2, t2) => Fe(o2, typeof e2 != "symbol" ? e2 + "" : e2, t2);
function Kt2(o2, e2) {
  const t2 = [
    {
      tag: `[data-inline-content-type="${o2.type}"]`,
      contentElement: (n) => {
        const s2 = n;
        return s2.matches("[data-editable]") ? s2 : s2.querySelector("[data-editable]") || s2;
      }
    }
  ];
  return e2 && t2.push({
    tag: "*",
    getAttrs(n) {
      if (typeof n == "string")
        return false;
      const s2 = e2 == null ? void 0 : e2(n);
      return s2 === void 0 ? false : s2;
    }
  }), t2;
}
function Jt3(o2, e2, t2, n = "before") {
  const s2 = typeof t2 == "string" ? t2 : t2.id, r4 = ht(o2), i3 = e2.map(
    (d) => bt(d, r4)
  ), c3 = Tt2(s2, o2.doc);
  if (!c3)
    throw new Error(`Block with ID ${s2} not found`);
  let a3 = c3.posBeforeNode;
  return n === "after" && (a3 += c3.node.nodeSize), o2.step(
    new ReplaceStep(a3, a3, new Slice(Fragment.from(i3), 0, 0))
  ), i3.map(
    (d) => L(d, r4)
  );
}
function j3(o2) {
  if (!o2 || o2.type.name !== "column")
    throw new Error("Invalid columnPos: does not point to column node.");
  const e2 = o2.firstChild;
  if (!e2)
    throw new Error("Invalid column: does not have child node.");
  const t2 = e2.firstChild;
  if (!t2)
    throw new Error("Invalid blockContainer: does not have child node.");
  return o2.childCount === 1 && e2.childCount === 1 && t2.type.name === "paragraph" && t2.content.content.length === 0;
}
function qt2(o2, e2) {
  const t2 = o2.doc.resolve(e2), n = t2.nodeAfter;
  if (!n || n.type.name !== "columnList")
    throw new Error(
      "Invalid columnListPos: does not point to columnList node."
    );
  for (let s2 = n.childCount - 1; s2 >= 0; s2--) {
    const r4 = o2.doc.resolve(t2.pos + 1).posAtIndex(s2), c3 = o2.doc.resolve(r4).nodeAfter;
    if (!c3 || c3.type.name !== "column")
      throw new Error("Invalid columnPos: does not point to column node.");
    j3(c3) && o2.delete(r4, r4 + c3.nodeSize);
  }
}
function W2(o2, e2) {
  qt2(o2, e2);
  const n = o2.doc.resolve(e2).nodeAfter;
  if (!n || n.type.name !== "columnList")
    throw new Error(
      "Invalid columnListPos: does not point to columnList node."
    );
  if (n.childCount > 2)
    return;
  if (n.childCount < 2)
    throw new Error("Invalid columnList: contains fewer than two children.");
  const s2 = e2 + 1, i3 = o2.doc.resolve(s2).nodeAfter, c3 = e2 + n.nodeSize - 1, l2 = o2.doc.resolve(c3).nodeBefore;
  if (!i3 || !l2)
    throw new Error("Invalid columnList: does not contain children.");
  const d = j3(i3), u2 = j3(l2);
  if (d && u2) {
    o2.delete(e2, e2 + n.nodeSize);
    return;
  }
  if (d) {
    o2.step(
      new ReplaceAroundStep(
        // Replaces `columnList`.
        e2,
        e2 + n.nodeSize,
        // Replaces with content of last `column`.
        c3 - l2.nodeSize + 1,
        c3 - 1,
        // Doesn't append anything.
        Slice.empty,
        0,
        false
      )
    );
    return;
  }
  if (u2) {
    o2.step(
      new ReplaceAroundStep(
        // Replaces `columnList`.
        e2,
        e2 + n.nodeSize,
        // Replaces with content of first `column`.
        s2 + 1,
        s2 + i3.nodeSize - 1,
        // Doesn't append anything.
        Slice.empty,
        0,
        false
      )
    );
    return;
  }
}
function ie4(o2, e2, t2) {
  const n = ht(o2), s2 = t2.map(
    (u2) => bt(u2, n)
  ), r4 = new Set(
    e2.map(
      (u2) => typeof u2 == "string" ? u2 : u2.id
    )
  ), i3 = [], c3 = /* @__PURE__ */ new Set(), a3 = typeof e2[0] == "string" ? e2[0] : e2[0].id;
  let l2 = 0;
  if (o2.doc.descendants((u2, p4) => {
    if (r4.size === 0)
      return false;
    if (!u2.type.isInGroup("bnBlock") || !r4.has(u2.attrs.id))
      return true;
    if (i3.push(L(u2, n)), r4.delete(u2.attrs.id), t2.length > 0 && u2.attrs.id === a3) {
      const g = o2.doc.nodeSize;
      o2.insert(p4, s2);
      const y3 = o2.doc.nodeSize;
      l2 += g - y3;
    }
    const m2 = o2.doc.nodeSize, f6 = o2.doc.resolve(p4 - l2);
    f6.node().type.name === "column" ? c3.add(f6.before(-1)) : f6.node().type.name === "columnList" && c3.add(f6.before()), f6.node().type.name === "blockGroup" && f6.node(f6.depth - 1).type.name !== "doc" && f6.node().childCount === 1 ? o2.delete(f6.before(), f6.after()) : o2.delete(p4 - l2, p4 - l2 + u2.nodeSize);
    const k3 = o2.doc.nodeSize;
    return l2 += m2 - k3, false;
  }), r4.size > 0) {
    const u2 = [...r4].join(`
`);
    throw Error(
      "Blocks with the following IDs could not be found in the editor: " + u2
    );
  }
  return c3.forEach((u2) => W2(o2, u2)), { insertedBlocks: s2.map(
    (u2) => L(u2, n)
  ), removedBlocks: i3 };
}
function Yt2(o2, e2, t2, n, s2) {
  let r4;
  if (e2)
    if (typeof e2 == "string")
      r4 = T([e2], o2.pmSchema, n);
    else if (Array.isArray(e2))
      r4 = T(e2, o2.pmSchema, n);
    else if (e2.type === "tableContent")
      r4 = kt(e2, o2.pmSchema);
    else
      throw new O(e2.type);
  else throw new Error("blockContent is required");
  const c3 = ((s2 == null ? void 0 : s2.document) ?? document).createDocumentFragment();
  for (const a3 of r4)
    if (a3.type.name !== "text" && o2.schema.inlineContentSchema[a3.type.name]) {
      const l2 = o2.schema.inlineContentSpecs[a3.type.name].implementation;
      if (l2) {
        const d = wt(
          a3,
          o2.schema.inlineContentSchema,
          o2.schema.styleSchema
        ), u2 = l2.render.call(
          {
            renderType: "dom",
            props: void 0
          },
          d,
          () => {
          },
          o2
        );
        if (u2) {
          if (c3.appendChild(u2.dom), u2.contentDOM) {
            const p4 = t2.serializeFragment(
              a3.content,
              s2
            );
            u2.contentDOM.dataset.editable = "", u2.contentDOM.appendChild(p4);
          }
          continue;
        }
      }
    } else if (a3.type.name === "text") {
      let l2 = document.createTextNode(
        a3.textContent
      );
      for (const d of a3.marks.toReversed())
        if (d.type.name in o2.schema.styleSpecs) {
          const u2 = o2.schema.styleSpecs[d.type.name].implementation.render(d.attrs.stringValue, o2);
          u2.contentDOM.appendChild(l2), l2 = u2.dom;
        } else {
          const u2 = d.type.spec.toDOM(d, true), p4 = DOMSerializer.renderSpec(document, u2);
          p4.contentDOM.appendChild(l2), l2 = p4.dom;
        }
      c3.appendChild(l2);
    } else {
      const l2 = t2.serializeFragment(
        Fragment.from([a3]),
        s2
      );
      c3.appendChild(l2);
    }
  return c3;
}
function Qt2(o2, e2, t2, n) {
  var u2, p4, m2, f6, k3;
  const s2 = o2.pmSchema.nodes.blockContainer, r4 = e2.props || {};
  for (const [g, y3] of Object.entries(
    o2.schema.blockSchema[e2.type].propSchema
  ))
    !(g in r4) && y3.default !== void 0 && (r4[g] = y3.default);
  const i3 = e2.children || [], a3 = o2.blockImplementations[e2.type].implementation.render.call(
    {
      renderType: "dom",
      props: void 0
    },
    { ...e2, props: r4, children: i3 },
    o2
  );
  if (a3.contentDOM && e2.content) {
    const g = Yt2(
      o2,
      e2.content,
      // TODO
      t2,
      e2.type,
      n
    );
    a3.contentDOM.appendChild(g);
  }
  if (o2.pmSchema.nodes[e2.type].isInGroup("bnBlock")) {
    if (e2.children && e2.children.length > 0) {
      const g = Be2(
        o2,
        e2.children,
        t2,
        n
      );
      (u2 = a3.contentDOM) == null || u2.append(g);
    }
    return a3.dom;
  }
  const d = (m2 = (p4 = s2.spec) == null ? void 0 : p4.toDOM) == null ? void 0 : m2.call(
    p4,
    s2.create({
      id: e2.id,
      ...r4
    })
  );
  return (f6 = d.contentDOM) == null || f6.appendChild(a3.dom), e2.children && e2.children.length > 0 && ((k3 = d.contentDOM) == null || k3.appendChild(
    Ce2(o2, e2.children, t2, n)
  )), d.dom;
}
function Be2(o2, e2, t2, n) {
  const r4 = ((n == null ? void 0 : n.document) ?? document).createDocumentFragment();
  for (const i3 of e2) {
    const c3 = Qt2(o2, i3, t2, n);
    r4.appendChild(c3);
  }
  return r4;
}
var Ce2 = (o2, e2, t2, n) => {
  var c3;
  const s2 = o2.pmSchema.nodes.blockGroup, r4 = s2.spec.toDOM(s2.create({})), i3 = Be2(o2, e2, t2, n);
  return (c3 = r4.contentDOM) == null || c3.appendChild(i3), r4.dom;
};
var Xt2 = (o2, e2) => {
  const t2 = DOMSerializer.fromSchema(o2);
  return {
    serializeBlocks: (n, s2) => Ce2(e2, n, t2, s2).outerHTML
  };
};
function Zt2(o2) {
  return o2.transact((e2) => {
    const t2 = Y2(e2.doc, e2.selection.anchor);
    if (e2.selection instanceof CellSelection)
      return {
        type: "cell",
        anchorBlockId: t2.node.attrs.id,
        anchorCellOffset: e2.selection.$anchorCell.pos - t2.posBeforeNode,
        headCellOffset: e2.selection.$headCell.pos - t2.posBeforeNode
      };
    if (e2.selection instanceof NodeSelection)
      return {
        type: "node",
        anchorBlockId: t2.node.attrs.id
      };
    {
      const n = Y2(e2.doc, e2.selection.head);
      return {
        type: "text",
        anchorBlockId: t2.node.attrs.id,
        headBlockId: n.node.attrs.id,
        anchorOffset: e2.selection.anchor - t2.posBeforeNode,
        headOffset: e2.selection.head - n.posBeforeNode
      };
    }
  });
}
function eo(o2, e2) {
  var s2, r4;
  const t2 = (s2 = Tt2(e2.anchorBlockId, o2.doc)) == null ? void 0 : s2.posBeforeNode;
  if (t2 === void 0)
    throw new Error(
      `Could not find block with ID ${e2.anchorBlockId} to update selection`
    );
  let n;
  if (e2.type === "cell")
    n = CellSelection.create(
      o2.doc,
      t2 + e2.anchorCellOffset,
      t2 + e2.headCellOffset
    );
  else if (e2.type === "node")
    n = NodeSelection.create(o2.doc, t2 + 1);
  else {
    const i3 = (r4 = Tt2(e2.headBlockId, o2.doc)) == null ? void 0 : r4.posBeforeNode;
    if (i3 === void 0)
      throw new Error(
        `Could not find block with ID ${e2.headBlockId} to update selection`
      );
    n = TextSelection.create(
      o2.doc,
      t2 + e2.anchorOffset,
      i3 + e2.headOffset
    );
  }
  o2.setSelection(n);
}
function K5(o2) {
  return o2.map((e2) => e2.type === "columnList" ? e2.children.map((t2) => K5(t2.children)).flat() : {
    ...e2,
    children: K5(e2.children)
  }).flat();
}
function xe2(o2, e2, t2) {
  o2.transact((n) => {
    var i3;
    const s2 = ((i3 = o2.getSelection()) == null ? void 0 : i3.blocks) || [
      o2.getTextCursorPosition().block
    ], r4 = Zt2(o2);
    o2.removeBlocks(s2), o2.insertBlocks(K5(s2), e2, t2), eo(n, r4);
  });
}
function Ee2(o2) {
  return !o2 || o2.type !== "columnList";
}
function Me2(o2, e2, t2) {
  let n, s2;
  if (e2 ? e2.children.length > 0 ? (n = e2.children[e2.children.length - 1], s2 = "after") : (n = e2, s2 = "before") : t2 && (n = t2, s2 = "before"), !n || !s2)
    return;
  const r4 = o2.getParentBlock(n);
  return Ee2(r4) ? { referenceBlock: n, placement: s2 } : Me2(
    o2,
    s2 === "after" ? n : o2.getPrevBlock(n),
    r4
  );
}
function we2(o2, e2, t2) {
  let n, s2;
  if (e2 ? e2.children.length > 0 ? (n = e2.children[0], s2 = "before") : (n = e2, s2 = "after") : t2 && (n = t2, s2 = "after"), !n || !s2)
    return;
  const r4 = o2.getParentBlock(n);
  return Ee2(r4) ? { referenceBlock: n, placement: s2 } : we2(
    o2,
    s2 === "before" ? n : o2.getNextBlock(n),
    r4
  );
}
function to(o2) {
  o2.transact(() => {
    const e2 = o2.getSelection(), t2 = (e2 == null ? void 0 : e2.blocks[0]) || o2.getTextCursorPosition().block, n = Me2(
      o2,
      o2.getPrevBlock(t2),
      o2.getParentBlock(t2)
    );
    n && xe2(
      o2,
      n.referenceBlock,
      n.placement
    );
  });
}
function oo(o2) {
  o2.transact(() => {
    const e2 = o2.getSelection(), t2 = (e2 == null ? void 0 : e2.blocks[(e2 == null ? void 0 : e2.blocks.length) - 1]) || o2.getTextCursorPosition().block, n = we2(
      o2,
      o2.getNextBlock(t2),
      o2.getParentBlock(t2)
    );
    n && xe2(
      o2,
      n.referenceBlock,
      n.placement
    );
  });
}
function no(o2, e2, t2) {
  const { $from: n, $to: s2 } = o2.selection, r4 = n.blockRange(
    s2,
    (f6) => f6.childCount > 0 && (f6.type.name === "blockGroup" || f6.type.name === "column")
    // change necessary to not look at first item child type
  );
  if (!r4)
    return false;
  const i3 = r4.startIndex;
  if (i3 === 0)
    return false;
  const a3 = r4.parent.child(i3 - 1);
  if (a3.type !== e2)
    return false;
  const l2 = a3.lastChild && a3.lastChild.type === t2, d = Fragment.from(l2 ? e2.create() : null), u2 = new Slice(
    Fragment.from(
      e2.create(null, Fragment.from(t2.create(null, d)))
      // change necessary to create "groupType" instead of parent.type
    ),
    l2 ? 3 : 1,
    0
  ), p4 = r4.start, m2 = r4.end;
  return o2.step(
    new ReplaceAroundStep(
      p4 - (l2 ? 3 : 1),
      m2,
      p4,
      m2,
      u2,
      1,
      true
    )
  ).scrollIntoView(), true;
}
function Te2(o2) {
  return o2.transact((e2) => no(
    e2,
    o2.pmSchema.nodes.blockContainer,
    o2.pmSchema.nodes.blockGroup
  ));
}
function so(o2) {
  o2._tiptapEditor.commands.liftListItem("blockContainer");
}
function ro(o2) {
  return o2.transact((e2) => {
    const { bnBlock: t2 } = Ot(e2);
    return e2.doc.resolve(t2.beforePos).nodeBefore !== null;
  });
}
function io(o2) {
  return o2.transact((e2) => {
    const { bnBlock: t2 } = Ot(e2);
    return e2.doc.resolve(t2.beforePos).depth > 1;
  });
}
function ao(o2, e2) {
  const t2 = typeof e2 == "string" ? e2 : e2.id, n = ht(o2), s2 = Tt2(t2, o2);
  if (s2)
    return L(s2.node, n);
}
function co(o2, e2) {
  const t2 = typeof e2 == "string" ? e2 : e2.id, n = Tt2(t2, o2), s2 = ht(o2);
  if (!n)
    return;
  const i3 = o2.resolve(n.posBeforeNode).nodeBefore;
  if (i3)
    return L(i3, s2);
}
function lo(o2, e2) {
  const t2 = typeof e2 == "string" ? e2 : e2.id, n = Tt2(t2, o2), s2 = ht(o2);
  if (!n)
    return;
  const i3 = o2.resolve(
    n.posBeforeNode + n.node.nodeSize
  ).nodeAfter;
  if (i3)
    return L(i3, s2);
}
function uo2(o2, e2) {
  const t2 = typeof e2 == "string" ? e2 : e2.id, n = ht(o2), s2 = Tt2(t2, o2);
  if (!s2)
    return;
  const r4 = o2.resolve(s2.posBeforeNode), i3 = r4.node(), c3 = r4.node(-1), a3 = c3.type.name !== "doc" ? i3.type.name === "blockGroup" ? c3 : i3 : void 0;
  if (a3)
    return L(a3, n);
}
var po3 = class {
  constructor(e2) {
    this.editor = e2;
  }
  /**
   * Gets a snapshot of all top-level (non-nested) blocks in the editor.
   * @returns A snapshot of all top-level (non-nested) blocks in the editor.
   */
  get document() {
    return this.editor.transact((e2) => St(e2.doc, this.editor.pmSchema));
  }
  /**
   * Gets a snapshot of an existing block from the editor.
   * @param blockIdentifier The identifier of an existing block that should be
   * retrieved.
   * @returns The block that matches the identifier, or `undefined` if no
   * matching block was found.
   */
  getBlock(e2) {
    return this.editor.transact((t2) => ao(t2.doc, e2));
  }
  /**
   * Gets a snapshot of the previous sibling of an existing block from the
   * editor.
   * @param blockIdentifier The identifier of an existing block for which the
   * previous sibling should be retrieved.
   * @returns The previous sibling of the block that matches the identifier.
   * `undefined` if no matching block was found, or it's the first child/block
   * in the document.
   */
  getPrevBlock(e2) {
    return this.editor.transact((t2) => co(t2.doc, e2));
  }
  /**
   * Gets a snapshot of the next sibling of an existing block from the editor.
   * @param blockIdentifier The identifier of an existing block for which the
   * next sibling should be retrieved.
   * @returns The next sibling of the block that matches the identifier.
   * `undefined` if no matching block was found, or it's the last child/block in
   * the document.
   */
  getNextBlock(e2) {
    return this.editor.transact((t2) => lo(t2.doc, e2));
  }
  /**
   * Gets a snapshot of the parent of an existing block from the editor.
   * @param blockIdentifier The identifier of an existing block for which the
   * parent should be retrieved.
   * @returns The parent of the block that matches the identifier. `undefined`
   * if no matching block was found, or the block isn't nested.
   */
  getParentBlock(e2) {
    return this.editor.transact(
      (t2) => uo2(t2.doc, e2)
    );
  }
  /**
   * Traverses all blocks in the editor depth-first, and executes a callback for each.
   * @param callback The callback to execute for each block. Returning `false` stops the traversal.
   * @param reverse Whether the blocks should be traversed in reverse order.
   */
  forEachBlock(e2, t2 = false) {
    const n = this.document.slice();
    t2 && n.reverse();
    function s2(r4) {
      for (const i3 of r4) {
        if (e2(i3) === false)
          return false;
        const c3 = t2 ? i3.children.slice().reverse() : i3.children;
        if (!s2(c3))
          return false;
      }
      return true;
    }
    s2(n);
  }
  /**
   * Inserts new blocks into the editor. If a block's `id` is undefined, BlockNote generates one automatically. Throws an
   * error if the reference block could not be found.
   * @param blocksToInsert An array of partial blocks that should be inserted.
   * @param referenceBlock An identifier for an existing block, at which the new blocks should be inserted.
   * @param placement Whether the blocks should be inserted just before, just after, or nested inside the
   * `referenceBlock`.
   */
  insertBlocks(e2, t2, n = "before") {
    return this.editor.transact(
      (s2) => Jt3(s2, e2, t2, n)
    );
  }
  /**
   * Updates an existing block in the editor. Since updatedBlock is a PartialBlock object, some fields might not be
   * defined. These undefined fields are kept as-is from the existing block. Throws an error if the block to update could
   * not be found.
   * @param blockToUpdate The block that should be updated.
   * @param update A partial block which defines how the existing block should be changed.
   */
  updateBlock(e2, t2) {
    return this.editor.transact((n) => yo(n, e2, t2));
  }
  /**
   * Removes existing blocks from the editor. Throws an error if any of the blocks could not be found.
   * @param blocksToRemove An array of identifiers for existing blocks that should be removed.
   */
  removeBlocks(e2) {
    return this.editor.transact(
      (t2) => ie4(t2, e2, []).removedBlocks
    );
  }
  /**
   * Replaces existing blocks in the editor with new blocks. If the blocks that should be removed are not adjacent or
   * are at different nesting levels, `blocksToInsert` will be inserted at the position of the first block in
   * `blocksToRemove`. Throws an error if any of the blocks to remove could not be found.
   * @param blocksToRemove An array of blocks that should be replaced.
   * @param blocksToInsert An array of partial blocks to replace the old ones with.
   */
  replaceBlocks(e2, t2) {
    return this.editor.transact(
      (n) => ie4(n, e2, t2)
    );
  }
  /**
   * Checks if the block containing the text cursor can be nested.
   */
  canNestBlock() {
    return ro(this.editor);
  }
  /**
   * Nests the block containing the text cursor into the block above it.
   */
  nestBlock() {
    Te2(this.editor);
  }
  /**
   * Checks if the block containing the text cursor is nested.
   */
  canUnnestBlock() {
    return io(this.editor);
  }
  /**
   * Lifts the block containing the text cursor out of its parent.
   */
  unnestBlock() {
    so(this.editor);
  }
  /**
   * Moves the selected blocks up. If the previous block has children, moves
   * them to the end of its children. If there is no previous block, but the
   * current blocks share a common parent, moves them out of & before it.
   */
  moveBlocksUp() {
    return to(this.editor);
  }
  /**
   * Moves the selected blocks down. If the next block has children, moves
   * them to the start of its children. If there is no next block, but the
   * current blocks share a common parent, moves them out of & after it.
   */
  moveBlocksDown() {
    return oo(this.editor);
  }
};
var fo3 = class extends f3 {
  constructor(e2) {
    super(), this.editor = e2, e2.on("create", () => {
      e2._tiptapEditor.on(
        "update",
        ({ transaction: t2, appendedTransactions: n }) => {
          this.emit("onChange", { editor: e2, transaction: t2, appendedTransactions: n });
        }
      ), e2._tiptapEditor.on("selectionUpdate", ({ transaction: t2 }) => {
        this.emit("onSelectionChange", { editor: e2, transaction: t2 });
      }), e2._tiptapEditor.on("mount", () => {
        this.emit("onMount", { editor: e2 });
      }), e2._tiptapEditor.on("unmount", () => {
        this.emit("onUnmount", { editor: e2 });
      });
    });
  }
  /**
   * Register a callback that will be called when the editor changes.
   */
  onChange(e2, t2 = true) {
    const n = ({
      transaction: s2,
      appendedTransactions: r4
    }) => {
      !t2 && ae(s2) || e2(this.editor, {
        getChanges() {
          return St3(
            s2,
            r4
          );
        }
      });
    };
    return this.on("onChange", n), () => {
      this.off("onChange", n);
    };
  }
  /**
   * Register a callback that will be called when the selection changes.
   */
  onSelectionChange(e2, t2 = false) {
    const n = (s2) => {
      !t2 && ae(s2.transaction) || e2(this.editor);
    };
    return this.on("onSelectionChange", n), () => {
      this.off("onSelectionChange", n);
    };
  }
  /**
   * Register a callback that will be called when the editor is mounted.
   */
  onMount(e2) {
    return this.on("onMount", e2), () => {
      this.off("onMount", e2);
    };
  }
  /**
   * Register a callback that will be called when the editor is unmounted.
   */
  onUnmount(e2) {
    return this.on("onUnmount", e2), () => {
      this.off("onUnmount", e2);
    };
  }
};
function ae(o2) {
  return !!o2.getMeta("y-sync$");
}
function ho2(o2) {
  return Array.prototype.indexOf.call(o2.parentElement.childNodes, o2);
}
function mo2(o2) {
  return o2.nodeType === 3 && !/\S/.test(o2.nodeValue || "");
}
function ko3(o2) {
  o2.querySelectorAll("li > ul, li > ol").forEach((e2) => {
    const t2 = ho2(e2), n = e2.parentElement, s2 = Array.from(n.childNodes).slice(
      t2 + 1
    );
    e2.remove(), s2.forEach((r4) => {
      r4.remove();
    }), n.insertAdjacentElement("afterend", e2), s2.reverse().forEach((r4) => {
      if (mo2(r4))
        return;
      const i3 = document.createElement("li");
      i3.append(r4), e2.insertAdjacentElement("afterend", i3);
    }), n.childNodes.length === 0 && n.remove();
  });
}
function go3(o2) {
  o2.querySelectorAll("li + ul, li + ol").forEach((e2) => {
    var r4, i3;
    const t2 = e2.previousElementSibling, n = document.createElement("div");
    t2.insertAdjacentElement("afterend", n), n.append(t2);
    const s2 = document.createElement("div");
    for (s2.setAttribute("data-node-type", "blockGroup"), n.append(s2); ((r4 = n.nextElementSibling) == null ? void 0 : r4.nodeName) === "UL" || ((i3 = n.nextElementSibling) == null ? void 0 : i3.nodeName) === "OL"; )
      s2.append(n.nextElementSibling);
  });
}
var ce = null;
function bo3() {
  return ce || (ce = document.implementation.createHTMLDocument("title"));
}
function yo3(o2) {
  if (typeof o2 == "string") {
    const e2 = bo3().createElement("div");
    e2.innerHTML = o2, o2 = e2;
  }
  return ko3(o2), go3(o2), o2;
}
function Pe2(o2, e2) {
  const t2 = yo3(o2), s2 = DOMParser2.fromSchema(e2).parse(t2, {
    topNode: e2.nodes.blockGroup.create()
  }), r4 = [];
  for (let i3 = 0; i3 < s2.childCount; i3++)
    r4.push(L(s2.child(i3), e2));
  return r4;
}
function So3(o2, e2) {
  const t2 = e2.value ? e2.value : "", n = {};
  e2.lang && (n["data-language"] = e2.lang);
  let s2 = {
    type: "element",
    tagName: "code",
    properties: n,
    children: [{ type: "text", value: t2 }]
  };
  return e2.meta && (s2.data = { meta: e2.meta }), o2.patch(e2, s2), s2 = o2.applyData(e2, s2), s2 = {
    type: "element",
    tagName: "pre",
    properties: {},
    children: [s2]
  }, o2.patch(e2, s2), s2;
}
function Bo3(o2, e2) {
  var r4;
  const t2 = String((e2 == null ? void 0 : e2.url) || ""), n = e2 != null && e2.title ? String(e2.title) : void 0;
  let s2 = {
    type: "element",
    tagName: "video",
    properties: {
      src: t2,
      "data-name": n,
      "data-url": t2,
      controls: true
    },
    children: []
  };
  return (r4 = o2.patch) == null || r4.call(o2, e2, s2), s2 = o2.applyData ? o2.applyData(e2, s2) : s2, s2;
}
function ve2(o2) {
  return unified().use(remarkParse).use(remarkGfm).use(remarkRehype, {
    handlers: {
      ...handlers3,
      image: (t2, n) => {
        const s2 = String((n == null ? void 0 : n.url) || "");
        return fo(s2) ? Bo3(t2, n) : handlers3.image(t2, n);
      },
      code: So3,
      blockquote: (t2, n) => {
        const s2 = {
          type: "element",
          tagName: "blockquote",
          properties: {},
          // The only difference from the original is that we don't wrap the children with line endings
          children: t2.wrap(t2.all(n), false)
        };
        return t2.patch(n, s2), t2.applyData(n, s2);
      }
    }
  }).use(rehypeStringify).processSync(o2).value;
}
function Co3(o2, e2) {
  const t2 = ve2(o2);
  return Pe2(t2, e2);
}
var xo3 = class {
  constructor(e2) {
    this.editor = e2;
  }
  /**
   * Exports blocks into a simplified HTML string. To better conform to HTML standards, children of blocks which aren't list
   * items are un-nested in the output HTML.
   *
   * @param blocks An array of blocks that should be serialized into HTML.
   * @returns The blocks, serialized as an HTML string.
   */
  blocksToHTMLLossy(e2 = this.editor.document) {
    return ve(
      this.editor.pmSchema,
      this.editor
    ).exportBlocks(e2, {});
  }
  /**
   * Serializes blocks into an HTML string in the format that would normally be rendered by the editor.
   *
   * Use this method if you want to server-side render HTML (for example, a blog post that has been edited in BlockNote)
   * and serve it to users without loading the editor on the client (i.e.: displaying the blog post)
   *
   * @param blocks An array of blocks that should be serialized into HTML.
   * @returns The blocks, serialized as an HTML string.
   */
  blocksToFullHTML(e2 = this.editor.document) {
    return Xt2(
      this.editor.pmSchema,
      this.editor
    ).serializeBlocks(e2, {});
  }
  /**
   * Parses blocks from an HTML string. Tries to create `Block` objects out of any HTML block-level elements, and
   * `InlineNode` objects from any HTML inline elements, though not all element types are recognized. If BlockNote
   * doesn't recognize an HTML element's tag, it will parse it as a paragraph or plain text.
   * @param html The HTML string to parse blocks from.
   * @returns The blocks parsed from the HTML string.
   */
  tryParseHTMLToBlocks(e2) {
    return Pe2(e2, this.editor.pmSchema);
  }
  /**
   * Serializes blocks into a Markdown string. The output is simplified as Markdown does not support all features of
   * BlockNote - children of blocks which aren't list items are un-nested and certain styles are removed.
   * @param blocks An array of blocks that should be serialized into Markdown.
   * @returns The blocks, serialized as a Markdown string.
   */
  blocksToMarkdownLossy(e2 = this.editor.document) {
    return Io(e2, this.editor.pmSchema, this.editor, {});
  }
  /**
   * Creates a list of blocks from a Markdown string. Tries to create `Block` and `InlineNode` objects based on
   * Markdown syntax, though not all symbols are recognized. If BlockNote doesn't recognize a symbol, it will parse it
   * as text.
   * @param markdown The Markdown string to parse blocks from.
   * @returns The blocks parsed from the Markdown string.
   */
  tryParseMarkdownToBlocks(e2) {
    return Co3(e2, this.editor.pmSchema);
  }
  /**
   * Paste HTML into the editor. Defaults to converting HTML to BlockNote HTML.
   * @param html The HTML to paste.
   * @param raw Whether to paste the HTML as is, or to convert it to BlockNote HTML.
   */
  pasteHTML(e2, t2 = false) {
    var s2;
    let n = e2;
    if (!t2) {
      const r4 = this.tryParseHTMLToBlocks(e2);
      n = this.blocksToFullHTML(r4);
    }
    n && ((s2 = this.editor.prosemirrorView) == null || s2.pasteHTML(n));
  }
  /**
   * Paste text into the editor. Defaults to interpreting text as markdown.
   * @param text The text to paste.
   */
  pasteText(e2) {
    var t2;
    return (t2 = this.editor.prosemirrorView) == null ? void 0 : t2.pasteText(e2);
  }
  /**
   * Paste markdown into the editor.
   * @param markdown The markdown to paste.
   */
  pasteMarkdown(e2) {
    const t2 = ve2(e2);
    return this.pasteHTML(t2);
  }
};
var oe2 = [
  "vscode-editor-data",
  "blocknote/html",
  "text/markdown",
  "text/html",
  "text/plain",
  "Files"
];
function Eo3(o2, e2) {
  if (!o2.startsWith(".") || !e2.startsWith("."))
    throw new Error("The strings provided are not valid file extensions.");
  return o2 === e2;
}
function Mo2(o2, e2) {
  const t2 = o2.split("/"), n = e2.split("/");
  if (t2.length !== 2)
    throw new Error(`The string ${o2} is not a valid MIME type.`);
  if (n.length !== 2)
    throw new Error(`The string ${e2} is not a valid MIME type.`);
  return t2[1] === "*" || n[1] === "*" ? t2[0] === n[0] : (t2[0] === "*" || n[0] === "*" || t2[0] === n[0]) && t2[1] === n[1];
}
function le2(o2, e2, t2, n = "after") {
  let s2;
  return Array.isArray(e2.content) && e2.content.length === 0 ? s2 = o2.updateBlock(e2, t2).id : s2 = o2.insertBlocks(
    [t2],
    e2,
    n
  )[0].id, s2;
}
async function Ie3(o2, e2) {
  var r4;
  if (!e2.uploadFile) {
    console.warn(
      "Attempted ot insert file, but uploadFile is not set in the BlockNote editor options"
    );
    return;
  }
  const t2 = "dataTransfer" in o2 ? o2.dataTransfer : o2.clipboardData;
  if (t2 === null)
    return;
  let n = null;
  for (const i3 of oe2)
    if (t2.types.includes(i3)) {
      n = i3;
      break;
    }
  if (n !== "Files")
    return;
  const s2 = t2.items;
  if (s2) {
    o2.preventDefault();
    for (let i3 = 0; i3 < s2.length; i3++) {
      let c3 = "file";
      for (const l2 of Object.values(e2.schema.blockSpecs))
        for (const d of ((r4 = l2.implementation.meta) == null ? void 0 : r4.fileBlockAccept) || []) {
          const u2 = d.startsWith("."), p4 = s2[i3].getAsFile();
          if (p4 && (!u2 && p4.type && Mo2(s2[i3].type, d) || u2 && Eo3(
            "." + p4.name.split(".").pop(),
            d
          ))) {
            c3 = l2.config.type;
            break;
          }
        }
      const a3 = s2[i3].getAsFile();
      if (a3) {
        const l2 = {
          type: c3,
          props: {
            name: a3.name
          }
        };
        let d;
        if (o2.type === "paste") {
          const m2 = e2.getTextCursorPosition().block;
          d = le2(e2, m2, l2);
        } else if (o2.type === "drop") {
          const m2 = {
            left: o2.clientX,
            top: o2.clientY
          }, f6 = e2.prosemirrorView.posAtCoords(m2);
          if (!f6)
            return;
          d = e2.transact((k3) => {
            var S4;
            const g = Y2(k3.doc, f6.pos), y3 = (S4 = e2.domElement) == null ? void 0 : S4.querySelector(
              `[data-id="${g.node.attrs.id}"]`
            ), T4 = y3 == null ? void 0 : y3.getBoundingClientRect();
            return le2(
              e2,
              e2.getBlock(g.node.attrs.id),
              l2,
              T4 && (T4.top + T4.bottom) / 2 > m2.top ? "before" : "after"
            );
          });
        } else
          return;
        const u2 = await e2.uploadFile(a3, d), p4 = typeof u2 == "string" ? {
          props: {
            url: u2
          }
        } : { ...u2 };
        e2.updateBlock(d, p4);
      }
    }
  }
}
var wo3 = (o2) => Extension.create({
  name: "dropFile",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        props: {
          handleDOMEvents: {
            drop(e2, t2) {
              if (!o2.isEditable)
                return;
              let n = null;
              for (const s2 of oe2)
                if (t2.dataTransfer.types.includes(s2)) {
                  n = s2;
                  break;
                }
              return n === null ? true : n === "Files" ? (Ie3(t2, o2), true) : false;
            }
          }
        }
      })
    ];
  }
});
var To3 = /(^|\n) {0,3}#{1,6} {1,8}[^\n]{1,64}\r?\n\r?\n\s{0,32}\S/;
var Po3 = /(_|__|\*|\*\*|~~|==|\+\+)(?!\s)(?:[^\s](?:.{0,62}[^\s])?|\S)(?=\1)/;
var vo3 = /\[[^\]]{1,128}\]\(https?:\/\/\S{1,999}\)/;
var Io2 = /(?:\s|^)`(?!\s)(?:[^\s`](?:[^`]{0,46}[^\s`])?|[^\s`])`([^\w]|$)/;
var Ao2 = /(?:^|\n)\s{0,5}-\s{1}[^\n]+\n\s{0,15}-\s/;
var _o = /(?:^|\n)\s{0,5}\d+\.\s{1}[^\n]+\n\s{0,15}\d+\.\s/;
var Do = /\n{2} {0,3}-{2,48}\n{2}/;
var Lo2 = /(?:\n|^)(```|~~~|\$\$)(?!`|~)[^\s]{0,64} {0,64}[^\n]{0,64}\n[\s\S]{0,9999}?\s*\1 {0,64}(?:\n+|$)/;
var No2 = /(?:\n|^)(?!\s)\w[^\n]{0,64}\r?\n(-|=)\1{0,64}\n\n\s{0,64}(\w|$)/;
var Oo = /(?:^|(\r?\n\r?\n))( {0,3}>[^\n]{1,333}\n){1,999}($|(\r?\n))/;
var Fo = /^\s*\|(.+\|)+\s*$/m;
var $o = /^\s*\|(\s*[-:]+[-:]\s*\|)+\s*$/m;
var Ho2 = /^\s*\|(.+\|)+\s*$/m;
var Vo = (o2) => To3.test(o2) || Po3.test(o2) || vo3.test(o2) || Io2.test(o2) || Ao2.test(o2) || _o.test(o2) || Do.test(o2) || Lo2.test(o2) || No2.test(o2) || Oo.test(o2) || Fo.test(o2) || $o.test(o2) || Ho2.test(o2);
async function Uo(o2, e2) {
  const { schema: t2 } = e2.state;
  if (!o2.clipboardData)
    return false;
  const n = o2.clipboardData.getData("text/plain");
  if (!n)
    return false;
  if (!t2.nodes.codeBlock)
    return e2.pasteText(n), true;
  const s2 = o2.clipboardData.getData("vscode-editor-data"), r4 = s2 ? JSON.parse(s2) : void 0, i3 = r4 == null ? void 0 : r4.mode;
  return i3 ? (e2.pasteHTML(
    `<pre><code class="language-${i3}">${n.replace(
      /\r\n?/g,
      `
`
    )}</code></pre>`
  ), true) : false;
}
function zo({
  event: o2,
  editor: e2,
  prioritizeMarkdownOverHTML: t2,
  plainTextAsMarkdown: n
}) {
  var c3;
  if (e2.transact(
    (a3) => a3.selection.$from.parent.type.spec.code && a3.selection.$to.parent.type.spec.code
  )) {
    const a3 = (c3 = o2.clipboardData) == null ? void 0 : c3.getData("text/plain");
    if (a3)
      return e2.pasteText(a3), true;
  }
  let r4;
  for (const a3 of oe2)
    if (o2.clipboardData.types.includes(a3)) {
      r4 = a3;
      break;
    }
  if (!r4)
    return true;
  if (r4 === "vscode-editor-data")
    return Uo(o2, e2.prosemirrorView), true;
  if (r4 === "Files")
    return Ie3(o2, e2), true;
  const i3 = o2.clipboardData.getData(r4);
  if (r4 === "blocknote/html")
    return e2.pasteHTML(i3, true), true;
  if (r4 === "text/markdown")
    return e2.pasteMarkdown(i3), true;
  if (t2) {
    const a3 = o2.clipboardData.getData("text/plain");
    if (Vo(a3))
      return e2.pasteMarkdown(a3), true;
  }
  return r4 === "text/html" ? (e2.pasteHTML(i3), true) : n ? (e2.pasteMarkdown(i3), true) : (e2.pasteText(i3), true);
}
var Go = (o2, e2) => Extension.create({
  name: "pasteFromClipboard",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        props: {
          handleDOMEvents: {
            paste(t2, n) {
              if (n.preventDefault(), !!o2.isEditable)
                return e2({
                  event: n,
                  editor: o2,
                  defaultPasteHandler: ({
                    prioritizeMarkdownOverHTML: s2 = true,
                    plainTextAsMarkdown: r4 = true
                  } = {}) => zo({
                    event: n,
                    editor: o2,
                    prioritizeMarkdownOverHTML: s2,
                    plainTextAsMarkdown: r4
                  })
                });
            }
          }
        }
      })
    ];
  }
});
function Ro(o2, e2, t2) {
  var c3;
  let n = false;
  const s2 = o2.state.selection instanceof CellSelection;
  if (!s2) {
    const a3 = o2.state.doc.slice(
      o2.state.selection.from,
      o2.state.selection.to,
      false
    ).content, l2 = [];
    for (let d = 0; d < a3.childCount; d++)
      l2.push(a3.child(d));
    n = l2.find(
      (d) => d.type.isInGroup("bnBlock") || d.type.name === "blockGroup" || d.type.spec.group === "blockContent"
    ) === void 0, n && (e2 = a3);
  }
  let r4;
  const i3 = ve(
    o2.state.schema,
    t2
  );
  if (s2) {
    ((c3 = e2.firstChild) == null ? void 0 : c3.type.name) === "table" && (e2 = e2.firstChild.content);
    const a3 = gt(
      e2,
      t2.schema.inlineContentSchema,
      t2.schema.styleSchema
    );
    r4 = `<table>${i3.exportInlineContent(
      a3,
      {}
    )}</table>`;
  } else if (n) {
    const a3 = F2(
      e2,
      t2.schema.inlineContentSchema,
      t2.schema.styleSchema
    );
    r4 = i3.exportInlineContent(a3, {});
  } else {
    const a3 = Lt2(e2);
    r4 = i3.exportBlocks(a3, {});
  }
  return r4;
}
function Ae2(o2, e2) {
  "node" in o2.state.selection && o2.state.selection.node.type.spec.group === "blockContent" && e2.transact(
    (i3) => i3.setSelection(
      new NodeSelection(i3.doc.resolve(o2.state.selection.from - 1))
    )
  );
  const t2 = o2.serializeForClipboard(
    o2.state.selection.content()
  ).dom.innerHTML, n = o2.state.selection.content().content, s2 = Ro(
    o2,
    n,
    e2
  ), r4 = Se(s2);
  return { clipboardHTML: t2, externalHTML: s2, markdown: r4 };
}
var de2 = () => {
  const o2 = window.getSelection();
  if (!o2 || o2.isCollapsed)
    return true;
  let e2 = o2.focusNode;
  for (; e2; ) {
    if (e2 instanceof HTMLElement && e2.getAttribute("contenteditable") === "false")
      return true;
    e2 = e2.parentElement;
  }
  return false;
};
var ue2 = (o2, e2, t2) => {
  t2.preventDefault(), t2.clipboardData.clearData();
  const { clipboardHTML: n, externalHTML: s2, markdown: r4 } = Ae2(
    e2,
    o2
  );
  t2.clipboardData.setData("blocknote/html", n), t2.clipboardData.setData("text/html", s2), t2.clipboardData.setData("text/plain", r4);
};
var jo = (o2) => Extension.create({
  name: "copyToClipboard",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        props: {
          handleDOMEvents: {
            copy(e2, t2) {
              return de2() || ue2(o2, e2, t2), true;
            },
            cut(e2, t2) {
              return de2() || (ue2(o2, e2, t2), e2.editable && e2.dispatch(e2.state.tr.deleteSelection())), true;
            },
            // This is for the use-case in which only a block without content
            // is selected, e.g. an image block, and dragged (not using the
            // drag handle).
            dragstart(e2, t2) {
              if (!("node" in e2.state.selection) || e2.state.selection.node.type.spec.group !== "blockContent")
                return;
              o2.transact(
                (i3) => i3.setSelection(
                  new NodeSelection(
                    i3.doc.resolve(e2.state.selection.from - 1)
                  )
                )
              ), t2.preventDefault(), t2.dataTransfer.clearData();
              const { clipboardHTML: n, externalHTML: s2, markdown: r4 } = Ae2(e2, o2);
              return t2.dataTransfer.setData("blocknote/html", n), t2.dataTransfer.setData("text/html", s2), t2.dataTransfer.setData("text/plain", r4), true;
            }
          }
        }
      })
    ];
  }
});
var Wo = Extension.create({
  name: "blockBackgroundColor",
  addGlobalAttributes() {
    return [
      {
        types: ["tableCell", "tableHeader"],
        attributes: {
          backgroundColor: Eo()
        }
      }
    ];
  }
});
var Ko = Node3.create({
  name: "hardBreak",
  inline: true,
  group: "inline",
  selectable: false,
  linebreakReplacement: true,
  priority: 10,
  parseHTML() {
    return [{ tag: "br" }];
  },
  renderHTML({ HTMLAttributes: o2 }) {
    return ["br", mergeAttributes(this.options.HTMLAttributes, o2)];
  },
  renderText() {
    return `
`;
  }
});
var J3 = (o2, e2) => {
  const t2 = o2.resolve(e2), n = t2.index();
  if (n === 0)
    return;
  const s2 = t2.posAtIndex(n - 1);
  return It(
    o2.resolve(s2)
  );
};
var _e2 = (o2, e2) => {
  for (; e2.childContainer; ) {
    const t2 = e2.childContainer.node, n = o2.resolve(e2.childContainer.beforePos + 1).posAtIndex(t2.childCount - 1);
    e2 = It(o2.resolve(n));
  }
  return e2;
};
var Jo = (o2, e2) => o2.isBlockContainer && o2.blockContent.node.type.spec.content === "inline*" && o2.blockContent.node.childCount > 0 && e2.isBlockContainer && e2.blockContent.node.type.spec.content === "inline*";
var qo = (o2, e2, t2, n) => {
  if (!n.isBlockContainer)
    throw new Error(
      `Attempted to merge block at position ${n.bnBlock.beforePos} into previous block at position ${t2.bnBlock.beforePos}, but next block is not a block container`
    );
  if (n.childContainer) {
    const s2 = o2.doc.resolve(
      n.childContainer.beforePos + 1
    ), r4 = o2.doc.resolve(
      n.childContainer.afterPos - 1
    ), i3 = s2.blockRange(r4);
    if (e2) {
      const c3 = o2.doc.resolve(n.bnBlock.beforePos);
      o2.tr.lift(i3, c3.depth);
    }
  }
  if (e2) {
    if (!t2.isBlockContainer)
      throw new Error(
        `Attempted to merge block at position ${n.bnBlock.beforePos} into previous block at position ${t2.bnBlock.beforePos}, but previous block is not a block container`
      );
    e2(
      o2.tr.delete(
        t2.blockContent.afterPos - 1,
        n.blockContent.beforePos + 1
      )
    );
  }
  return true;
};
var pe2 = (o2) => ({
  state: e2,
  dispatch: t2
}) => {
  const n = e2.doc.resolve(o2), s2 = It(n), r4 = J3(
    e2.doc,
    s2.bnBlock.beforePos
  );
  if (!r4)
    return false;
  const i3 = _e2(
    e2.doc,
    r4
  );
  return Jo(i3, s2) ? qo(e2, t2, i3, s2) : false;
};
var Yo = Extension.create({
  priority: 50,
  // TODO: The shortcuts need a refactor. Do we want to use a command priority
  //  design as there is now, or clump the logic into a single function?
  addKeyboardShortcuts() {
    const o2 = () => this.editor.commands.first(({ chain: n, commands: s2 }) => [
      // Deletes the selection if it's not empty.
      () => s2.deleteSelection(),
      // Undoes an input rule if one was triggered in the last editor state change.
      () => s2.undoInputRule(),
      // Reverts block content type to a paragraph if the selection is at the start of the block.
      () => s2.command(({ state: r4 }) => {
        const i3 = Tt(r4);
        if (!i3.isBlockContainer)
          return false;
        const c3 = r4.selection.from === i3.blockContent.beforePos + 1, a3 = i3.blockContent.node.type.name === "paragraph";
        return c3 && !a3 ? s2.command(
          ko(i3.bnBlock.beforePos, {
            type: "paragraph",
            props: {}
          })
        ) : false;
      }),
      // Removes a level of nesting if the block is indented if the selection is at the start of the block.
      () => s2.command(({ state: r4 }) => {
        const i3 = Tt(r4);
        if (!i3.isBlockContainer)
          return false;
        const { blockContent: c3 } = i3;
        return r4.selection.from === c3.beforePos + 1 ? s2.liftListItem("blockContainer") : false;
      }),
      // Merges block with the previous one if it isn't indented, and the selection is at the start of the
      // block. The target block for merging must contain inline content.
      () => s2.command(({ state: r4 }) => {
        const i3 = Tt(r4);
        if (!i3.isBlockContainer)
          return false;
        const { bnBlock: c3, blockContent: a3 } = i3, l2 = r4.selection.from === a3.beforePos + 1, d = r4.selection.empty, u2 = c3.beforePos;
        return l2 && d ? n().command(pe2(u2)).scrollIntoView().run() : false;
      }),
      () => s2.command(({ state: r4, tr: i3, dispatch: c3 }) => {
        const a3 = Tt(r4);
        if (!a3.isBlockContainer || !(i3.selection.from === a3.blockContent.beforePos + 1))
          return false;
        const d = i3.doc.resolve(a3.bnBlock.beforePos);
        if (d.nodeBefore || d.node().type.name !== "column")
          return false;
        const m2 = i3.doc.resolve(a3.bnBlock.beforePos), f6 = i3.doc.resolve(m2.before()), k3 = f6.before();
        if (c3) {
          const g = i3.doc.slice(
            a3.bnBlock.beforePos,
            a3.bnBlock.afterPos
          ).content;
          i3.delete(
            a3.bnBlock.beforePos,
            a3.bnBlock.afterPos
          ), f6.index() === 0 ? (W2(i3, k3), i3.insert(k3, g), i3.setSelection(
            TextSelection.near(i3.doc.resolve(k3))
          )) : (i3.insert(f6.pos - 1, g), i3.setSelection(
            TextSelection.near(i3.doc.resolve(f6.pos - 1))
          ), W2(i3, k3));
        }
        return true;
      }),
      // Deletes the current block if it's an empty block with inline content,
      // and moves the selection to the previous block.
      () => s2.command(({ state: r4 }) => {
        const i3 = Tt(r4);
        if (!i3.isBlockContainer)
          return false;
        if (i3.blockContent.node.childCount === 0 && i3.blockContent.node.type.spec.content === "inline*") {
          const a3 = J3(
            r4.doc,
            i3.bnBlock.beforePos
          );
          if (!a3 || !a3.isBlockContainer)
            return false;
          let l2 = n();
          if (a3.blockContent.node.type.spec.content === "tableRow+") {
            const f6 = i3.bnBlock.beforePos - 1 - 1 - 1 - 1 - 1;
            l2 = l2.setTextSelection(
              f6
            );
          } else if (a3.blockContent.node.type.spec.content === "") {
            const d = a3.blockContent.afterPos - a3.blockContent.node.nodeSize;
            l2 = l2.setNodeSelection(
              d
            );
          } else {
            const d = a3.blockContent.afterPos - a3.blockContent.node.nodeSize;
            l2 = l2.setTextSelection(d);
          }
          return l2.deleteRange({
            from: i3.bnBlock.beforePos,
            to: i3.bnBlock.afterPos
          }).scrollIntoView().run();
        }
        return false;
      }),
      // Deletes previous block if it contains no content and isn't a table,
      // when the selection is empty and at the start of the block. Moves the
      // current block into the deleted block's place.
      () => s2.command(({ state: r4 }) => {
        const i3 = Tt(r4);
        if (!i3.isBlockContainer)
          throw new Error("todo");
        const c3 = r4.selection.from === i3.blockContent.beforePos + 1, a3 = r4.selection.empty, l2 = J3(
          r4.doc,
          i3.bnBlock.beforePos
        );
        if (l2 && c3 && a3) {
          const d = _e2(
            r4.doc,
            l2
          );
          if (!d.isBlockContainer)
            throw new Error("todo");
          if (d.blockContent.node.type.spec.content === "" || d.blockContent.node.type.spec.content === "inline*" && d.blockContent.node.childCount === 0)
            return n().cut(
              {
                from: i3.bnBlock.beforePos,
                to: i3.bnBlock.afterPos
              },
              d.bnBlock.afterPos
            ).deleteRange({
              from: d.bnBlock.beforePos,
              to: d.bnBlock.afterPos
            }).run();
        }
        return false;
      })
    ]), e2 = () => this.editor.commands.first(({ commands: n }) => [
      // Deletes the selection if it's not empty.
      () => n.deleteSelection(),
      // Merges block with the next one (at the same nesting level or lower),
      // if one exists, the block has no children, and the selection is at the
      // end of the block.
      () => n.command(({ state: s2 }) => {
        const r4 = Tt(s2);
        if (!r4.isBlockContainer)
          return false;
        const {
          bnBlock: i3,
          blockContent: c3,
          childContainer: a3
        } = r4, { depth: l2 } = s2.doc.resolve(i3.beforePos), d = i3.afterPos === s2.doc.nodeSize - 3, u2 = s2.selection.from === c3.afterPos - 1, p4 = s2.selection.empty;
        if (!d && u2 && p4 && !(a3 !== void 0)) {
          let f6 = l2, k3 = i3.afterPos + 1, g = s2.doc.resolve(k3).depth;
          for (; g < f6; )
            f6 = g, k3 += 2, g = s2.doc.resolve(k3).depth;
          return n.command(pe2(k3 - 1));
        }
        return false;
      })
    ]), t2 = (n = false) => this.editor.commands.first(({ commands: s2, tr: r4 }) => [
      // Removes a level of nesting if the block is empty & indented, while the selection is also empty & at the start
      // of the block.
      () => s2.command(({ state: i3 }) => {
        const c3 = Tt(i3);
        if (!c3.isBlockContainer)
          return false;
        const { bnBlock: a3, blockContent: l2 } = c3, { depth: d } = i3.doc.resolve(a3.beforePos), u2 = i3.selection.$anchor.parentOffset === 0, p4 = i3.selection.anchor === i3.selection.head, m2 = l2.node.childCount === 0, f6 = d > 1;
        return u2 && p4 && m2 && f6 ? s2.liftListItem("blockContainer") : false;
      }),
      // Creates a hard break if block is configured to do so.
      () => s2.command(({ state: i3 }) => {
        var l2;
        const c3 = Tt(i3), a3 = ((l2 = this.options.editor.schema.blockSchema[c3.blockNoteType].meta) == null ? void 0 : l2.hardBreakShortcut) ?? "shift+enter";
        if (a3 === "none")
          return false;
        if (
          // If shortcut is not configured, or is configured as "shift+enter",
          // create a hard break for shift+enter, but not for enter.
          a3 === "shift+enter" && n || // If shortcut is configured as "enter", create a hard break for
          // both enter and shift+enter.
          a3 === "enter"
        ) {
          const d = r4.storedMarks || r4.selection.$head.marks().filter(
            (u2) => this.editor.extensionManager.splittableMarks.includes(
              u2.type.name
            )
          );
          return r4.insert(
            r4.selection.head,
            r4.doc.type.schema.nodes.hardBreak.create()
          ).ensureMarks(d), true;
        }
        return false;
      }),
      // Creates a new block and moves the selection to it if the current one is empty, while the selection is also
      // empty & at the start of the block.
      () => s2.command(({ state: i3, dispatch: c3 }) => {
        const a3 = Tt(i3);
        if (!a3.isBlockContainer)
          return false;
        const { bnBlock: l2, blockContent: d } = a3, u2 = i3.selection.$anchor.parentOffset === 0, p4 = i3.selection.anchor === i3.selection.head, m2 = d.node.childCount === 0;
        if (u2 && p4 && m2) {
          const f6 = l2.afterPos, k3 = f6 + 2;
          if (c3) {
            const g = i3.schema.nodes.blockContainer.createAndFill();
            i3.tr.insert(f6, g).scrollIntoView(), i3.tr.setSelection(
              new TextSelection(i3.doc.resolve(k3))
            );
          }
          return true;
        }
        return false;
      }),
      // Splits the current block, moving content inside that's after the cursor to a new text block below. Also
      // deletes the selection beforehand, if it's not empty.
      () => s2.command(({ state: i3, chain: c3 }) => {
        const a3 = Tt(i3);
        if (!a3.isBlockContainer)
          return false;
        const { blockContent: l2 } = a3, d = i3.selection.$anchor.parentOffset === 0;
        return l2.node.childCount === 0 ? false : (c3().deleteSelection().command(
          So(
            i3.selection.from,
            d,
            d
          )
        ).run(), true);
      })
    ]);
    return {
      Backspace: o2,
      Delete: e2,
      Enter: () => t2(),
      "Shift-Enter": () => t2(true),
      // Always returning true for tab key presses ensures they're not captured by the browser. Otherwise, they blur the
      // editor since the browser will try to use tab for keyboard navigation.
      Tab: () => {
        var n, s2;
        return this.options.tabBehavior !== "prefer-indent" && ((n = this.options.editor.getExtension(yo2)) != null && n.store.state || ((s2 = this.options.editor.getExtension(I2)) == null ? void 0 : s2.store.state) !== void 0) ? false : Te2(this.options.editor);
      },
      "Shift-Tab": () => {
        var n, s2;
        return this.options.tabBehavior !== "prefer-indent" && ((n = this.options.editor.getExtension(yo2)) != null && n.store.state || ((s2 = this.options.editor.getExtension(I2)) == null ? void 0 : s2.store.state) !== void 0) ? false : this.editor.commands.liftListItem("blockContainer");
      },
      "Shift-Mod-ArrowUp": () => (this.options.editor.moveBlocksUp(), true),
      "Shift-Mod-ArrowDown": () => (this.options.editor.moveBlocksDown(), true),
      "Mod-z": () => this.options.editor.undo(),
      "Mod-y": () => this.options.editor.redo(),
      "Shift-Mod-z": () => this.options.editor.redo()
    };
  }
});
var Qo = Mark2.create({
  name: "insertion",
  inclusive: false,
  excludes: "deletion modification insertion",
  addAttributes() {
    return {
      id: { default: null, validate: "number" }
      // note: validate is supported in prosemirror but not in tiptap, so this doesn't actually work (considered not critical)
    };
  },
  extendMarkSchema(o2) {
    return o2.name !== "insertion" ? {} : {
      blocknoteIgnore: true,
      inclusive: false,
      toDOM(e2, t2) {
        return [
          "ins",
          {
            "data-id": String(e2.attrs.id),
            "data-inline": String(t2),
            ...!t2 && { style: "display: contents" }
            // changed to "contents" to make this work for table rows
          },
          0
        ];
      },
      parseDOM: [
        {
          tag: "ins",
          getAttrs(e2) {
            return e2.dataset.id ? {
              id: parseInt(e2.dataset.id, 10)
            } : false;
          }
        }
      ]
    };
  }
});
var Xo = Mark2.create({
  name: "deletion",
  inclusive: false,
  excludes: "insertion modification deletion",
  addAttributes() {
    return {
      id: { default: null, validate: "number" }
      // note: validate is supported in prosemirror but not in tiptap
    };
  },
  extendMarkSchema(o2) {
    return o2.name !== "deletion" ? {} : {
      blocknoteIgnore: true,
      inclusive: false,
      // attrs: {
      //   id: { validate: "number" },
      // },
      toDOM(e2, t2) {
        return [
          "del",
          {
            "data-id": String(e2.attrs.id),
            "data-inline": String(t2),
            ...!t2 && { style: "display: contents" }
            // changed to "contents" to make this work for table rows
          },
          0
        ];
      },
      parseDOM: [
        {
          tag: "del",
          getAttrs(e2) {
            return e2.dataset.id ? {
              id: parseInt(e2.dataset.id, 10)
            } : false;
          }
        }
      ]
    };
  }
});
var Zo = Mark2.create({
  name: "modification",
  inclusive: false,
  excludes: "deletion insertion",
  addAttributes() {
    return {
      id: { default: null, validate: "number" },
      type: { validate: "string" },
      attrName: { default: null, validate: "string|null" },
      previousValue: { default: null },
      newValue: { default: null }
    };
  },
  extendMarkSchema(o2) {
    return o2.name !== "modification" ? {} : {
      blocknoteIgnore: true,
      inclusive: false,
      // attrs: {
      //   id: { validate: "number" },
      //   type: { validate: "string" },
      //   attrName: { default: null, validate: "string|null" },
      //   previousValue: { default: null },
      //   newValue: { default: null },
      // },
      toDOM(e2, t2) {
        return [
          t2 ? "span" : "div",
          {
            "data-type": "modification",
            "data-id": String(e2.attrs.id),
            "data-mod-type": e2.attrs.type,
            "data-mod-prev-val": JSON.stringify(e2.attrs.previousValue),
            // TODO: Try to serialize marks with toJSON?
            "data-mod-new-val": JSON.stringify(e2.attrs.newValue)
          },
          0
        ];
      },
      parseDOM: [
        {
          tag: "span[data-type='modification']",
          getAttrs(e2) {
            return e2.dataset.id ? {
              id: parseInt(e2.dataset.id, 10),
              type: e2.dataset.modType,
              previousValue: e2.dataset.modPrevVal,
              newValue: e2.dataset.modNewVal
            } : false;
          }
        },
        {
          tag: "div[data-type='modification']",
          getAttrs(e2) {
            return e2.dataset.id ? {
              id: parseInt(e2.dataset.id, 10),
              type: e2.dataset.modType,
              previousValue: e2.dataset.modPrevVal
            } : false;
          }
        }
      ]
    };
  }
});
var en2 = Extension.create({
  name: "textAlignment",
  addGlobalAttributes() {
    return [
      {
        // Generally text alignment is handled through props using the custom
        // blocks API. Tables are the only blocks that are created as TipTap
        // nodes and ported to blocks, so we need to add text alignment in a
        // separate extension.
        types: ["tableCell", "tableHeader"],
        attributes: {
          textAlignment: {
            default: "left",
            parseHTML: (o2) => o2.getAttribute("data-text-alignment"),
            renderHTML: (o2) => o2.textAlignment === "left" ? {} : {
              "data-text-alignment": o2.textAlignment
            }
          }
        }
      }
    ];
  }
});
var tn2 = Extension.create({
  name: "blockTextColor",
  addGlobalAttributes() {
    return [
      {
        types: ["table", "tableCell", "tableHeader"],
        attributes: {
          textColor: xo()
        }
      }
    ];
  }
});
var on2 = {
  blockColor: "data-block-color",
  blockStyle: "data-block-style",
  id: "data-id",
  depth: "data-depth",
  depthChange: "data-depth-change"
};
var nn2 = Node3.create({
  name: "blockContainer",
  group: "blockGroupChild bnBlock",
  // A block always contains content, and optionally a blockGroup which contains nested blocks
  content: "blockContent blockGroup?",
  // Ensures content-specific keyboard handlers trigger first.
  priority: 50,
  defining: true,
  marks: "insertion modification deletion",
  parseHTML() {
    return [
      {
        tag: "div[data-node-type=" + this.name + "]",
        getAttrs: (o2) => {
          if (typeof o2 == "string")
            return false;
          const e2 = {};
          for (const [t2, n] of Object.entries(on2))
            o2.getAttribute(n) && (e2[t2] = o2.getAttribute(n));
          return e2;
        }
      },
      // Ignore `blockOuter` divs, but parse the `blockContainer` divs inside them.
      {
        tag: 'div[data-node-type="blockOuter"]',
        skip: true
      }
    ];
  },
  renderHTML({ HTMLAttributes: o2 }) {
    var s2;
    const e2 = document.createElement("div");
    e2.className = "bn-block-outer", e2.setAttribute("data-node-type", "blockOuter");
    for (const [r4, i3] of Object.entries(o2))
      r4 !== "class" && e2.setAttribute(r4, i3);
    const t2 = {
      ...((s2 = this.options.domAttributes) == null ? void 0 : s2.block) || {},
      ...o2
    }, n = document.createElement("div");
    n.className = D2("bn-block", t2.class), n.setAttribute("data-node-type", this.name);
    for (const [r4, i3] of Object.entries(t2))
      r4 !== "class" && n.setAttribute(r4, i3);
    return e2.appendChild(n), {
      dom: e2,
      contentDOM: n
    };
  }
});
var sn2 = Node3.create({
  name: "blockGroup",
  group: "childContainer",
  content: "blockGroupChild+",
  marks: "deletion insertion modification",
  parseHTML() {
    return [
      {
        tag: "div",
        getAttrs: (o2) => typeof o2 == "string" ? false : o2.getAttribute("data-node-type") === "blockGroup" ? null : false
      }
    ];
  },
  renderHTML({ HTMLAttributes: o2 }) {
    var n;
    const e2 = {
      ...((n = this.options.domAttributes) == null ? void 0 : n.blockGroup) || {},
      ...o2
    }, t2 = document.createElement("div");
    t2.className = D2(
      "bn-block-group",
      e2.class
    ), t2.setAttribute("data-node-type", "blockGroup");
    for (const [s2, r4] of Object.entries(e2))
      s2 !== "class" && t2.setAttribute(s2, r4);
    return {
      dom: t2,
      contentDOM: t2
    };
  }
});
var rn2 = Node3.create({
  name: "doc",
  topNode: true,
  content: "blockGroup",
  marks: "insertion modification deletion"
});
var an2 = a(
  ({ options: o2 }) => ({
    key: "collaboration",
    blockNoteExtensions: [
      fo2(o2),
      te(o2),
      F3(o2),
      $5(),
      go2(o2)
    ]
  })
);
var fe2 = false;
function cn2(o2, e2) {
  const t2 = [
    extensions_exports.ClipboardTextSerializer,
    extensions_exports.Commands,
    extensions_exports.Editable,
    extensions_exports.FocusEvents,
    extensions_exports.Tabindex,
    Gapcursor,
    Q.configure({
      // everything from bnBlock group (nodes that represent a BlockNote block should have an id)
      types: ["blockContainer", "columnList", "column"],
      setIdAttribute: e2.setIdAttribute
    }),
    Ko,
    Text2,
    // marks:
    Qo,
    Xo,
    Zo,
    Link.extend({
      inclusive: false
    }).configure({
      defaultProtocol: Co,
      // only call this once if we have multiple editors installed. Or fix https://github.com/ueberdosis/tiptap/issues/5450
      protocols: fe2 ? [] : ko2
    }),
    ...Object.values(o2.schema.styleSpecs).map((n) => n.implementation.mark.configure({
      editor: o2
    })),
    tn2,
    Wo,
    en2,
    // make sure escape blurs editor, so that we can tab to other elements in the host page (accessibility)
    Extension.create({
      name: "OverrideEscape",
      addKeyboardShortcuts: () => ({
        Escape: () => {
          var n;
          return (n = o2.getExtension(_n)) != null && n.shown() ? false : (o2.blur(), true);
        }
      })
    }),
    // nodes
    rn2,
    nn2.configure({
      editor: o2,
      domAttributes: e2.domAttributes
    }),
    Yo.configure({
      editor: o2,
      tabBehavior: e2.tabBehavior
    }),
    sn2.configure({
      domAttributes: e2.domAttributes
    }),
    ...Object.values(o2.schema.inlineContentSpecs).filter((n) => n.config !== "link" && n.config !== "text").map((n) => n.implementation.node.configure({
      editor: o2
    })),
    ...Object.values(o2.schema.blockSpecs).flatMap((n) => [
      // the node extension implementations
      ..."node" in n.implementation ? [
        n.implementation.node.configure({
          editor: o2,
          domAttributes: e2.domAttributes
        })
      ] : []
    ]),
    jo(o2),
    Go(
      o2,
      e2.pasteHandler || ((n) => n.defaultPasteHandler())
    ),
    wo3(o2)
  ];
  return fe2 = true, t2;
}
function ln2(o2, e2) {
  const t2 = [
    po2(),
    wo(e2),
    I2(e2),
    yo2(e2),
    vo(e2),
    So2(),
    xo2(e2),
    f2(e2),
    Bo2(e2),
    _n(e2),
    ...e2.trailingBlock !== false ? [Po2()] : []
  ];
  return e2.collaboration ? t2.push(an2(e2.collaboration)) : t2.push(bo2()), "table" in o2.schema.blockSpecs && t2.push(To2(e2)), e2.animations !== false && t2.push(Eo2()), t2;
}
var dn2 = class {
  constructor(e2, t2) {
    h6(this, "disabledExtensions", /* @__PURE__ */ new Set());
    h6(this, "extensions", []);
    h6(this, "abortMap", /* @__PURE__ */ new Map());
    h6(this, "extensionFactories", /* @__PURE__ */ new Map());
    h6(this, "extensionPlugins", /* @__PURE__ */ new Map());
    this.editor = e2, this.options = t2, e2.onMount(() => {
      for (const n of this.extensions)
        if (n.mount) {
          const s2 = new window.AbortController(), r4 = n.mount({
            dom: e2.prosemirrorView.dom,
            root: e2.prosemirrorView.root,
            signal: s2.signal
          });
          r4 && s2.signal.addEventListener("abort", () => {
            r4();
          }), this.abortMap.set(n, s2);
        }
    }), e2.onUnmount(() => {
      for (const [n, s2] of this.abortMap.entries())
        this.abortMap.delete(n), s2.abort();
    }), this.disabledExtensions = new Set(t2.disableExtensions || []);
    for (const n of ln2(this.editor, this.options))
      this.addExtension(n);
    for (const n of this.options.extensions ?? [])
      this.addExtension(n);
    for (const n of Object.values(this.editor.schema.blockSpecs))
      for (const s2 of n.extensions ?? [])
        this.addExtension(s2);
  }
  /**
   * Register one or more extensions to the editor after the editor is initialized.
   *
   * This allows users to switch on & off extensions "at runtime".
   */
  registerExtension(e2) {
    var r4;
    const t2 = [].concat(e2).filter(Boolean);
    if (!t2.length) {
      console.warn("No extensions found to register", e2);
      return;
    }
    const n = t2.map((i3) => this.addExtension(i3)).filter(Boolean), s2 = /* @__PURE__ */ new Set();
    for (const i3 of n)
      i3 != null && i3.tiptapExtensions && console.warn(
        `Extension ${i3.key} has tiptap extensions, but these cannot be changed after initializing the editor. Please separate the extension into multiple extensions if you want to add them, or re-initialize the editor.`,
        i3
      ), (r4 = i3 == null ? void 0 : i3.inputRules) != null && r4.length && console.warn(
        `Extension ${i3.key} has input rules, but these cannot be changed after initializing the editor. Please separate the extension into multiple extensions if you want to add them, or re-initialize the editor.`,
        i3
      ), this.getProsemirrorPluginsFromExtension(i3).plugins.forEach(
        (c3) => {
          s2.add(c3);
        }
      );
    this.updatePlugins((i3) => [...i3, ...s2]);
  }
  /**
   * Register an extension to the editor
   * @param extension - The extension to register
   * @returns The extension instance
   */
  addExtension(e2) {
    let t2;
    if (typeof e2 == "function" ? t2 = e2({ editor: this.editor }) : t2 = e2, !(!t2 || this.disabledExtensions.has(t2.key))) {
      if (typeof e2 == "function") {
        const n = t2[r];
        typeof n == "function" && this.extensionFactories.set(n, t2);
      }
      if (this.extensions.push(t2), t2.blockNoteExtensions)
        for (const n of t2.blockNoteExtensions)
          this.addExtension(n);
      return t2;
    }
  }
  /**
   * Resolve an extension or a list of extensions into a list of extension instances
   * @param toResolve - The extension or list of extensions to resolve
   * @returns A list of extension instances
   */
  resolveExtensions(e2) {
    const t2 = [];
    if (typeof e2 == "function") {
      const n = this.extensionFactories.get(e2);
      n && t2.push(n);
    } else if (Array.isArray(e2))
      for (const n of e2)
        t2.push(...this.resolveExtensions(n));
    else if (typeof e2 == "object" && "key" in e2)
      t2.push(e2);
    else if (typeof e2 == "string") {
      const n = this.extensions.find((s2) => s2.key === e2);
      n && t2.push(n);
    }
    return t2;
  }
  /**
   * Unregister an extension from the editor
   * @param toUnregister - The extension to unregister
   * @returns void
   */
  unregisterExtension(e2) {
    var r4;
    const t2 = this.resolveExtensions(e2);
    if (!t2.length) {
      console.warn("No extensions found to unregister", e2);
      return;
    }
    let n = false;
    const s2 = /* @__PURE__ */ new Set();
    for (const i3 of t2) {
      this.extensions = this.extensions.filter((a3) => a3 !== i3), this.extensionFactories.forEach((a3, l2) => {
        a3 === i3 && this.extensionFactories.delete(l2);
      }), (r4 = this.abortMap.get(i3)) == null || r4.abort(), this.abortMap.delete(i3);
      const c3 = this.extensionPlugins.get(i3);
      c3 == null || c3.forEach((a3) => {
        s2.add(a3);
      }), this.extensionPlugins.delete(i3), i3.tiptapExtensions && !n && (n = true, console.warn(
        `Extension ${i3.key} has tiptap extensions, but they will not be removed. Please separate the extension into multiple extensions if you want to remove them, or re-initialize the editor.`,
        e2
      ));
    }
    this.updatePlugins(
      (i3) => i3.filter((c3) => !s2.has(c3))
    );
  }
  /**
   * Allows resetting the current prosemirror state's plugins
   * @param update - A function that takes the current plugins and returns the new plugins
   * @returns void
   */
  updatePlugins(e2) {
    const t2 = this.editor.prosemirrorState, n = t2.reconfigure({
      plugins: e2(t2.plugins.slice())
    });
    this.editor.prosemirrorView.updateState(n);
  }
  /**
   * Get all the extensions that are registered to the editor
   */
  getTiptapExtensions() {
    var s2;
    const e2 = cn2(
      this.editor,
      this.options
    ).filter((r4) => !this.disabledExtensions.has(r4.name)), t2 = P2(this.extensions), n = /* @__PURE__ */ new Map();
    for (const r4 of this.extensions) {
      r4.tiptapExtensions && e2.push(...r4.tiptapExtensions);
      const i3 = t2(r4.key), { plugins: c3, inputRules: a3 } = this.getProsemirrorPluginsFromExtension(r4);
      c3.length && e2.push(
        Extension.create({
          name: r4.key,
          priority: i3,
          addProseMirrorPlugins: () => c3
        })
      ), a3.length && (n.has(i3) || n.set(i3, []), n.get(i3).push(...a3));
    }
    e2.push(
      Extension.create({
        name: "blocknote-input-rules",
        addProseMirrorPlugins() {
          const r4 = [];
          return Array.from(n.keys()).sort().reverse().forEach((i3) => {
            r4.push(...n.get(i3));
          }), [inputRules({ rules: r4 })];
        }
      })
    );
    for (const r4 of ((s2 = this.options._tiptapOptions) == null ? void 0 : s2.extensions) ?? [])
      e2.push(r4);
    return e2;
  }
  /**
   * This maps a blocknote extension into an array of Prosemirror plugins if it has any of the following:
   * - plugins
   * - keyboard shortcuts
   * - input rules
   */
  getProsemirrorPluginsFromExtension(e2) {
    var s2, r4, i3;
    const t2 = [...e2.prosemirrorPlugins ?? []], n = [];
    return !((s2 = e2.prosemirrorPlugins) != null && s2.length) && !Object.keys(e2.keyboardShortcuts || {}).length && !((r4 = e2.inputRules) != null && r4.length) ? { plugins: t2, inputRules: n } : (this.extensionPlugins.set(e2, t2), (i3 = e2.inputRules) != null && i3.length && n.push(
      ...e2.inputRules.map((c3) => new InputRule2(c3.find, (a3, l2, d, u2) => {
        const p4 = c3.replace({
          match: l2,
          range: { from: d, to: u2 },
          editor: this.editor
        });
        if (p4) {
          const m2 = this.editor.getTextCursorPosition();
          if (this.editor.schema.blockSchema[m2.block.type].content !== "inline")
            return null;
          const f6 = Ot(a3.tr), k3 = a3.tr.deleteRange(d, u2);
          return K4(k3, f6.bnBlock.beforePos, p4), k3;
        }
        return null;
      }))
    ), Object.keys(e2.keyboardShortcuts || {}).length && t2.push(
      keymap(
        Object.fromEntries(
          Object.entries(e2.keyboardShortcuts).map(([c3, a3]) => [
            c3,
            () => a3({ editor: this.editor })
          ])
        )
      )
    ), { plugins: t2, inputRules: n });
  }
  /**
   * Get all extensions
   */
  getExtensions() {
    return new Map(
      this.extensions.map((e2) => [e2.key, e2])
    );
  }
  getExtension(e2) {
    if (typeof e2 == "string") {
      const t2 = this.extensions.find((n) => n.key === e2);
      return t2 || void 0;
    } else if (typeof e2 == "function") {
      const t2 = this.extensionFactories.get(e2);
      return t2 || void 0;
    }
    throw new Error(`Invalid extension type: ${typeof e2}`);
  }
  /**
   * Check if an extension exists
   */
  hasExtension(e2) {
    return typeof e2 == "string" ? this.extensions.some((t2) => t2.key === e2) : typeof e2 == "object" && "key" in e2 ? this.extensions.some((t2) => t2.key === e2.key) : typeof e2 == "function" ? this.extensionFactories.has(e2) : false;
  }
};
function un2(o2, e2) {
  let { $from: t2, $to: n } = e2;
  if (t2.pos > t2.start() && t2.pos < o2.content.size) {
    const s2 = o2.textBetween(t2.pos, t2.pos + 1);
    if (/^[\w\p{P}]$/u.test(s2)) {
      const i3 = o2.textBetween(t2.start(), t2.pos).match(/[\w\p{P}]+$/u);
      i3 && (t2 = o2.resolve(t2.pos - i3[0].length));
    }
  }
  if (n.pos < n.end() && n.pos > 0) {
    const s2 = o2.textBetween(n.pos - 1, n.pos);
    if (/^[\w\p{P}]$/u.test(s2)) {
      const i3 = o2.textBetween(n.pos, n.end()).match(/^[\w\p{P}]+/u);
      i3 && (n = o2.resolve(n.pos + i3[0].length));
    }
  }
  return { $from: t2, $to: n, from: t2.pos, to: n.pos };
}
function pn2(o2) {
  const e2 = ht(o2);
  if (o2.selection.empty || "node" in o2.selection)
    return;
  const t2 = o2.doc.resolve(
    Y2(o2.doc, o2.selection.from).posBeforeNode
  ), n = o2.doc.resolve(
    Y2(o2.doc, o2.selection.to).posBeforeNode
  ), s2 = (l2, d) => {
    const u2 = t2.posAtIndex(l2, d), p4 = o2.doc.resolve(u2).nodeAfter;
    if (!p4)
      throw new Error(
        `Error getting selection - node not found at position ${u2}`
      );
    return L(p4, e2);
  }, r4 = [], i3 = t2.sharedDepth(n.pos), c3 = t2.index(i3), a3 = n.index(i3);
  if (t2.depth > i3) {
    r4.push(L(t2.nodeAfter, e2));
    for (let l2 = t2.depth; l2 > i3; l2--)
      if (t2.node(l2).type.isInGroup("childContainer")) {
        const u2 = t2.index(l2) + 1, p4 = t2.node(l2).childCount;
        for (let m2 = u2; m2 < p4; m2++)
          r4.push(s2(m2, l2));
      }
  } else
    r4.push(s2(c3, i3));
  for (let l2 = c3 + 1; l2 <= a3; l2++)
    r4.push(s2(l2, i3));
  if (r4.length === 0)
    throw new Error(
      `Error getting selection - selection doesn't span any blocks (${o2.selection})`
    );
  return {
    blocks: r4
  };
}
function fn2(o2, e2, t2) {
  const n = typeof e2 == "string" ? e2 : e2.id, s2 = typeof t2 == "string" ? t2 : t2.id, r4 = ht(o2), i3 = J(r4);
  if (n === s2)
    throw new Error(
      `Attempting to set selection with the same anchor and head blocks (id ${n})`
    );
  const c3 = Tt2(n, o2.doc);
  if (!c3)
    throw new Error(`Block with ID ${n} not found`);
  const a3 = Tt2(s2, o2.doc);
  if (!a3)
    throw new Error(`Block with ID ${s2} not found`);
  const l2 = Z(c3), d = Z(a3), u2 = i3.blockSchema[l2.blockNoteType], p4 = i3.blockSchema[d.blockNoteType];
  if (!l2.isBlockContainer || u2.content === "none")
    throw new Error(
      `Attempting to set selection anchor in block without content (id ${n})`
    );
  if (!d.isBlockContainer || p4.content === "none")
    throw new Error(
      `Attempting to set selection anchor in block without content (id ${s2})`
    );
  let m2, f6;
  if (u2.content === "table") {
    const k3 = TableMap.get(l2.blockContent.node);
    m2 = l2.blockContent.beforePos + k3.positionAt(0, 0, l2.blockContent.node) + 1 + 2;
  } else
    m2 = l2.blockContent.beforePos + 1;
  if (p4.content === "table") {
    const k3 = TableMap.get(d.blockContent.node), g = d.blockContent.beforePos + k3.positionAt(
      k3.height - 1,
      k3.width - 1,
      d.blockContent.node
    ) + 1, y3 = o2.doc.resolve(g).nodeAfter.nodeSize;
    f6 = g + y3 - 2;
  } else
    f6 = d.blockContent.afterPos - 1;
  o2.setSelection(TextSelection.create(o2.doc, m2, f6));
}
function hn2(o2, e2 = false) {
  const t2 = ht(o2), n = e2 ? un2(o2.doc, o2.selection) : o2.selection;
  let s2 = n.$from, r4 = n.$to;
  for (; r4.parentOffset >= r4.parent.nodeSize - 2 && r4.depth > 0; )
    r4 = o2.doc.resolve(r4.pos + 1);
  for (; r4.parentOffset === 0 && r4.depth > 0; )
    r4 = o2.doc.resolve(r4.pos - 1);
  for (; s2.parentOffset === 0 && s2.depth > 0; )
    s2 = o2.doc.resolve(s2.pos - 1);
  for (; s2.parentOffset >= s2.parent.nodeSize - 2 && s2.depth > 0; )
    s2 = o2.doc.resolve(s2.pos + 1);
  const i3 = Dt(
    o2.doc.slice(s2.pos, r4.pos, true),
    t2
  );
  return {
    _meta: {
      startPos: s2.pos,
      endPos: r4.pos
    },
    ...i3
  };
}
function mn2(o2) {
  const { bnBlock: e2 } = Ot(o2), t2 = ht(o2.doc), n = o2.doc.resolve(e2.beforePos), s2 = n.nodeBefore, r4 = o2.doc.resolve(e2.afterPos).nodeAfter;
  let i3;
  return n.depth > 1 && (i3 = n.node(), i3.type.isInGroup("bnBlock") || (i3 = n.node(n.depth - 1))), {
    block: L(e2.node, t2),
    prevBlock: s2 === null ? void 0 : L(s2, t2),
    nextBlock: r4 === null ? void 0 : L(r4, t2),
    parentBlock: i3 === void 0 ? void 0 : L(i3, t2)
  };
}
function De2(o2, e2, t2 = "start") {
  const n = typeof e2 == "string" ? e2 : e2.id, s2 = ht(o2.doc), r4 = J(s2), i3 = Tt2(n, o2.doc);
  if (!i3)
    throw new Error(`Block with ID ${n} not found`);
  const c3 = Z(i3), a3 = r4.blockSchema[c3.blockNoteType].content;
  if (c3.isBlockContainer) {
    const l2 = c3.blockContent;
    if (a3 === "none") {
      o2.setSelection(NodeSelection.create(o2.doc, l2.beforePos));
      return;
    }
    if (a3 === "inline")
      t2 === "start" ? o2.setSelection(
        TextSelection.create(o2.doc, l2.beforePos + 1)
      ) : o2.setSelection(
        TextSelection.create(o2.doc, l2.afterPos - 1)
      );
    else if (a3 === "table")
      t2 === "start" ? o2.setSelection(
        TextSelection.create(o2.doc, l2.beforePos + 4)
      ) : o2.setSelection(
        TextSelection.create(o2.doc, l2.afterPos - 4)
      );
    else
      throw new O(a3);
  } else {
    const l2 = t2 === "start" ? c3.childContainer.node.firstChild : c3.childContainer.node.lastChild;
    De2(o2, l2.attrs.id, t2);
  }
}
var kn2 = class {
  constructor(e2) {
    this.editor = e2;
  }
  /**
   * Gets a snapshot of the current selection. This contains all blocks (included nested blocks)
   * that the selection spans across.
   *
   * If the selection starts / ends halfway through a block, the returned data will contain the entire block.
   */
  getSelection() {
    return this.editor.transact((e2) => pn2(e2));
  }
  /**
   * Gets a snapshot of the current selection. This contains all blocks (included nested blocks)
   * that the selection spans across.
   *
   * If the selection starts / ends halfway through a block, the returned block will be
   * only the part of the block that is included in the selection.
   */
  getSelectionCutBlocks(e2 = false) {
    return this.editor.transact((t2) => hn2(t2, e2));
  }
  /**
   * Sets the selection to a range of blocks.
   * @param startBlock The identifier of the block that should be the start of the selection.
   * @param endBlock The identifier of the block that should be the end of the selection.
   */
  setSelection(e2, t2) {
    return this.editor.transact((n) => fn2(n, e2, t2));
  }
  /**
   * Gets a snapshot of the current text cursor position.
   * @returns A snapshot of the current text cursor position.
   */
  getTextCursorPosition() {
    return this.editor.transact((e2) => mn2(e2));
  }
  /**
   * Sets the text cursor position to the start or end of an existing block. Throws an error if the target block could
   * not be found.
   * @param targetBlock The identifier of an existing block that the text cursor should be moved to.
   * @param placement Whether the text cursor should be placed at the start or end of the block.
   */
  setTextCursorPosition(e2, t2 = "start") {
    return this.editor.transact(
      (n) => De2(n, e2, t2)
    );
  }
  /**
   * Gets the bounding box of the current selection.
   */
  getSelectionBoundingBox() {
    if (!this.editor.prosemirrorView)
      return;
    const { selection: e2 } = this.editor.prosemirrorState, { ranges: t2 } = e2, n = Math.min(...t2.map((r4) => r4.$from.pos)), s2 = Math.max(...t2.map((r4) => r4.$to.pos));
    if (isNodeSelection(e2)) {
      const r4 = this.editor.prosemirrorView.nodeDOM(n);
      if (r4)
        return r4.getBoundingClientRect();
    }
    return posToDOMRect(
      this.editor.prosemirrorView,
      n,
      s2
    ).toJSON();
  }
};
var gn2 = class {
  constructor(e2) {
    h6(this, "activeTransaction", null);
    h6(this, "isInCan", false);
    this.editor = e2;
  }
  /**
   * For any command that can be executed, you can check if it can be executed by calling `editor.can(command)`.
   * @example
   * ```ts
   * if (editor.can(editor.undo)) {
   *   // show button
   * } else {
   *   // hide button
   * }
   */
  can(e2) {
    try {
      return this.isInCan = true, e2();
    } finally {
      this.isInCan = false;
    }
  }
  /**
   * Execute a prosemirror command. This is mostly for backwards compatibility with older code.
   *
   * @note You should prefer the {@link transact} method when possible, as it will automatically handle the dispatching of the transaction and work across blocknote transactions.
   *
   * @example
   * ```ts
   * editor.exec((state, dispatch, view) => {
   *   dispatch(state.tr.insertText("Hello, world!"));
   * });
   * ```
   */
  exec(e2) {
    if (this.activeTransaction)
      throw new Error(
        "`exec` should not be called within a `transact` call, move the `exec` call outside of the `transact` call"
      );
    if (this.isInCan)
      return this.canExec(e2);
    const t2 = this.prosemirrorState, n = this.prosemirrorView;
    return e2(t2, (r4) => this.prosemirrorView.dispatch(r4), n);
  }
  /**
   * Check if a command can be executed. A command should return `false` if it is not valid in the current state.
   *
   * @example
   * ```ts
   * if (editor.canExec(command)) {
   *   // show button
   * } else {
   *   // hide button
   * }
   * ```
   */
  canExec(e2) {
    if (this.activeTransaction)
      throw new Error(
        "`canExec` should not be called within a `transact` call, move the `canExec` call outside of the `transact` call"
      );
    const t2 = this.prosemirrorState, n = this.prosemirrorView;
    return e2(t2, void 0, n);
  }
  /**
   * Execute a function within a "blocknote transaction".
   * All changes to the editor within the transaction will be grouped together, so that
   * we can dispatch them as a single operation (thus creating only a single undo step)
   *
   * @note There is no need to dispatch the transaction, as it will be automatically dispatched when the callback is complete.
   *
   * @example
   * ```ts
   * // All changes to the editor will be grouped together
   * editor.transact((tr) => {
   *   tr.insertText("Hello, world!");
   * // These two operations will be grouped together in a single undo step
   *   editor.transact((tr) => {
   *     tr.insertText("Hello, world!");
   *   });
   * });
   * ```
   */
  transact(e2) {
    if (this.activeTransaction)
      return e2(this.activeTransaction);
    try {
      this.activeTransaction = this.editor._tiptapEditor.state.tr;
      const t2 = e2(this.activeTransaction), n = this.activeTransaction;
      return this.activeTransaction = null, n && // Only dispatch if the transaction was actually modified in some way
      (n.docChanged || n.selectionSet || n.scrolledIntoView || n.storedMarksSet || !n.isGeneric) && this.prosemirrorView.dispatch(n), t2;
    } finally {
      this.activeTransaction = null;
    }
  }
  /**
   * Get the underlying prosemirror state
   * @note Prefer using `editor.transact` to read the current editor state, as that will ensure the state is up to date
   * @see https://prosemirror.net/docs/ref/#state.EditorState
   */
  get prosemirrorState() {
    if (this.activeTransaction)
      throw new Error(
        "`prosemirrorState` should not be called within a `transact` call, move the `prosemirrorState` call outside of the `transact` call or use `editor.transact` to read the current editor state"
      );
    return this.editor._tiptapEditor.state;
  }
  /**
   * Get the underlying prosemirror view
   * @see https://prosemirror.net/docs/ref/#view.EditorView
   */
  get prosemirrorView() {
    return this.editor._tiptapEditor.view;
  }
  isFocused() {
    var e2;
    return ((e2 = this.prosemirrorView) == null ? void 0 : e2.hasFocus()) || false;
  }
  focus() {
    var e2;
    (e2 = this.prosemirrorView) == null || e2.focus();
  }
  /**
   * Checks if the editor is currently editable, or if it's locked.
   * @returns True if the editor is editable, false otherwise.
   */
  get isEditable() {
    if (!this.editor._tiptapEditor) {
      if (!this.editor.headless)
        throw new Error("no editor, but also not headless?");
      return false;
    }
    return this.editor._tiptapEditor.isEditable === void 0 ? true : this.editor._tiptapEditor.isEditable;
  }
  /**
   * Makes the editor editable or locks it, depending on the argument passed.
   * @param editable True to make the editor editable, or false to lock it.
   */
  set isEditable(e2) {
    if (!this.editor._tiptapEditor) {
      if (!this.editor.headless)
        throw new Error("no editor, but also not headless?");
      return;
    }
    this.editor._tiptapEditor.options.editable !== e2 && this.editor._tiptapEditor.setEditable(e2);
  }
  /**
   * Undo the last action.
   */
  undo() {
    const e2 = this.editor.getExtension("yUndo");
    if (e2)
      return this.exec(e2.undoCommand);
    const t2 = this.editor.getExtension("history");
    if (t2)
      return this.exec(t2.undoCommand);
    throw new Error("No undo plugin found");
  }
  /**
   * Redo the last action.
   */
  redo() {
    const e2 = this.editor.getExtension("yUndo");
    if (e2)
      return this.exec(e2.redoCommand);
    const t2 = this.editor.getExtension("history");
    if (t2)
      return this.exec(t2.redoCommand);
    throw new Error("No redo plugin found");
  }
};
function bn2(o2, e2, t2, n = { updateSelection: true }) {
  let { from: s2, to: r4 } = typeof e2 == "number" ? { from: e2, to: e2 } : { from: e2.from, to: e2.to }, i3 = true, c3 = true, a3 = "";
  if (t2.forEach((l2) => {
    l2.check(), i3 && l2.isText && l2.marks.length === 0 ? a3 += l2.text : i3 = false, c3 = c3 ? l2.isBlock : false;
  }), s2 === r4 && c3) {
    const { parent: l2 } = o2.doc.resolve(s2);
    l2.isTextblock && !l2.type.spec.code && !l2.childCount && (s2 -= 1, r4 += 1);
  }
  return i3 ? o2.insertText(a3, s2, r4) : o2.replaceWith(s2, r4, t2), n.updateSelection && selectionToInsertionEnd2(o2, o2.steps.length - 1, -1), true;
}
var yn2 = class {
  constructor(e2) {
    this.editor = e2;
  }
  /**
   * Insert a piece of content at the current cursor position.
   *
   * @param content can be a string, or array of partial inline content elements
   */
  insertInlineContent(e2, { updateSelection: t2 = false } = {}) {
    const n = T(e2, this.editor.pmSchema);
    this.editor.transact((s2) => {
      bn2(
        s2,
        {
          from: s2.selection.from,
          to: s2.selection.to
        },
        n,
        {
          updateSelection: t2
        }
      );
    });
  }
  /**
   * Gets the active text styles at the text cursor position or at the end of the current selection if it's active.
   */
  getActiveStyles() {
    return this.editor.transact((e2) => {
      const t2 = {}, n = e2.selection.$to.marks();
      for (const s2 of n) {
        const r4 = this.editor.schema.styleSchema[s2.type.name];
        if (!r4) {
          s2.type.name !== "link" && // "blocknoteIgnore" tagged marks (such as comments) are also not considered BlockNote "styles"
          !s2.type.spec.blocknoteIgnore && console.warn("mark not found in styleschema", s2.type.name);
          continue;
        }
        r4.propSchema === "boolean" ? t2[r4.type] = true : t2[r4.type] = s2.attrs.stringValue;
      }
      return t2;
    });
  }
  /**
   * Adds styles to the currently selected content.
   * @param styles The styles to add.
   */
  addStyles(e2) {
    for (const [t2, n] of Object.entries(e2)) {
      const s2 = this.editor.schema.styleSchema[t2];
      if (!s2)
        throw new Error(`style ${t2} not found in styleSchema`);
      if (s2.propSchema === "boolean")
        this.editor._tiptapEditor.commands.setMark(t2);
      else if (s2.propSchema === "string")
        this.editor._tiptapEditor.commands.setMark(t2, {
          stringValue: n
        });
      else
        throw new O(s2.propSchema);
    }
  }
  /**
   * Removes styles from the currently selected content.
   * @param styles The styles to remove.
   */
  removeStyles(e2) {
    for (const t2 of Object.keys(e2))
      this.editor._tiptapEditor.commands.unsetMark(t2);
  }
  /**
   * Toggles styles on the currently selected content.
   * @param styles The styles to toggle.
   */
  toggleStyles(e2) {
    for (const [t2, n] of Object.entries(e2)) {
      const s2 = this.editor.schema.styleSchema[t2];
      if (!s2)
        throw new Error(`style ${t2} not found in styleSchema`);
      if (s2.propSchema === "boolean")
        this.editor._tiptapEditor.commands.toggleMark(t2);
      else if (s2.propSchema === "string")
        this.editor._tiptapEditor.commands.toggleMark(t2, {
          stringValue: n
        });
      else
        throw new O(s2.propSchema);
    }
  }
  /**
   * Gets the currently selected text.
   */
  getSelectedText() {
    return this.editor.transact((e2) => e2.doc.textBetween(e2.selection.from, e2.selection.to));
  }
  /**
   * Gets the URL of the last link in the current selection, or `undefined` if there are no links in the selection.
   */
  getSelectedLinkUrl() {
    return this.editor._tiptapEditor.getAttributes("link").href;
  }
  /**
   * Creates a new link to replace the selected content.
   * @param url The link URL.
   * @param text The text to display the link with.
   */
  createLink(e2, t2) {
    if (e2 === "")
      return;
    const n = this.editor.pmSchema.mark("link", { href: e2 });
    this.editor.transact((s2) => {
      const { from: r4, to: i3 } = s2.selection;
      t2 ? s2.insertText(t2, r4, i3).addMark(r4, r4 + t2.length, n) : s2.setSelection(TextSelection.create(s2.doc, i3)).addMark(
        r4,
        i3,
        n
      );
    });
  }
};
function Sn2(o2, e2) {
  const t2 = [];
  return o2.forEach((n, s2, r4) => {
    r4 !== e2 && t2.push(n);
  }), Fragment.from(t2);
}
function Bn2(o2, e2) {
  const t2 = [];
  for (let n = 0; n < o2.childCount; n++)
    if (o2.child(n).type.name === "tableRow")
      if (t2.length > 0 && t2[t2.length - 1].type.name === "table") {
        const s2 = t2[t2.length - 1], r4 = s2.copy(s2.content.addToEnd(o2.child(n)));
        t2[t2.length - 1] = r4;
      } else {
        const s2 = e2.nodes.table.createChecked(
          void 0,
          o2.child(n)
        );
        t2.push(s2);
      }
    else
      t2.push(o2.child(n));
  return o2 = Fragment.from(t2), o2;
}
function Cn2(o2, e2) {
  let t2 = Fragment.from(o2.content);
  if (t2 = Bn2(t2, e2.state.schema), !xn2(t2, e2))
    return new Slice(t2, o2.openStart, o2.openEnd);
  for (let n = 0; n < t2.childCount; n++)
    if (t2.child(n).type.spec.group === "blockContent") {
      const s2 = [t2.child(n)];
      if (n + 1 < t2.childCount && t2.child(n + 1).type.name === "blockGroup") {
        const i3 = t2.child(n + 1).child(0).child(0);
        (i3.type.name === "bulletListItem" || i3.type.name === "numberedListItem" || i3.type.name === "checkListItem") && (s2.push(t2.child(n + 1)), t2 = Sn2(t2, n + 1));
      }
      const r4 = e2.state.schema.nodes.blockContainer.createChecked(
        void 0,
        s2
      );
      t2 = t2.replaceChild(n, r4);
    }
  return new Slice(t2, o2.openStart, o2.openEnd);
}
function xn2(o2, e2) {
  var r4, i3;
  const t2 = o2.childCount === 1, n = ((r4 = o2.firstChild) == null ? void 0 : r4.type.spec.content) === "inline*", s2 = ((i3 = o2.firstChild) == null ? void 0 : i3.type.spec.content) === "tableRow+";
  if (t2) {
    if (n)
      return false;
    if (s2) {
      const c3 = Tt(e2.state);
      if (c3.isBlockContainer)
        return !(c3.blockContent.node.type.spec.content === "tableRow+");
    }
  }
  return true;
}
var En2 = {
  enableInputRules: true,
  enablePasteRules: true,
  enableCoreExtensions: false
};
var Le2 = class _Le extends f3 {
  constructor(t2) {
    var l2, d, u2, p4, m2, f6, k3, g, y3, T4;
    super();
    h6(this, "pmSchema");
    h6(this, "_tiptapEditor");
    h6(this, "elementRenderer", null);
    h6(this, "blockCache", /* @__PURE__ */ new WeakMap());
    h6(this, "dictionary");
    h6(this, "schema");
    h6(this, "blockImplementations");
    h6(this, "inlineContentImplementations");
    h6(this, "styleImplementations");
    h6(this, "uploadFile");
    h6(this, "onUploadStartCallbacks", []);
    h6(this, "onUploadEndCallbacks", []);
    h6(this, "resolveFileUrl");
    h6(this, "settings");
    h6(this, "_blockManager");
    h6(this, "_eventManager");
    h6(this, "_exportManager");
    h6(this, "_extensionManager");
    h6(this, "_selectionManager");
    h6(this, "_stateManager");
    h6(this, "_styleManager");
    h6(this, "unregisterExtension", (...t3) => this._extensionManager.unregisterExtension(...t3));
    h6(this, "registerExtension", (...t3) => this._extensionManager.registerExtension(...t3));
    h6(this, "getExtension", (...t3) => this._extensionManager.getExtension(...t3));
    h6(this, "mount", (t3) => {
      this._tiptapEditor.mount({ mount: t3 });
    });
    h6(this, "unmount", () => {
      this._tiptapEditor.unmount();
    });
    this.options = t2, this.dictionary = t2.dictionary || i, this.settings = {
      tables: {
        splitCells: ((l2 = t2 == null ? void 0 : t2.tables) == null ? void 0 : l2.splitCells) ?? false,
        cellBackgroundColor: ((d = t2 == null ? void 0 : t2.tables) == null ? void 0 : d.cellBackgroundColor) ?? false,
        cellTextColor: ((u2 = t2 == null ? void 0 : t2.tables) == null ? void 0 : u2.cellTextColor) ?? false,
        headers: ((p4 = t2 == null ? void 0 : t2.tables) == null ? void 0 : p4.headers) ?? false
      }
    };
    const n = {
      defaultStyles: true,
      schema: t2.schema || h5.create(),
      ...t2,
      placeholders: {
        ...this.dictionary.placeholders,
        ...t2.placeholders
      }
    };
    if (this.schema = n.schema, this.blockImplementations = n.schema.blockSpecs, this.inlineContentImplementations = n.schema.inlineContentSpecs, this.styleImplementations = n.schema.styleSpecs, n.uploadFile) {
      const S4 = n.uploadFile;
      this.uploadFile = async (P4, w3) => {
        this.onUploadStartCallbacks.forEach(
          (v8) => v8.apply(this, [w3])
        );
        try {
          return await S4(P4, w3);
        } finally {
          this.onUploadEndCallbacks.forEach(
            (v8) => v8.apply(this, [w3])
          );
        }
      };
    }
    this.resolveFileUrl = n.resolveFileUrl, this._eventManager = new fo3(this), this._extensionManager = new dn2(this, n);
    const s2 = this._extensionManager.getTiptapExtensions(), r4 = this._extensionManager.hasExtension("ySync") || this._extensionManager.hasExtension("liveblocksExtension");
    r4 && n.initialContent && console.warn(
      "When using Collaboration, initialContent might cause conflicts, because changes should come from the collaboration provider"
    );
    const i3 = {
      ...En2,
      ...n._tiptapOptions,
      element: null,
      autofocus: n.autofocus ?? false,
      extensions: s2,
      editorProps: {
        ...(m2 = n._tiptapOptions) == null ? void 0 : m2.editorProps,
        attributes: {
          // As of TipTap v2.5.0 the tabIndex is removed when the editor is not
          // editable, so you can't focus it. We want to revert this as we have
          // UI behaviour that relies on it.
          tabIndex: "0",
          ...(k3 = (f6 = n._tiptapOptions) == null ? void 0 : f6.editorProps) == null ? void 0 : k3.attributes,
          ...(g = n.domAttributes) == null ? void 0 : g.editor,
          class: D2(
            "bn-editor",
            n.defaultStyles ? "bn-default-styles" : "",
            ((T4 = (y3 = n.domAttributes) == null ? void 0 : y3.editor) == null ? void 0 : T4.class) || ""
          )
        },
        transformPasted: Cn2
      }
    };
    try {
      const S4 = n.initialContent || (r4 ? [
        {
          type: "paragraph",
          id: "initialBlockId"
        }
      ] : [
        {
          type: "paragraph",
          id: Q.options.generateID()
        }
      ]);
      if (!Array.isArray(S4) || S4.length === 0)
        throw new Error(
          "initialContent must be a non-empty array of blocks, received: " + S4
        );
      const P4 = getSchema(i3.extensions), w3 = S4.map(
        (Ne3) => bt(Ne3, P4, this.schema.styleSchema).toJSON()
      ), v8 = createDocument(
        {
          type: "doc",
          content: [
            {
              type: "blockGroup",
              content: w3
            }
          ]
        },
        P4,
        i3.parseOptions
      );
      this._tiptapEditor = new Editor({
        ...i3,
        content: v8.toJSON()
      }), this.pmSchema = this._tiptapEditor.schema;
    } catch (S4) {
      throw new Error(
        "Error creating document from blocks passed as `initialContent`",
        { cause: S4 }
      );
    }
    let c3;
    const a3 = this.pmSchema.nodes.doc.createAndFill;
    this.pmSchema.nodes.doc.createAndFill = (...S4) => {
      if (c3)
        return c3;
      const P4 = a3.apply(this.pmSchema.nodes.doc, S4), w3 = JSON.parse(JSON.stringify(P4.toJSON()));
      return w3.content[0].content[0].attrs.id = "initialBlockId", c3 = Node2.fromJSON(this.pmSchema, w3), c3;
    }, this.pmSchema.cached.blockNoteEditor = this, this._blockManager = new po3(this), this._exportManager = new xo3(this), this._selectionManager = new kn2(this), this._stateManager = new gn2(this), this._styleManager = new yn2(this), this.emit("create");
  }
  static create(t2) {
    return new _Le(t2 ?? {});
  }
  /**
   * BlockNote extensions that are added to the editor, keyed by the extension key
   */
  get extensions() {
    return this._extensionManager.getExtensions();
  }
  /**
   * Execute a prosemirror command. This is mostly for backwards compatibility with older code.
   *
   * @note You should prefer the {@link transact} method when possible, as it will automatically handle the dispatching of the transaction and work across blocknote transactions.
   *
   * @example
   * ```ts
   * editor.exec((state, dispatch, view) => {
   *   dispatch(state.tr.insertText("Hello, world!"));
   * });
   * ```
   */
  exec(t2) {
    return this._stateManager.exec(t2);
  }
  /**
   * Check if a command can be executed. A command should return `false` if it is not valid in the current state.
   *
   * @example
   * ```ts
   * if (editor.canExec(command)) {
   *   // show button
   * } else {
   *   // hide button
   * }
   * ```
   */
  canExec(t2) {
    return this._stateManager.canExec(t2);
  }
  /**
   * Execute a function within a "blocknote transaction".
   * All changes to the editor within the transaction will be grouped together, so that
   * we can dispatch them as a single operation (thus creating only a single undo step)
   *
   * @note There is no need to dispatch the transaction, as it will be automatically dispatched when the callback is complete.
   *
   * @example
   * ```ts
   * // All changes to the editor will be grouped together
   * editor.transact((tr) => {
   *   tr.insertText("Hello, world!");
   * // These two operations will be grouped together in a single undo step
   *   editor.transact((tr) => {
   *     tr.insertText("Hello, world!");
   *   });
   * });
   * ```
   */
  transact(t2) {
    return this._stateManager.transact(t2);
  }
  /**
   * Get the underlying prosemirror state
   * @note Prefer using `editor.transact` to read the current editor state, as that will ensure the state is up to date
   * @see https://prosemirror.net/docs/ref/#state.EditorState
   */
  get prosemirrorState() {
    return this._stateManager.prosemirrorState;
  }
  /**
   * Get the underlying prosemirror view
   * @see https://prosemirror.net/docs/ref/#view.EditorView
   */
  get prosemirrorView() {
    return this._stateManager.prosemirrorView;
  }
  get domElement() {
    var t2;
    if (!this.headless)
      return (t2 = this.prosemirrorView) == null ? void 0 : t2.dom;
  }
  isFocused() {
    var t2;
    return this.headless ? false : ((t2 = this.prosemirrorView) == null ? void 0 : t2.hasFocus()) || false;
  }
  get headless() {
    return !this._tiptapEditor.isInitialized;
  }
  /**
   * Focus on the editor
   */
  focus() {
    this.headless || this.prosemirrorView.focus();
  }
  /**
   * Blur the editor
   */
  blur() {
    var t2;
    this.headless || (t2 = this.domElement) == null || t2.blur();
  }
  // TODO move to extension
  onUploadStart(t2) {
    return this.onUploadStartCallbacks.push(t2), () => {
      const n = this.onUploadStartCallbacks.indexOf(t2);
      n > -1 && this.onUploadStartCallbacks.splice(n, 1);
    };
  }
  onUploadEnd(t2) {
    return this.onUploadEndCallbacks.push(t2), () => {
      const n = this.onUploadEndCallbacks.indexOf(t2);
      n > -1 && this.onUploadEndCallbacks.splice(n, 1);
    };
  }
  /**
   * @deprecated, use `editor.document` instead
   */
  get topLevelBlocks() {
    return this.document;
  }
  /**
   * Gets a snapshot of all top-level (non-nested) blocks in the editor.
   * @returns A snapshot of all top-level (non-nested) blocks in the editor.
   */
  get document() {
    return this._blockManager.document;
  }
  /**
   * Gets a snapshot of an existing block from the editor.
   * @param blockIdentifier The identifier of an existing block that should be
   * retrieved.
   * @returns The block that matches the identifier, or `undefined` if no
   * matching block was found.
   */
  getBlock(t2) {
    return this._blockManager.getBlock(t2);
  }
  /**
   * Gets a snapshot of the previous sibling of an existing block from the
   * editor.
   * @param blockIdentifier The identifier of an existing block for which the
   * previous sibling should be retrieved.
   * @returns The previous sibling of the block that matches the identifier.
   * `undefined` if no matching block was found, or it's the first child/block
   * in the document.
   */
  getPrevBlock(t2) {
    return this._blockManager.getPrevBlock(t2);
  }
  /**
   * Gets a snapshot of the next sibling of an existing block from the editor.
   * @param blockIdentifier The identifier of an existing block for which the
   * next sibling should be retrieved.
   * @returns The next sibling of the block that matches the identifier.
   * `undefined` if no matching block was found, or it's the last child/block in
   * the document.
   */
  getNextBlock(t2) {
    return this._blockManager.getNextBlock(t2);
  }
  /**
   * Gets a snapshot of the parent of an existing block from the editor.
   * @param blockIdentifier The identifier of an existing block for which the
   * parent should be retrieved.
   * @returns The parent of the block that matches the identifier. `undefined`
   * if no matching block was found, or the block isn't nested.
   */
  getParentBlock(t2) {
    return this._blockManager.getParentBlock(t2);
  }
  /**
   * Traverses all blocks in the editor depth-first, and executes a callback for each.
   * @param callback The callback to execute for each block. Returning `false` stops the traversal.
   * @param reverse Whether the blocks should be traversed in reverse order.
   */
  forEachBlock(t2, n = false) {
    this._blockManager.forEachBlock(t2, n);
  }
  /**
   * Executes a callback whenever the editor's contents change.
   * @param callback The callback to execute.
   *
   * @deprecated use {@link BlockNoteEditor.onChange} instead
   */
  onEditorContentChange(t2) {
    this._tiptapEditor.on("update", t2);
  }
  /**
   * Executes a callback whenever the editor's selection changes.
   * @param callback The callback to execute.
   *
   * @deprecated use `onSelectionChange` instead
   */
  onEditorSelectionChange(t2) {
    this._tiptapEditor.on("selectionUpdate", t2);
  }
  /**
   * Executes a callback before any change is applied to the editor, allowing you to cancel the change.
   * @param callback The callback to execute.
   * @returns A function to remove the callback.
   */
  onBeforeChange(t2) {
    return this._extensionManager.getExtension(po2).subscribe(t2);
  }
  /**
   * Gets a snapshot of the current text cursor position.
   * @returns A snapshot of the current text cursor position.
   */
  getTextCursorPosition() {
    return this._selectionManager.getTextCursorPosition();
  }
  /**
   * Sets the text cursor position to the start or end of an existing block. Throws an error if the target block could
   * not be found.
   * @param targetBlock The identifier of an existing block that the text cursor should be moved to.
   * @param placement Whether the text cursor should be placed at the start or end of the block.
   */
  setTextCursorPosition(t2, n = "start") {
    return this._selectionManager.setTextCursorPosition(t2, n);
  }
  /**
   * Gets a snapshot of the current selection. This contains all blocks (included nested blocks)
   * that the selection spans across.
   *
   * If the selection starts / ends halfway through a block, the returned data will contain the entire block.
   */
  getSelection() {
    return this._selectionManager.getSelection();
  }
  /**
   * Gets a snapshot of the current selection. This contains all blocks (included nested blocks)
   * that the selection spans across.
   *
   * If the selection starts / ends halfway through a block, the returned block will be
   * only the part of the block that is included in the selection.
   */
  getSelectionCutBlocks(t2 = false) {
    return this._selectionManager.getSelectionCutBlocks(t2);
  }
  /**
   * Sets the selection to a range of blocks.
   * @param startBlock The identifier of the block that should be the start of the selection.
   * @param endBlock The identifier of the block that should be the end of the selection.
   */
  setSelection(t2, n) {
    return this._selectionManager.setSelection(t2, n);
  }
  /**
   * Checks if the editor is currently editable, or if it's locked.
   * @returns True if the editor is editable, false otherwise.
   */
  get isEditable() {
    return this._stateManager.isEditable;
  }
  /**
   * Makes the editor editable or locks it, depending on the argument passed.
   * @param editable True to make the editor editable, or false to lock it.
   */
  set isEditable(t2) {
    this._stateManager.isEditable = t2;
  }
  /**
   * Inserts new blocks into the editor. If a block's `id` is undefined, BlockNote generates one automatically. Throws an
   * error if the reference block could not be found.
   * @param blocksToInsert An array of partial blocks that should be inserted.
   * @param referenceBlock An identifier for an existing block, at which the new blocks should be inserted.
   * @param placement Whether the blocks should be inserted just before, just after, or nested inside the
   * `referenceBlock`.
   */
  insertBlocks(t2, n, s2 = "before") {
    return this._blockManager.insertBlocks(
      t2,
      n,
      s2
    );
  }
  /**
   * Updates an existing block in the editor. Since updatedBlock is a PartialBlock object, some fields might not be
   * defined. These undefined fields are kept as-is from the existing block. Throws an error if the block to update could
   * not be found.
   * @param blockToUpdate The block that should be updated.
   * @param update A partial block which defines how the existing block should be changed.
   */
  updateBlock(t2, n) {
    return this._blockManager.updateBlock(t2, n);
  }
  /**
   * Removes existing blocks from the editor. Throws an error if any of the blocks could not be found.
   * @param blocksToRemove An array of identifiers for existing blocks that should be removed.
   */
  removeBlocks(t2) {
    return this._blockManager.removeBlocks(t2);
  }
  /**
   * Replaces existing blocks in the editor with new blocks. If the blocks that should be removed are not adjacent or
   * are at different nesting levels, `blocksToInsert` will be inserted at the position of the first block in
   * `blocksToRemove`. Throws an error if any of the blocks to remove could not be found.
   * @param blocksToRemove An array of blocks that should be replaced.
   * @param blocksToInsert An array of partial blocks to replace the old ones with.
   */
  replaceBlocks(t2, n) {
    return this._blockManager.replaceBlocks(t2, n);
  }
  /**
   * Undo the last action.
   */
  undo() {
    return this._stateManager.undo();
  }
  /**
   * Redo the last action.
   */
  redo() {
    return this._stateManager.redo();
  }
  /**
   * Insert a piece of content at the current cursor position.
   *
   * @param content can be a string, or array of partial inline content elements
   */
  insertInlineContent(t2, { updateSelection: n = false } = {}) {
    this._styleManager.insertInlineContent(t2, { updateSelection: n });
  }
  /**
   * Gets the active text styles at the text cursor position or at the end of the current selection if it's active.
   */
  getActiveStyles() {
    return this._styleManager.getActiveStyles();
  }
  /**
   * Adds styles to the currently selected content.
   * @param styles The styles to add.
   */
  addStyles(t2) {
    this._styleManager.addStyles(t2);
  }
  /**
   * Removes styles from the currently selected content.
   * @param styles The styles to remove.
   */
  removeStyles(t2) {
    this._styleManager.removeStyles(t2);
  }
  /**
   * Toggles styles on the currently selected content.
   * @param styles The styles to toggle.
   */
  toggleStyles(t2) {
    this._styleManager.toggleStyles(t2);
  }
  /**
   * Gets the currently selected text.
   */
  getSelectedText() {
    return this._styleManager.getSelectedText();
  }
  /**
   * Gets the URL of the last link in the current selection, or `undefined` if there are no links in the selection.
   */
  getSelectedLinkUrl() {
    return this._styleManager.getSelectedLinkUrl();
  }
  /**
   * Creates a new link to replace the selected content.
   * @param url The link URL.
   * @param text The text to display the link with.
   */
  createLink(t2, n) {
    this._styleManager.createLink(t2, n);
  }
  /**
   * Checks if the block containing the text cursor can be nested.
   */
  canNestBlock() {
    return this._blockManager.canNestBlock();
  }
  /**
   * Nests the block containing the text cursor into the block above it.
   */
  nestBlock() {
    this._blockManager.nestBlock();
  }
  /**
   * Checks if the block containing the text cursor is nested.
   */
  canUnnestBlock() {
    return this._blockManager.canUnnestBlock();
  }
  /**
   * Lifts the block containing the text cursor out of its parent.
   */
  unnestBlock() {
    this._blockManager.unnestBlock();
  }
  /**
   * Moves the selected blocks up. If the previous block has children, moves
   * them to the end of its children. If there is no previous block, but the
   * current blocks share a common parent, moves them out of & before it.
   */
  moveBlocksUp() {
    return this._blockManager.moveBlocksUp();
  }
  /**
   * Moves the selected blocks down. If the next block has children, moves
   * them to the start of its children. If there is no next block, but the
   * current blocks share a common parent, moves them out of & after it.
   */
  moveBlocksDown() {
    return this._blockManager.moveBlocksDown();
  }
  /**
   * Exports blocks into a simplified HTML string. To better conform to HTML standards, children of blocks which aren't list
   * items are un-nested in the output HTML.
   *
   * @param blocks An array of blocks that should be serialized into HTML.
   * @returns The blocks, serialized as an HTML string.
   */
  blocksToHTMLLossy(t2 = this.document) {
    return this._exportManager.blocksToHTMLLossy(t2);
  }
  /**
   * Serializes blocks into an HTML string in the format that would normally be rendered by the editor.
   *
   * Use this method if you want to server-side render HTML (for example, a blog post that has been edited in BlockNote)
   * and serve it to users without loading the editor on the client (i.e.: displaying the blog post)
   *
   * @param blocks An array of blocks that should be serialized into HTML.
   * @returns The blocks, serialized as an HTML string.
   */
  blocksToFullHTML(t2 = this.document) {
    return this._exportManager.blocksToFullHTML(t2);
  }
  /**
   * Parses blocks from an HTML string. Tries to create `Block` objects out of any HTML block-level elements, and
   * `InlineNode` objects from any HTML inline elements, though not all element types are recognized. If BlockNote
   * doesn't recognize an HTML element's tag, it will parse it as a paragraph or plain text.
   * @param html The HTML string to parse blocks from.
   * @returns The blocks parsed from the HTML string.
   */
  tryParseHTMLToBlocks(t2) {
    return this._exportManager.tryParseHTMLToBlocks(t2);
  }
  /**
   * Serializes blocks into a Markdown string. The output is simplified as Markdown does not support all features of
   * BlockNote - children of blocks which aren't list items are un-nested and certain styles are removed.
   * @param blocks An array of blocks that should be serialized into Markdown.
   * @returns The blocks, serialized as a Markdown string.
   */
  blocksToMarkdownLossy(t2 = this.document) {
    return this._exportManager.blocksToMarkdownLossy(t2);
  }
  /**
   * Creates a list of blocks from a Markdown string. Tries to create `Block` and `InlineNode` objects based on
   * Markdown syntax, though not all symbols are recognized. If BlockNote doesn't recognize a symbol, it will parse it
   * as text.
   * @param markdown The Markdown string to parse blocks from.
   * @returns The blocks parsed from the Markdown string.
   */
  tryParseMarkdownToBlocks(t2) {
    return this._exportManager.tryParseMarkdownToBlocks(t2);
  }
  /**
   * A callback function that runs whenever the editor's contents change.
   *
   * @param callback The callback to execute.
   * @returns A function to remove the callback.
   */
  onChange(t2, n) {
    return this._eventManager.onChange(t2, n);
  }
  /**
   * A callback function that runs whenever the text cursor position or selection changes.
   *
   * @param callback The callback to execute.
   * @returns A function to remove the callback.
   */
  onSelectionChange(t2, n) {
    return this._eventManager.onSelectionChange(
      t2,
      n
    );
  }
  /**
   * A callback function that runs when the editor has been mounted.
   *
   * This can be useful for plugins to initialize themselves after the editor has been mounted.
   *
   * @param callback The callback to execute.
   * @returns A function to remove the callback.
   */
  onMount(t2) {
    this._eventManager.onMount(t2);
  }
  /**
   * A callback function that runs when the editor has been unmounted.
   *
   * This can be useful for plugins to clean up themselves after the editor has been unmounted.
   *
   * @param callback The callback to execute.
   * @returns A function to remove the callback.
   */
  onUnmount(t2) {
    this._eventManager.onUnmount(t2);
  }
  /**
   * Gets the bounding box of the current selection.
   * @returns The bounding box of the current selection.
   */
  getSelectionBoundingBox() {
    return this._selectionManager.getSelectionBoundingBox();
  }
  get isEmpty() {
    const t2 = this.document;
    return t2.length === 0 || t2.length === 1 && t2[0].type === "paragraph" && t2[0].content.length === 0;
  }
  /**
   * Paste HTML into the editor. Defaults to converting HTML to BlockNote HTML.
   * @param html The HTML to paste.
   * @param raw Whether to paste the HTML as is, or to convert it to BlockNote HTML.
   */
  pasteHTML(t2, n = false) {
    this._exportManager.pasteHTML(t2, n);
  }
  /**
   * Paste text into the editor. Defaults to interpreting text as markdown.
   * @param text The text to paste.
   */
  pasteText(t2) {
    return this._exportManager.pasteText(t2);
  }
  /**
   * Paste markdown into the editor.
   * @param markdown The markdown to paste.
   */
  pasteMarkdown(t2) {
    return this._exportManager.pasteMarkdown(t2);
  }
};

// ../../node_modules/.pnpm/@tanstack+react-store@0.7.7_react-dom@19.2.3_react@19.2.3__react@19.2.3/node_modules/@tanstack/react-store/dist/esm/index.js
var import_with_selector = __toESM(require_with_selector());
function useStore(store, selector = (d) => d) {
  const slice2 = (0, import_with_selector.useSyncExternalStoreWithSelector)(
    store.subscribe,
    () => store.state,
    () => store.state,
    selector,
    shallow
  );
  return slice2;
}
function shallow(objA, objB) {
  if (Object.is(objA, objB)) {
    return true;
  }
  if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) {
    return false;
  }
  if (objA instanceof Map && objB instanceof Map) {
    if (objA.size !== objB.size) return false;
    for (const [k3, v8] of objA) {
      if (!objB.has(k3) || !Object.is(v8, objB.get(k3))) return false;
    }
    return true;
  }
  if (objA instanceof Set && objB instanceof Set) {
    if (objA.size !== objB.size) return false;
    for (const v8 of objA) {
      if (!objB.has(v8)) return false;
    }
    return true;
  }
  if (objA instanceof Date && objB instanceof Date) {
    if (objA.getTime() !== objB.getTime()) return false;
    return true;
  }
  const keysA = getOwnKeys(objA);
  if (keysA.length !== getOwnKeys(objB).length) {
    return false;
  }
  for (let i3 = 0; i3 < keysA.length; i3++) {
    if (!Object.prototype.hasOwnProperty.call(objB, keysA[i3]) || !Object.is(objA[keysA[i3]], objB[keysA[i3]])) {
      return false;
    }
  }
  return true;
}
function getOwnKeys(obj) {
  return Object.keys(obj).concat(
    Object.getOwnPropertySymbols(obj)
  );
}

// ../../node_modules/.pnpm/@blocknote+react@0.45.0_@floating-ui+dom@1.7.4_@tiptap+extensions@3.14.0_@tiptap+core@3_4c2381f288dfb667bae932edc4edea17/node_modules/@blocknote/react/dist/blocknote-react.js
var import_react_dom5 = __toESM(require_react_dom());

// ../../node_modules/.pnpm/@tiptap+react@3.14.0_@floating-ui+dom@1.7.4_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__@tip_34fe65420fd98382102c1f587a210fa8/node_modules/@tiptap/react/dist/index.js
var import_react3 = __toESM(require_react());
var import_react4 = __toESM(require_react());
var import_react_dom3 = __toESM(require_react_dom());
var import_shim = __toESM(require_shim());
var import_jsx_runtime3 = __toESM(require_jsx_runtime());
var import_react5 = __toESM(require_react());
var import_shim2 = __toESM(require_shim());

// ../../node_modules/.pnpm/fast-equals@5.4.0/node_modules/fast-equals/dist/es/index.mjs
var { getOwnPropertyNames, getOwnPropertySymbols } = Object;
var { hasOwnProperty: hasOwnProperty3 } = Object.prototype;
function combineComparators(comparatorA, comparatorB) {
  return function isEqual(a3, b4, state) {
    return comparatorA(a3, b4, state) && comparatorB(a3, b4, state);
  };
}
function createIsCircular(areItemsEqual) {
  return function isCircular(a3, b4, state) {
    if (!a3 || !b4 || typeof a3 !== "object" || typeof b4 !== "object") {
      return areItemsEqual(a3, b4, state);
    }
    const { cache } = state;
    const cachedA = cache.get(a3);
    const cachedB = cache.get(b4);
    if (cachedA && cachedB) {
      return cachedA === b4 && cachedB === a3;
    }
    cache.set(a3, b4);
    cache.set(b4, a3);
    const result = areItemsEqual(a3, b4, state);
    cache.delete(a3);
    cache.delete(b4);
    return result;
  };
}
function getShortTag(value) {
  return value != null ? value[Symbol.toStringTag] : void 0;
}
function getStrictProperties(object) {
  return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object));
}
var hasOwn = (
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  Object.hasOwn || ((object, property) => hasOwnProperty3.call(object, property))
);
function sameValueZeroEqual(a3, b4) {
  return a3 === b4 || !a3 && !b4 && a3 !== a3 && b4 !== b4;
}
var PREACT_VNODE = "__v";
var PREACT_OWNER = "__o";
var REACT_OWNER = "_owner";
var { getOwnPropertyDescriptor, keys: keys4 } = Object;
function areArrayBuffersEqual(a3, b4) {
  return a3.byteLength === b4.byteLength && areTypedArraysEqual(new Uint8Array(a3), new Uint8Array(b4));
}
function areArraysEqual(a3, b4, state) {
  let index4 = a3.length;
  if (b4.length !== index4) {
    return false;
  }
  while (index4-- > 0) {
    if (!state.equals(a3[index4], b4[index4], index4, index4, a3, b4, state)) {
      return false;
    }
  }
  return true;
}
function areDataViewsEqual(a3, b4) {
  return a3.byteLength === b4.byteLength && areTypedArraysEqual(new Uint8Array(a3.buffer, a3.byteOffset, a3.byteLength), new Uint8Array(b4.buffer, b4.byteOffset, b4.byteLength));
}
function areDatesEqual(a3, b4) {
  return sameValueZeroEqual(a3.getTime(), b4.getTime());
}
function areErrorsEqual(a3, b4) {
  return a3.name === b4.name && a3.message === b4.message && a3.cause === b4.cause && a3.stack === b4.stack;
}
function areFunctionsEqual(a3, b4) {
  return a3 === b4;
}
function areMapsEqual(a3, b4, state) {
  const size5 = a3.size;
  if (size5 !== b4.size) {
    return false;
  }
  if (!size5) {
    return true;
  }
  const matchedIndices = new Array(size5);
  const aIterable = a3.entries();
  let aResult;
  let bResult;
  let index4 = 0;
  while (aResult = aIterable.next()) {
    if (aResult.done) {
      break;
    }
    const bIterable = b4.entries();
    let hasMatch = false;
    let matchIndex = 0;
    while (bResult = bIterable.next()) {
      if (bResult.done) {
        break;
      }
      if (matchedIndices[matchIndex]) {
        matchIndex++;
        continue;
      }
      const aEntry = aResult.value;
      const bEntry = bResult.value;
      if (state.equals(aEntry[0], bEntry[0], index4, matchIndex, a3, b4, state) && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a3, b4, state)) {
        hasMatch = matchedIndices[matchIndex] = true;
        break;
      }
      matchIndex++;
    }
    if (!hasMatch) {
      return false;
    }
    index4++;
  }
  return true;
}
var areNumbersEqual = sameValueZeroEqual;
function areObjectsEqual(a3, b4, state) {
  const properties = keys4(a3);
  let index4 = properties.length;
  if (keys4(b4).length !== index4) {
    return false;
  }
  while (index4-- > 0) {
    if (!isPropertyEqual(a3, b4, state, properties[index4])) {
      return false;
    }
  }
  return true;
}
function areObjectsEqualStrict(a3, b4, state) {
  const properties = getStrictProperties(a3);
  let index4 = properties.length;
  if (getStrictProperties(b4).length !== index4) {
    return false;
  }
  let property;
  let descriptorA;
  let descriptorB;
  while (index4-- > 0) {
    property = properties[index4];
    if (!isPropertyEqual(a3, b4, state, property)) {
      return false;
    }
    descriptorA = getOwnPropertyDescriptor(a3, property);
    descriptorB = getOwnPropertyDescriptor(b4, property);
    if ((descriptorA || descriptorB) && (!descriptorA || !descriptorB || descriptorA.configurable !== descriptorB.configurable || descriptorA.enumerable !== descriptorB.enumerable || descriptorA.writable !== descriptorB.writable)) {
      return false;
    }
  }
  return true;
}
function arePrimitiveWrappersEqual(a3, b4) {
  return sameValueZeroEqual(a3.valueOf(), b4.valueOf());
}
function areRegExpsEqual(a3, b4) {
  return a3.source === b4.source && a3.flags === b4.flags;
}
function areSetsEqual(a3, b4, state) {
  const size5 = a3.size;
  if (size5 !== b4.size) {
    return false;
  }
  if (!size5) {
    return true;
  }
  const matchedIndices = new Array(size5);
  const aIterable = a3.values();
  let aResult;
  let bResult;
  while (aResult = aIterable.next()) {
    if (aResult.done) {
      break;
    }
    const bIterable = b4.values();
    let hasMatch = false;
    let matchIndex = 0;
    while (bResult = bIterable.next()) {
      if (bResult.done) {
        break;
      }
      if (!matchedIndices[matchIndex] && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a3, b4, state)) {
        hasMatch = matchedIndices[matchIndex] = true;
        break;
      }
      matchIndex++;
    }
    if (!hasMatch) {
      return false;
    }
  }
  return true;
}
function areTypedArraysEqual(a3, b4) {
  let index4 = a3.byteLength;
  if (b4.byteLength !== index4 || a3.byteOffset !== b4.byteOffset) {
    return false;
  }
  while (index4-- > 0) {
    if (a3[index4] !== b4[index4]) {
      return false;
    }
  }
  return true;
}
function areUrlsEqual(a3, b4) {
  return a3.hostname === b4.hostname && a3.pathname === b4.pathname && a3.protocol === b4.protocol && a3.port === b4.port && a3.hash === b4.hash && a3.username === b4.username && a3.password === b4.password;
}
function isPropertyEqual(a3, b4, state, property) {
  if ((property === REACT_OWNER || property === PREACT_OWNER || property === PREACT_VNODE) && (a3.$$typeof || b4.$$typeof)) {
    return true;
  }
  return hasOwn(b4, property) && state.equals(a3[property], b4[property], property, property, a3, b4, state);
}
var ARRAY_BUFFER_TAG = "[object ArrayBuffer]";
var ARGUMENTS_TAG = "[object Arguments]";
var BOOLEAN_TAG = "[object Boolean]";
var DATA_VIEW_TAG = "[object DataView]";
var DATE_TAG = "[object Date]";
var ERROR_TAG = "[object Error]";
var MAP_TAG = "[object Map]";
var NUMBER_TAG = "[object Number]";
var OBJECT_TAG = "[object Object]";
var REG_EXP_TAG = "[object RegExp]";
var SET_TAG = "[object Set]";
var STRING_TAG = "[object String]";
var TYPED_ARRAY_TAGS = {
  "[object Int8Array]": true,
  "[object Uint8Array]": true,
  "[object Uint8ClampedArray]": true,
  "[object Int16Array]": true,
  "[object Uint16Array]": true,
  "[object Int32Array]": true,
  "[object Uint32Array]": true,
  "[object Float16Array]": true,
  "[object Float32Array]": true,
  "[object Float64Array]": true,
  "[object BigInt64Array]": true,
  "[object BigUint64Array]": true
};
var URL_TAG = "[object URL]";
var toString3 = Object.prototype.toString;
function createEqualityComparator({ areArrayBuffersEqual: areArrayBuffersEqual2, areArraysEqual: areArraysEqual2, areDataViewsEqual: areDataViewsEqual2, areDatesEqual: areDatesEqual2, areErrorsEqual: areErrorsEqual2, areFunctionsEqual: areFunctionsEqual2, areMapsEqual: areMapsEqual2, areNumbersEqual: areNumbersEqual2, areObjectsEqual: areObjectsEqual2, arePrimitiveWrappersEqual: arePrimitiveWrappersEqual2, areRegExpsEqual: areRegExpsEqual2, areSetsEqual: areSetsEqual2, areTypedArraysEqual: areTypedArraysEqual2, areUrlsEqual: areUrlsEqual2, unknownTagComparators }) {
  return function comparator(a3, b4, state) {
    if (a3 === b4) {
      return true;
    }
    if (a3 == null || b4 == null) {
      return false;
    }
    const type = typeof a3;
    if (type !== typeof b4) {
      return false;
    }
    if (type !== "object") {
      if (type === "number") {
        return areNumbersEqual2(a3, b4, state);
      }
      if (type === "function") {
        return areFunctionsEqual2(a3, b4, state);
      }
      return false;
    }
    const constructor = a3.constructor;
    if (constructor !== b4.constructor) {
      return false;
    }
    if (constructor === Object) {
      return areObjectsEqual2(a3, b4, state);
    }
    if (Array.isArray(a3)) {
      return areArraysEqual2(a3, b4, state);
    }
    if (constructor === Date) {
      return areDatesEqual2(a3, b4, state);
    }
    if (constructor === RegExp) {
      return areRegExpsEqual2(a3, b4, state);
    }
    if (constructor === Map) {
      return areMapsEqual2(a3, b4, state);
    }
    if (constructor === Set) {
      return areSetsEqual2(a3, b4, state);
    }
    const tag = toString3.call(a3);
    if (tag === DATE_TAG) {
      return areDatesEqual2(a3, b4, state);
    }
    if (tag === REG_EXP_TAG) {
      return areRegExpsEqual2(a3, b4, state);
    }
    if (tag === MAP_TAG) {
      return areMapsEqual2(a3, b4, state);
    }
    if (tag === SET_TAG) {
      return areSetsEqual2(a3, b4, state);
    }
    if (tag === OBJECT_TAG) {
      return typeof a3.then !== "function" && typeof b4.then !== "function" && areObjectsEqual2(a3, b4, state);
    }
    if (tag === URL_TAG) {
      return areUrlsEqual2(a3, b4, state);
    }
    if (tag === ERROR_TAG) {
      return areErrorsEqual2(a3, b4, state);
    }
    if (tag === ARGUMENTS_TAG) {
      return areObjectsEqual2(a3, b4, state);
    }
    if (TYPED_ARRAY_TAGS[tag]) {
      return areTypedArraysEqual2(a3, b4, state);
    }
    if (tag === ARRAY_BUFFER_TAG) {
      return areArrayBuffersEqual2(a3, b4, state);
    }
    if (tag === DATA_VIEW_TAG) {
      return areDataViewsEqual2(a3, b4, state);
    }
    if (tag === BOOLEAN_TAG || tag === NUMBER_TAG || tag === STRING_TAG) {
      return arePrimitiveWrappersEqual2(a3, b4, state);
    }
    if (unknownTagComparators) {
      let unknownTagComparator = unknownTagComparators[tag];
      if (!unknownTagComparator) {
        const shortTag = getShortTag(a3);
        if (shortTag) {
          unknownTagComparator = unknownTagComparators[shortTag];
        }
      }
      if (unknownTagComparator) {
        return unknownTagComparator(a3, b4, state);
      }
    }
    return false;
  };
}
function createEqualityComparatorConfig({ circular, createCustomConfig, strict }) {
  let config = {
    areArrayBuffersEqual,
    areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual,
    areDataViewsEqual,
    areDatesEqual,
    areErrorsEqual,
    areFunctionsEqual,
    areMapsEqual: strict ? combineComparators(areMapsEqual, areObjectsEqualStrict) : areMapsEqual,
    areNumbersEqual,
    areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual,
    arePrimitiveWrappersEqual,
    areRegExpsEqual,
    areSetsEqual: strict ? combineComparators(areSetsEqual, areObjectsEqualStrict) : areSetsEqual,
    areTypedArraysEqual: strict ? combineComparators(areTypedArraysEqual, areObjectsEqualStrict) : areTypedArraysEqual,
    areUrlsEqual,
    unknownTagComparators: void 0
  };
  if (createCustomConfig) {
    config = Object.assign({}, config, createCustomConfig(config));
  }
  if (circular) {
    const areArraysEqual2 = createIsCircular(config.areArraysEqual);
    const areMapsEqual2 = createIsCircular(config.areMapsEqual);
    const areObjectsEqual2 = createIsCircular(config.areObjectsEqual);
    const areSetsEqual2 = createIsCircular(config.areSetsEqual);
    config = Object.assign({}, config, {
      areArraysEqual: areArraysEqual2,
      areMapsEqual: areMapsEqual2,
      areObjectsEqual: areObjectsEqual2,
      areSetsEqual: areSetsEqual2
    });
  }
  return config;
}
function createInternalEqualityComparator(compare) {
  return function(a3, b4, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) {
    return compare(a3, b4, state);
  };
}
function createIsEqual({ circular, comparator, createState: createState3, equals: equals2, strict }) {
  if (createState3) {
    return function isEqual(a3, b4) {
      const { cache = circular ? /* @__PURE__ */ new WeakMap() : void 0, meta: meta2 } = createState3();
      return comparator(a3, b4, {
        cache,
        equals: equals2,
        meta: meta2,
        strict
      });
    };
  }
  if (circular) {
    return function isEqual(a3, b4) {
      return comparator(a3, b4, {
        cache: /* @__PURE__ */ new WeakMap(),
        equals: equals2,
        meta: void 0,
        strict
      });
    };
  }
  const state = {
    cache: void 0,
    equals: equals2,
    meta: void 0,
    strict
  };
  return function isEqual(a3, b4) {
    return comparator(a3, b4, state);
  };
}
var deepEqual2 = createCustomEqual();
var strictDeepEqual = createCustomEqual({ strict: true });
var circularDeepEqual = createCustomEqual({ circular: true });
var strictCircularDeepEqual = createCustomEqual({
  circular: true,
  strict: true
});
var shallowEqual = createCustomEqual({
  createInternalComparator: () => sameValueZeroEqual
});
var strictShallowEqual = createCustomEqual({
  strict: true,
  createInternalComparator: () => sameValueZeroEqual
});
var circularShallowEqual = createCustomEqual({
  circular: true,
  createInternalComparator: () => sameValueZeroEqual
});
var strictCircularShallowEqual = createCustomEqual({
  circular: true,
  createInternalComparator: () => sameValueZeroEqual,
  strict: true
});
function createCustomEqual(options2 = {}) {
  const { circular = false, createInternalComparator: createCustomInternalComparator, createState: createState3, strict = false } = options2;
  const config = createEqualityComparatorConfig(options2);
  const comparator = createEqualityComparator(config);
  const equals2 = createCustomInternalComparator ? createCustomInternalComparator(comparator) : createInternalEqualityComparator(comparator);
  return createIsEqual({ circular, comparator, createState: createState3, equals: equals2, strict });
}

// ../../node_modules/.pnpm/@tiptap+react@3.14.0_@floating-ui+dom@1.7.4_@tiptap+core@3.14.0_@tiptap+pm@3.14.0__@tip_34fe65420fd98382102c1f587a210fa8/node_modules/@tiptap/react/dist/index.js
var import_react6 = __toESM(require_react());
var import_with_selector2 = __toESM(require_with_selector());
var import_jsx_runtime4 = __toESM(require_jsx_runtime());
var import_react7 = __toESM(require_react());
var import_jsx_runtime5 = __toESM(require_jsx_runtime());
var import_react8 = __toESM(require_react());
var import_jsx_runtime6 = __toESM(require_jsx_runtime());
var import_react9 = __toESM(require_react());
var import_react10 = __toESM(require_react());
var import_react_dom4 = __toESM(require_react_dom());
var import_jsx_runtime7 = __toESM(require_jsx_runtime());
var import_jsx_runtime8 = __toESM(require_jsx_runtime());
var import_react11 = __toESM(require_react());
var import_jsx_runtime9 = __toESM(require_jsx_runtime());
var mergeRefs = (...refs) => {
  return (node2) => {
    refs.forEach((ref) => {
      if (typeof ref === "function") {
        ref(node2);
      } else if (ref) {
        ;
        ref.current = node2;
      }
    });
  };
};
var Portals = ({ contentComponent }) => {
  const renderers = (0, import_shim.useSyncExternalStore)(
    contentComponent.subscribe,
    contentComponent.getSnapshot,
    contentComponent.getServerSnapshot
  );
  return (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children: Object.values(renderers) });
};
function getInstance() {
  const subscribers = /* @__PURE__ */ new Set();
  let renderers = {};
  return {
    /**
     * Subscribe to the editor instance's changes.
     */
    subscribe(callback) {
      subscribers.add(callback);
      return () => {
        subscribers.delete(callback);
      };
    },
    getSnapshot() {
      return renderers;
    },
    getServerSnapshot() {
      return renderers;
    },
    /**
     * Adds a new NodeView Renderer to the editor.
     */
    setRenderer(id2, renderer) {
      renderers = {
        ...renderers,
        [id2]: import_react_dom3.default.createPortal(renderer.reactElement, renderer.element, id2)
      };
      subscribers.forEach((subscriber) => subscriber());
    },
    /**
     * Removes a NodeView Renderer from the editor.
     */
    removeRenderer(id2) {
      const nextRenderers = { ...renderers };
      delete nextRenderers[id2];
      renderers = nextRenderers;
      subscribers.forEach((subscriber) => subscriber());
    }
  };
}
var PureEditorContent = class extends import_react4.default.Component {
  constructor(props) {
    var _a2;
    super(props);
    this.editorContentRef = import_react4.default.createRef();
    this.initialized = false;
    this.state = {
      hasContentComponentInitialized: Boolean((_a2 = props.editor) == null ? void 0 : _a2.contentComponent)
    };
  }
  componentDidMount() {
    this.init();
  }
  componentDidUpdate() {
    this.init();
  }
  init() {
    var _a2;
    const editor = this.props.editor;
    if (editor && !editor.isDestroyed && ((_a2 = editor.view.dom) == null ? void 0 : _a2.parentNode)) {
      if (editor.contentComponent) {
        return;
      }
      const element7 = this.editorContentRef.current;
      element7.append(...editor.view.dom.parentNode.childNodes);
      editor.setOptions({
        element: element7
      });
      editor.contentComponent = getInstance();
      if (!this.state.hasContentComponentInitialized) {
        this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => {
          this.setState((prevState) => {
            if (!prevState.hasContentComponentInitialized) {
              return {
                hasContentComponentInitialized: true
              };
            }
            return prevState;
          });
          if (this.unsubscribeToContentComponent) {
            this.unsubscribeToContentComponent();
          }
        });
      }
      editor.createNodeViews();
      this.initialized = true;
    }
  }
  componentWillUnmount() {
    var _a2;
    const editor = this.props.editor;
    if (!editor) {
      return;
    }
    this.initialized = false;
    if (!editor.isDestroyed) {
      editor.view.setProps({
        nodeViews: {}
      });
    }
    if (this.unsubscribeToContentComponent) {
      this.unsubscribeToContentComponent();
    }
    editor.contentComponent = null;
    try {
      if (!((_a2 = editor.view.dom) == null ? void 0 : _a2.parentNode)) {
        return;
      }
      const newElement = document.createElement("div");
      newElement.append(...editor.view.dom.parentNode.childNodes);
      editor.setOptions({
        element: newElement
      });
    } catch {
    }
  }
  render() {
    const { editor, innerRef, ...rest } = this.props;
    return (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
      (0, import_jsx_runtime3.jsx)("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }),
      (editor == null ? void 0 : editor.contentComponent) && (0, import_jsx_runtime3.jsx)(Portals, { contentComponent: editor.contentComponent })
    ] });
  }
};
var EditorContentWithKey = (0, import_react4.forwardRef)(
  (props, ref) => {
    const key2 = import_react4.default.useMemo(() => {
      return Math.floor(Math.random() * 4294967295).toString();
    }, [props.editor]);
    return import_react4.default.createElement(PureEditorContent, {
      key: key2,
      innerRef: ref,
      ...props
    });
  }
);
var EditorContent = import_react4.default.memo(EditorContentWithKey);
var isSSR = typeof window === "undefined";
var isNext = isSSR || Boolean(typeof window !== "undefined" && window.next);
var EditorContext = (0, import_react3.createContext)({
  editor: null
});
var EditorConsumer = EditorContext.Consumer;
var ReactNodeViewContext = (0, import_react7.createContext)({
  onDragStart: () => {
  },
  nodeViewContentChildren: void 0,
  nodeViewContentRef: () => {
  }
});
var useReactNodeView = () => (0, import_react7.useContext)(ReactNodeViewContext);
var NodeViewWrapper = import_react8.default.forwardRef((props, ref) => {
  const { onDragStart } = useReactNodeView();
  const Tag = props.as || "div";
  return (
    // @ts-ignore
    (0, import_jsx_runtime6.jsx)(
      Tag,
      {
        ...props,
        ref,
        "data-node-view-wrapper": "",
        onDragStart,
        style: {
          whiteSpace: "normal",
          ...props.style
        }
      }
    )
  );
});
function isClassComponent(Component) {
  return !!(typeof Component === "function" && Component.prototype && Component.prototype.isReactComponent);
}
function isForwardRefComponent(Component) {
  return !!(typeof Component === "object" && Component.$$typeof && (Component.$$typeof.toString() === "Symbol(react.forward_ref)" || Component.$$typeof.description === "react.forward_ref"));
}
function isMemoComponent(Component) {
  return !!(typeof Component === "object" && Component.$$typeof && (Component.$$typeof.toString() === "Symbol(react.memo)" || Component.$$typeof.description === "react.memo"));
}
function canReceiveRef(Component) {
  if (isClassComponent(Component)) {
    return true;
  }
  if (isForwardRefComponent(Component)) {
    return true;
  }
  if (isMemoComponent(Component)) {
    const wrappedComponent = Component.type;
    if (wrappedComponent) {
      return isClassComponent(wrappedComponent) || isForwardRefComponent(wrappedComponent);
    }
  }
  return false;
}
function isReact19Plus() {
  try {
    if (import_react10.version) {
      const majorVersion = parseInt(import_react10.version.split(".")[0], 10);
      return majorVersion >= 19;
    }
  } catch {
  }
  return false;
}
var ReactRenderer = class {
  /**
   * Immediately creates element and renders the provided React component.
   */
  constructor(component, { editor, props = {}, as = "div", className = "" }) {
    this.ref = null;
    this.id = Math.floor(Math.random() * 4294967295).toString();
    this.component = component;
    this.editor = editor;
    this.props = props;
    this.element = document.createElement(as);
    this.element.classList.add("react-renderer");
    if (className) {
      this.element.classList.add(...className.split(" "));
    }
    if (this.editor.isInitialized) {
      (0, import_react_dom4.flushSync)(() => {
        this.render();
      });
    } else {
      queueMicrotask(() => {
        this.render();
      });
    }
  }
  /**
   * Render the React component.
   */
  render() {
    var _a2;
    const Component = this.component;
    const props = this.props;
    const editor = this.editor;
    const isReact19 = isReact19Plus();
    const componentCanReceiveRef = canReceiveRef(Component);
    const elementProps = { ...props };
    if (elementProps.ref && !(isReact19 || componentCanReceiveRef)) {
      delete elementProps.ref;
    }
    if (!elementProps.ref && (isReact19 || componentCanReceiveRef)) {
      elementProps.ref = (ref) => {
        this.ref = ref;
      };
    }
    this.reactElement = (0, import_jsx_runtime7.jsx)(Component, { ...elementProps });
    (_a2 = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a2.setRenderer(this.id, this);
  }
  /**
   * Re-renders the React component with new props.
   */
  updateProps(props = {}) {
    this.props = {
      ...this.props,
      ...props
    };
    this.render();
  }
  /**
   * Destroy the React component.
   */
  destroy() {
    var _a2;
    const editor = this.editor;
    (_a2 = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a2.removeRenderer(this.id);
    try {
      if (this.element && this.element.parentNode) {
        this.element.parentNode.removeChild(this.element);
      }
    } catch {
    }
  }
  /**
   * Update the attributes of the element that holds the React component.
   */
  updateAttributes(attributes) {
    Object.keys(attributes).forEach((key2) => {
      this.element.setAttribute(key2, attributes[key2]);
    });
  }
};
var ReactMarkViewContext = import_react9.default.createContext({
  markViewContentRef: () => {
  }
});
var ReactMarkView = class extends MarkView {
  constructor(component, props, options2) {
    super(component, props, options2);
    const { as = "span", attrs, className = "" } = options2 || {};
    const componentProps = { ...props, updateAttributes: this.updateAttributes.bind(this) };
    this.contentDOMElement = document.createElement("span");
    const markViewContentRef = (el2) => {
      if (el2 && !el2.contains(this.contentDOMElement)) {
        el2.appendChild(this.contentDOMElement);
      }
    };
    const context = {
      markViewContentRef
    };
    const ReactMarkViewProvider = import_react9.default.memo((componentProps2) => {
      return (0, import_jsx_runtime8.jsx)(ReactMarkViewContext.Provider, { value: context, children: import_react9.default.createElement(component, componentProps2) });
    });
    ReactMarkViewProvider.displayName = "ReactMarkView";
    this.renderer = new ReactRenderer(ReactMarkViewProvider, {
      editor: props.editor,
      props: componentProps,
      as,
      className: `mark-${props.mark.type.name} ${className}`.trim()
    });
    if (attrs) {
      this.renderer.updateAttributes(attrs);
    }
  }
  get dom() {
    return this.renderer.element;
  }
  get contentDOM() {
    return this.contentDOMElement;
  }
};
function ReactMarkViewRenderer(component, options2 = {}) {
  return (props) => new ReactMarkView(component, props, options2);
}
var ReactNodeView = class extends NodeView {
  constructor(component, props, options2) {
    super(component, props, options2);
    this.selectionRafId = null;
    if (!this.node.isLeaf) {
      if (this.options.contentDOMElementTag) {
        this.contentDOMElement = document.createElement(this.options.contentDOMElementTag);
      } else {
        this.contentDOMElement = document.createElement(this.node.isInline ? "span" : "div");
      }
      this.contentDOMElement.dataset.nodeViewContentReact = "";
      this.contentDOMElement.dataset.nodeViewWrapper = "";
      this.contentDOMElement.style.whiteSpace = "inherit";
      const contentTarget = this.dom.querySelector("[data-node-view-content]");
      if (!contentTarget) {
        return;
      }
      contentTarget.appendChild(this.contentDOMElement);
    }
  }
  /**
   * Setup the React component.
   * Called on initialization.
   */
  mount() {
    const props = {
      editor: this.editor,
      node: this.node,
      decorations: this.decorations,
      innerDecorations: this.innerDecorations,
      view: this.view,
      selected: false,
      extension: this.extension,
      HTMLAttributes: this.HTMLAttributes,
      getPos: () => this.getPos(),
      updateAttributes: (attributes = {}) => this.updateAttributes(attributes),
      deleteNode: () => this.deleteNode(),
      ref: (0, import_react11.createRef)()
    };
    if (!this.component.displayName) {
      const capitalizeFirstChar = (string3) => {
        return string3.charAt(0).toUpperCase() + string3.substring(1);
      };
      this.component.displayName = capitalizeFirstChar(this.extension.name);
    }
    const onDragStart = this.onDragStart.bind(this);
    const nodeViewContentRef = (element7) => {
      if (element7 && this.contentDOMElement && element7.firstChild !== this.contentDOMElement) {
        if (element7.hasAttribute("data-node-view-wrapper")) {
          element7.removeAttribute("data-node-view-wrapper");
        }
        element7.appendChild(this.contentDOMElement);
      }
    };
    const context = { onDragStart, nodeViewContentRef };
    const Component = this.component;
    const ReactNodeViewProvider = (0, import_react11.memo)((componentProps) => {
      return (0, import_jsx_runtime9.jsx)(ReactNodeViewContext.Provider, { value: context, children: (0, import_react11.createElement)(Component, componentProps) });
    });
    ReactNodeViewProvider.displayName = "ReactNodeView";
    let as = this.node.isInline ? "span" : "div";
    if (this.options.as) {
      as = this.options.as;
    }
    const { className = "" } = this.options;
    this.handleSelectionUpdate = this.handleSelectionUpdate.bind(this);
    this.renderer = new ReactRenderer(ReactNodeViewProvider, {
      editor: this.editor,
      props,
      as,
      className: `node-${this.node.type.name} ${className}`.trim()
    });
    this.editor.on("selectionUpdate", this.handleSelectionUpdate);
    this.updateElementAttributes();
  }
  /**
   * Return the DOM element.
   * This is the element that will be used to display the node view.
   */
  get dom() {
    var _a2;
    if (this.renderer.element.firstElementChild && !((_a2 = this.renderer.element.firstElementChild) == null ? void 0 : _a2.hasAttribute("data-node-view-wrapper"))) {
      throw Error("Please use the NodeViewWrapper component for your node view.");
    }
    return this.renderer.element;
  }
  /**
   * Return the content DOM element.
   * This is the element that will be used to display the rich-text content of the node.
   */
  get contentDOM() {
    if (this.node.isLeaf) {
      return null;
    }
    return this.contentDOMElement;
  }
  /**
   * On editor selection update, check if the node is selected.
   * If it is, call `selectNode`, otherwise call `deselectNode`.
   */
  handleSelectionUpdate() {
    if (this.selectionRafId) {
      cancelAnimationFrame(this.selectionRafId);
      this.selectionRafId = null;
    }
    this.selectionRafId = requestAnimationFrame(() => {
      this.selectionRafId = null;
      const { from: from4, to: to2 } = this.editor.state.selection;
      const pos = this.getPos();
      if (typeof pos !== "number") {
        return;
      }
      if (from4 <= pos && to2 >= pos + this.node.nodeSize) {
        if (this.renderer.props.selected) {
          return;
        }
        this.selectNode();
      } else {
        if (!this.renderer.props.selected) {
          return;
        }
        this.deselectNode();
      }
    });
  }
  /**
   * On update, update the React component.
   * To prevent unnecessary updates, the `update` option can be used.
   */
  update(node2, decorations, innerDecorations) {
    const rerenderComponent = (props) => {
      this.renderer.updateProps(props);
      if (typeof this.options.attrs === "function") {
        this.updateElementAttributes();
      }
    };
    if (node2.type !== this.node.type) {
      return false;
    }
    if (typeof this.options.update === "function") {
      const oldNode = this.node;
      const oldDecorations = this.decorations;
      const oldInnerDecorations = this.innerDecorations;
      this.node = node2;
      this.decorations = decorations;
      this.innerDecorations = innerDecorations;
      return this.options.update({
        oldNode,
        oldDecorations,
        newNode: node2,
        newDecorations: decorations,
        oldInnerDecorations,
        innerDecorations,
        updateProps: () => rerenderComponent({ node: node2, decorations, innerDecorations })
      });
    }
    if (node2 === this.node && this.decorations === decorations && this.innerDecorations === innerDecorations) {
      return true;
    }
    this.node = node2;
    this.decorations = decorations;
    this.innerDecorations = innerDecorations;
    rerenderComponent({ node: node2, decorations, innerDecorations });
    return true;
  }
  /**
   * Select the node.
   * Add the `selected` prop and the `ProseMirror-selectednode` class.
   */
  selectNode() {
    this.renderer.updateProps({
      selected: true
    });
    this.renderer.element.classList.add("ProseMirror-selectednode");
  }
  /**
   * Deselect the node.
   * Remove the `selected` prop and the `ProseMirror-selectednode` class.
   */
  deselectNode() {
    this.renderer.updateProps({
      selected: false
    });
    this.renderer.element.classList.remove("ProseMirror-selectednode");
  }
  /**
   * Destroy the React component instance.
   */
  destroy() {
    this.renderer.destroy();
    this.editor.off("selectionUpdate", this.handleSelectionUpdate);
    this.contentDOMElement = null;
    if (this.selectionRafId) {
      cancelAnimationFrame(this.selectionRafId);
      this.selectionRafId = null;
    }
  }
  /**
   * Update the attributes of the top-level element that holds the React component.
   * Applying the attributes defined in the `attrs` option.
   */
  updateElementAttributes() {
    if (this.options.attrs) {
      let attrsObj = {};
      if (typeof this.options.attrs === "function") {
        const extensionAttributes = this.editor.extensionManager.attributes;
        const HTMLAttributes = getRenderedAttributes(this.node, extensionAttributes);
        attrsObj = this.options.attrs({ node: this.node, HTMLAttributes });
      } else {
        attrsObj = this.options.attrs;
      }
      this.renderer.updateAttributes(attrsObj);
    }
  }
};
function ReactNodeViewRenderer(component, options2) {
  return (props) => {
    if (!props.editor.contentComponent) {
      return {};
    }
    return new ReactNodeView(component, props, options2);
  };
}

// ../../node_modules/.pnpm/@blocknote+react@0.45.0_@floating-ui+dom@1.7.4_@tiptap+extensions@3.14.0_@tiptap+core@3_4c2381f288dfb667bae932edc4edea17/node_modules/@blocknote/react/dist/blocknote-react.js
var import_client = __toESM(require_client());
var ln3 = Object.defineProperty;
var cn3 = (e2, t2, n) => t2 in e2 ? ln3(e2, t2, { enumerable: true, configurable: true, writable: true, value: n }) : e2[t2] = n;
var ee2 = (e2, t2, n) => cn3(e2, typeof t2 != "symbol" ? t2 + "" : t2, n);
var _t5 = (0, import_react12.createContext)(void 0);
function q3(e2) {
  return (0, import_react12.useContext)(_t5);
}
var lo2 = (0, import_react12.createContext)(
  void 0
);
function w2() {
  return (0, import_react12.useContext)(lo2);
}
function v7(e2) {
  const t2 = q3();
  if (!(t2 != null && t2.editor))
    throw new Error(
      "useBlockNoteEditor was called outside of a BlockNoteContext provider or BlockNoteView component"
    );
  return t2.editor;
}
function M6() {
  return q3().editor.dictionary;
}
var co2 = (e2) => {
  const t2 = w2(), n = M6(), o2 = v7(), r4 = o2.getBlock(e2.blockId), [i3, c3] = (0, import_react12.useState)(""), s2 = (0, import_react12.useCallback)(
    (d) => {
      c3(d.currentTarget.value);
    },
    []
  ), a3 = (0, import_react12.useCallback)(
    (d) => {
      d.key === "Enter" && (d.preventDefault(), o2.updateBlock(r4.id, {
        props: {
          name: po(i3),
          url: i3
        }
      }));
    },
    [o2, r4.id, i3]
  ), u2 = (0, import_react12.useCallback)(() => {
    o2.updateBlock(r4.id, {
      props: {
        name: po(i3),
        url: i3
      }
    });
  }, [o2, r4.id, i3]);
  return (0, import_jsx_runtime10.jsxs)(t2.FilePanel.TabPanel, { className: "bn-tab-panel", children: [
    (0, import_jsx_runtime10.jsx)(
      t2.FilePanel.TextInput,
      {
        className: "bn-text-input",
        placeholder: n.file_panel.embed.url_placeholder,
        value: i3,
        onChange: s2,
        onKeyDown: a3,
        "data-test": "embed-input"
      }
    ),
    (0, import_jsx_runtime10.jsx)(
      t2.FilePanel.Button,
      {
        className: "bn-button",
        onClick: u2,
        "data-test": "embed-input-button",
        children: n.file_panel.embed.embed_button[r4.type] || n.file_panel.embed.embed_button.file
      }
    )
  ] });
};
var ao2 = (e2) => {
  var m2, h7;
  const t2 = w2(), n = M6(), { setLoading: o2 } = e2, r4 = v7(), i3 = r4.getBlock(e2.blockId), [c3, s2] = (0, import_react12.useState)(false);
  (0, import_react12.useEffect)(() => {
    c3 && setTimeout(() => {
      s2(false);
    }, 3e3);
  }, [c3]);
  const a3 = (0, import_react12.useCallback)(
    (f6) => {
      if (f6 === null)
        return;
      async function g(b4) {
        if (o2(true), r4.uploadFile !== void 0)
          try {
            let p4 = await r4.uploadFile(b4, e2.blockId);
            typeof p4 == "string" && (p4 = {
              props: {
                name: b4.name,
                url: p4
              }
            }), r4.updateBlock(e2.blockId, p4);
          } catch {
            s2(true);
          } finally {
            o2(false);
          }
      }
      g(f6);
    },
    [e2.blockId, r4, o2]
  ), u2 = r4.schema.blockSpecs[i3.type], d = (h7 = (m2 = u2.implementation.meta) == null ? void 0 : m2.fileBlockAccept) != null && h7.length ? u2.implementation.meta.fileBlockAccept.join(",") : "*/*";
  return (0, import_jsx_runtime10.jsxs)(t2.FilePanel.TabPanel, { className: "bn-tab-panel", children: [
    (0, import_jsx_runtime10.jsx)(
      t2.FilePanel.FileInput,
      {
        className: "bn-file-input",
        "data-test": "upload-input",
        accept: d,
        placeholder: n.file_panel.upload.file_placeholder[i3.type] || n.file_panel.upload.file_placeholder.file,
        value: null,
        onChange: a3
      }
    ),
    c3 && (0, import_jsx_runtime10.jsx)("div", { className: "bn-error-text", children: n.file_panel.upload.upload_error })
  ] });
};
var Et3 = (e2) => {
  const t2 = w2(), n = M6(), o2 = v7(), [r4, i3] = (0, import_react12.useState)(false), c3 = e2.tabs ?? [
    ...o2.uploadFile !== void 0 ? [
      {
        name: n.file_panel.upload.title,
        tabPanel: (0, import_jsx_runtime10.jsx)(ao2, { blockId: e2.blockId, setLoading: i3 })
      }
    ] : [],
    {
      name: n.file_panel.embed.title,
      tabPanel: (0, import_jsx_runtime10.jsx)(co2, { blockId: e2.blockId })
    }
  ], [s2, a3] = (0, import_react12.useState)(
    e2.defaultOpenTab || c3[0].name
  );
  return (0, import_jsx_runtime10.jsx)(
    t2.FilePanel.Root,
    {
      className: "bn-panel",
      defaultOpenTab: s2,
      openTab: s2,
      setOpenTab: a3,
      tabs: c3,
      loading: r4
    }
  );
};
function so2(e2) {
  let t2 = new DOMRect();
  const n = "getBoundingClientRect" in e2 ? () => e2.getBoundingClientRect() : () => e2.element.getBoundingClientRect();
  return () => "element" in e2 && (e2.cacheMountedBoundingClientRect ?? true) ? (e2.element.isConnected && (t2 = n()), t2) : n();
}
var U4 = (e2) => {
  var g, b4, p4;
  const { refs: t2, floatingStyles: n, context: o2 } = useFloating2({
    whileElementsMounted: autoUpdate,
    ...e2.useFloatingOptions
  }), { isMounted: r4, styles: i3 } = useTransitionStyles(
    o2,
    e2.useTransitionStylesProps
  ), { status: c3 } = useTransitionStatus(
    o2,
    e2.useTransitionStatusProps
  ), s2 = useDismiss(o2, e2.useDismissProps), a3 = useHover(o2, { enabled: false, ...e2.useHoverProps }), { getFloatingProps: u2 } = useInteractions([s2, a3]), d = (0, import_react12.useRef)(""), m2 = (0, import_react12.useRef)(null), h7 = useMergeRefs([m2, t2.setFloating]);
  if ((0, import_react12.useEffect)(() => {
    if (e2.reference) {
      const C3 = "element" in e2.reference ? e2.reference.element : void 0;
      C3 !== void 0 && t2.setReference(C3), t2.setPositionReference({
        getBoundingClientRect: so2(
          e2.reference
        ),
        contextElement: C3
      });
    }
  }, [e2.reference, t2]), (0, import_react12.useEffect)(
    () => {
      var C3;
      (c3 === "initial" || c3 === "open") && (C3 = m2.current) != null && C3.innerHTML && (d.current = m2.current.innerHTML);
    },
    // `props.children` is added to the deps, since it's ultimately the HTML of
    // the children that we're storing.
    [c3, e2.reference, e2.children]
  ), !r4)
    return false;
  const f6 = {
    ...e2.elementProps,
    style: {
      display: "flex",
      ...(g = e2.elementProps) == null ? void 0 : g.style,
      zIndex: `calc(var(--bn-ui-base-z-index) + ${((p4 = (b4 = e2.elementProps) == null ? void 0 : b4.style) == null ? void 0 : p4.zIndex) || 0})`,
      ...n,
      ...i3
    },
    ...u2()
  };
  return c3 === "close" ? (0, import_jsx_runtime10.jsx)(
    "div",
    {
      ref: h7,
      ...f6,
      dangerouslySetInnerHTML: { __html: d.current }
    }
  ) : (0, import_jsx_runtime10.jsx)("div", { ref: h7, ...f6, children: e2.children });
};
var Bt3 = (e2) => {
  const { blockId: t2, children: n, ...o2 } = e2, r4 = v7(), i3 = (0, import_react12.useMemo)(
    () => r4.transact((c3) => {
      if (!t2)
        return;
      const s2 = Tt2(t2, c3.doc);
      if (!s2)
        return;
      const { node: a3 } = r4.prosemirrorView.domAtPos(
        s2.posBeforeNode + 1
      );
      if (a3 instanceof Element)
        return {
          element: a3
        };
    }),
    [r4, t2]
  );
  return (0, import_jsx_runtime10.jsx)(U4, { reference: i3, ...o2, children: t2 !== void 0 && n });
};
function T3(e2, t2) {
  const o2 = ((t2 == null ? void 0 : t2.editor) ?? v7()).getExtension(e2);
  if (!o2)
    throw new Error("Extension not found", { cause: { plugin: e2 } });
  return o2;
}
function E3(e2, t2) {
  const { store: n } = T3(e2, t2);
  if (!n)
    throw new Error("Store not found on plugin", { cause: { plugin: e2 } });
  return useStore(n, t2 == null ? void 0 : t2.selector);
}
var uo3 = (e2) => {
  const t2 = v7(), n = T3(I2), o2 = E3(I2), r4 = (0, import_react12.useMemo)(
    () => ({
      useFloatingOptions: {
        open: !!o2,
        // Needed as hooks like `useDismiss` call `onOpenChange` to change the
        // open state.
        onOpenChange: (c3, s2, a3) => {
          c3 || n.closeMenu(), a3 === "escape-key" && t2.focus();
        },
        middleware: [offset3(10), flip3()]
      },
      elementProps: {
        style: {
          zIndex: 90
        }
      },
      ...e2.floatingUIOptions
    }),
    [o2, t2, n, e2.floatingUIOptions]
  ), i3 = e2.filePanel || Et3;
  return (0, import_jsx_runtime10.jsx)(Bt3, { blockId: o2, ...r4, children: o2 && (0, import_jsx_runtime10.jsx)(i3, { blockId: o2 }) });
};
function mo3(e2) {
  return e2 && e2.__esModule && Object.prototype.hasOwnProperty.call(e2, "default") ? e2.default : e2;
}
var fo4 = function e(t2, n) {
  if (t2 === n) return true;
  if (t2 && n && typeof t2 == "object" && typeof n == "object") {
    if (t2.constructor !== n.constructor) return false;
    var o2, r4, i3;
    if (Array.isArray(t2)) {
      if (o2 = t2.length, o2 != n.length) return false;
      for (r4 = o2; r4-- !== 0; )
        if (!e(t2[r4], n[r4])) return false;
      return true;
    }
    if (t2 instanceof Map && n instanceof Map) {
      if (t2.size !== n.size) return false;
      for (r4 of t2.entries())
        if (!n.has(r4[0])) return false;
      for (r4 of t2.entries())
        if (!e(r4[1], n.get(r4[0]))) return false;
      return true;
    }
    if (t2 instanceof Set && n instanceof Set) {
      if (t2.size !== n.size) return false;
      for (r4 of t2.entries())
        if (!n.has(r4[0])) return false;
      return true;
    }
    if (ArrayBuffer.isView(t2) && ArrayBuffer.isView(n)) {
      if (o2 = t2.length, o2 != n.length) return false;
      for (r4 = o2; r4-- !== 0; )
        if (t2[r4] !== n[r4]) return false;
      return true;
    }
    if (t2.constructor === RegExp) return t2.source === n.source && t2.flags === n.flags;
    if (t2.valueOf !== Object.prototype.valueOf) return t2.valueOf() === n.valueOf();
    if (t2.toString !== Object.prototype.toString) return t2.toString() === n.toString();
    if (i3 = Object.keys(t2), o2 = i3.length, o2 !== Object.keys(n).length) return false;
    for (r4 = o2; r4-- !== 0; )
      if (!Object.prototype.hasOwnProperty.call(n, i3[r4])) return false;
    for (r4 = o2; r4-- !== 0; ) {
      var c3 = i3[r4];
      if (!(c3 === "_owner" && t2.$$typeof) && !e(t2[c3], n[c3]))
        return false;
    }
    return true;
  }
  return t2 !== t2 && n !== n;
};
var ho3 = mo3(fo4);
var Ie4 = { exports: {} };
var se2 = { exports: {} };
var _e3 = {};
var ot;
function bo4() {
  return ot || (ot = 1, (function() {
    function e2(f6, g) {
      return f6 === g && (f6 !== 0 || 1 / f6 === 1 / g) || f6 !== f6 && g !== g;
    }
    function t2(f6, g) {
      d || r4.startTransition === void 0 || (d = true, console.error(
        "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
      ));
      var b4 = g();
      if (!m2) {
        var p4 = g();
        i3(b4, p4) || (console.error(
          "The result of getSnapshot should be cached to avoid an infinite loop"
        ), m2 = true);
      }
      p4 = c3({
        inst: { value: b4, getSnapshot: g }
      });
      var C3 = p4[0].inst, _2 = p4[1];
      return a3(
        function() {
          C3.value = b4, C3.getSnapshot = g, n(C3) && _2({ inst: C3 });
        },
        [f6, b4, g]
      ), s2(
        function() {
          return n(C3) && _2({ inst: C3 }), f6(function() {
            n(C3) && _2({ inst: C3 });
          });
        },
        [f6]
      ), u2(b4), b4;
    }
    function n(f6) {
      var g = f6.getSnapshot;
      f6 = f6.value;
      try {
        var b4 = g();
        return !i3(f6, b4);
      } catch {
        return true;
      }
    }
    function o2(f6, g) {
      return g();
    }
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
    var r4 = import_react12.default, i3 = typeof Object.is == "function" ? Object.is : e2, c3 = r4.useState, s2 = r4.useEffect, a3 = r4.useLayoutEffect, u2 = r4.useDebugValue, d = false, m2 = false, h7 = typeof window > "u" || typeof window.document > "u" || typeof window.document.createElement > "u" ? o2 : t2;
    _e3.useSyncExternalStore = r4.useSyncExternalStore !== void 0 ? r4.useSyncExternalStore : h7, typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
  })()), _e3;
}
var rt;
function Lt3() {
  return rt || (rt = 1, false ? se2.exports = go() : se2.exports = bo4()), se2.exports;
}
var Ee3 = {};
var lt;
function Co4() {
  return lt || (lt = 1, (function() {
    function e2(u2, d) {
      return u2 === d && (u2 !== 0 || 1 / u2 === 1 / d) || u2 !== u2 && d !== d;
    }
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
    var t2 = import_react12.default, n = Lt3(), o2 = typeof Object.is == "function" ? Object.is : e2, r4 = n.useSyncExternalStore, i3 = t2.useRef, c3 = t2.useEffect, s2 = t2.useMemo, a3 = t2.useDebugValue;
    Ee3.useSyncExternalStoreWithSelector = function(u2, d, m2, h7, f6) {
      var g = i3(null);
      if (g.current === null) {
        var b4 = { hasValue: false, value: null };
        g.current = b4;
      } else b4 = g.current;
      g = s2(
        function() {
          function C3(B4) {
            if (!_2) {
              if (_2 = true, N3 = B4, B4 = h7(B4), f6 !== void 0 && b4.hasValue) {
                var I4 = b4.value;
                if (f6(I4, B4))
                  return O2 = I4;
              }
              return O2 = B4;
            }
            if (I4 = O2, o2(N3, B4))
              return I4;
            var K6 = h7(B4);
            return f6 !== void 0 && f6(I4, K6) ? (N3 = B4, I4) : (N3 = B4, O2 = K6);
          }
          var _2 = false, N3, O2, $6 = m2 === void 0 ? null : m2;
          return [
            function() {
              return C3(d());
            },
            $6 === null ? void 0 : function() {
              return C3($6());
            }
          ];
        },
        [d, m2, h7, f6]
      );
      var p4 = r4(u2, g[0], g[1]);
      return c3(
        function() {
          b4.hasValue = true, b4.value = p4;
        },
        [p4]
      ), a3(p4), p4;
    }, typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ < "u" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop == "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
  })()), Ee3;
}
false ? Ie4.exports = po() : Ie4.exports = Co4();
var vo4 = Ie4.exports;
var wo4 = typeof window < "u" ? import_react12.useLayoutEffect : import_react12.useEffect;
var ko4 = class {
  constructor(t2) {
    ee2(this, "transactionNumber", 0);
    ee2(this, "lastTransactionNumber", 0);
    ee2(this, "lastSnapshot");
    ee2(this, "editor");
    ee2(this, "subscribers", /* @__PURE__ */ new Set());
    this.editor = t2, this.lastSnapshot = { editor: t2, transactionNumber: 0 }, this.getSnapshot = this.getSnapshot.bind(this), this.getServerSnapshot = this.getServerSnapshot.bind(this), this.watch = this.watch.bind(this), this.subscribe = this.subscribe.bind(this);
  }
  /**
   * Get the current editor instance.
   */
  getSnapshot() {
    return this.transactionNumber === this.lastTransactionNumber ? this.lastSnapshot : (this.lastTransactionNumber = this.transactionNumber, this.lastSnapshot = {
      editor: this.editor,
      transactionNumber: this.transactionNumber
    }, this.lastSnapshot);
  }
  /**
   * Always disable the editor on the server-side.
   */
  getServerSnapshot() {
    return { editor: null, transactionNumber: 0 };
  }
  /**
   * Subscribe to the editor instance's changes.
   */
  subscribe(t2) {
    return this.subscribers.add(t2), () => {
      this.subscribers.delete(t2);
    };
  }
  /**
   * Watch the editor instance for changes.
   */
  watch(t2, n) {
    if (this.editor = t2, this.editor) {
      const o2 = () => {
        this.transactionNumber += 1, this.subscribers.forEach((c3) => c3());
      }, r4 = this.editor._tiptapEditor, i3 = {
        all: "transaction",
        selection: "selectionUpdate",
        change: "update"
      };
      return r4.on(i3[n], o2), () => {
        r4.off(i3[n], o2);
      };
    }
  }
};
function R4(e2) {
  const t2 = q3(), n = e2.editor || (t2 == null ? void 0 : t2.editor) || null, o2 = e2.on || "all", [r4] = (0, import_react12.useState)(() => new ko4(n)), i3 = vo4.useSyncExternalStoreWithSelector(
    r4.subscribe,
    r4.getSnapshot,
    r4.getServerSnapshot,
    e2.selector,
    e2.equalityFn ?? ho3
  );
  return wo4(() => r4.watch(n, o2), [n, r4, o2]), (0, import_react12.useDebugValue)(i3), i3;
}
var Ue = (e2) => {
  const { position: t2, children: n, ...o2 } = e2, { from: r4, to: i3 } = t2 || {}, c3 = v7(), s2 = (0, import_react12.useMemo)(() => {
    var a3;
    if (!(r4 === void 0 || i3 === void 0))
      return {
        // Use first child as the editor DOM element may itself be scrollable.
        // For FloatingUI to auto-update the position during scrolling, the
        // `contextElement` must be a descendant of the scroll container.
        element: ((a3 = c3.domElement) == null ? void 0 : a3.firstElementChild) || void 0,
        getBoundingClientRect: () => posToDOMRect(c3.prosemirrorView, r4, i3 ?? r4)
      };
  }, [c3, r4, i3]);
  return (0, import_jsx_runtime10.jsx)(U4, { reference: s2, ...o2, children: t2 !== void 0 && n });
};
var Rt4 = {
  color: void 0,
  size: void 0,
  className: void 0,
  style: void 0,
  attr: void 0
};
var ct = import_react12.default.createContext && import_react12.default.createContext(Rt4);
var Ho3 = ["attr", "size", "title"];
function xo4(e2, t2) {
  if (e2 == null) return {};
  var n = yo4(e2, t2), o2, r4;
  if (Object.getOwnPropertySymbols) {
    var i3 = Object.getOwnPropertySymbols(e2);
    for (r4 = 0; r4 < i3.length; r4++)
      o2 = i3[r4], !(t2.indexOf(o2) >= 0) && Object.prototype.propertyIsEnumerable.call(e2, o2) && (n[o2] = e2[o2]);
  }
  return n;
}
function yo4(e2, t2) {
  if (e2 == null) return {};
  var n = {};
  for (var o2 in e2)
    if (Object.prototype.hasOwnProperty.call(e2, o2)) {
      if (t2.indexOf(o2) >= 0) continue;
      n[o2] = e2[o2];
    }
  return n;
}
function ge2() {
  return ge2 = Object.assign ? Object.assign.bind() : function(e2) {
    for (var t2 = 1; t2 < arguments.length; t2++) {
      var n = arguments[t2];
      for (var o2 in n)
        Object.prototype.hasOwnProperty.call(n, o2) && (e2[o2] = n[o2]);
    }
    return e2;
  }, ge2.apply(this, arguments);
}
function at(e2, t2) {
  var n = Object.keys(e2);
  if (Object.getOwnPropertySymbols) {
    var o2 = Object.getOwnPropertySymbols(e2);
    t2 && (o2 = o2.filter(function(r4) {
      return Object.getOwnPropertyDescriptor(e2, r4).enumerable;
    })), n.push.apply(n, o2);
  }
  return n;
}
function be2(e2) {
  for (var t2 = 1; t2 < arguments.length; t2++) {
    var n = arguments[t2] != null ? arguments[t2] : {};
    t2 % 2 ? at(Object(n), true).forEach(function(o2) {
      So4(e2, o2, n[o2]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(n)) : at(Object(n)).forEach(function(o2) {
      Object.defineProperty(e2, o2, Object.getOwnPropertyDescriptor(n, o2));
    });
  }
  return e2;
}
function So4(e2, t2, n) {
  return t2 = Mo3(t2), t2 in e2 ? Object.defineProperty(e2, t2, { value: n, enumerable: true, configurable: true, writable: true }) : e2[t2] = n, e2;
}
function Mo3(e2) {
  var t2 = Vo2(e2, "string");
  return typeof t2 == "symbol" ? t2 : t2 + "";
}
function Vo2(e2, t2) {
  if (typeof e2 != "object" || !e2) return e2;
  var n = e2[Symbol.toPrimitive];
  if (n !== void 0) {
    var o2 = n.call(e2, t2);
    if (typeof o2 != "object") return o2;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (t2 === "string" ? String : Number)(e2);
}
function Ot4(e2) {
  return e2 && e2.map((t2, n) => import_react12.default.createElement(t2.tag, be2({
    key: n
  }, t2.attr), Ot4(t2.child)));
}
function k2(e2) {
  return (t2) => import_react12.default.createElement(To4, ge2({
    attr: be2({}, e2.attr)
  }, t2), Ot4(e2.child));
}
function To4(e2) {
  var t2 = (n) => {
    var {
      attr: o2,
      size: r4,
      title: i3
    } = e2, c3 = xo4(e2, Ho3), s2 = r4 || n.size || "1em", a3;
    return n.className && (a3 = n.className), e2.className && (a3 = (a3 ? a3 + " " : "") + e2.className), import_react12.default.createElement("svg", ge2({
      stroke: "currentColor",
      fill: "currentColor",
      strokeWidth: "0"
    }, n.attr, o2, c3, {
      className: a3,
      style: be2(be2({
        color: e2.color || n.color
      }, n.style), e2.style),
      height: s2,
      width: s2,
      xmlns: "http://www.w3.org/2000/svg"
    }), i3 && import_react12.default.createElement("title", null, i3), e2.children);
  };
  return ct !== void 0 ? import_react12.default.createElement(ct.Consumer, null, (n) => t2(n)) : t2(Rt4);
}
function _o2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M8 7V11L2 6L8 1V5H13C17.4183 5 21 8.58172 21 13C21 17.4183 17.4183 21 13 21H4V19H13C16.3137 19 19 16.3137 19 13C19 9.68629 16.3137 7 13 7H8Z" }, child: [] }] })(e2);
}
function It4(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M7.29117 20.8242L2 22L3.17581 16.7088C2.42544 15.3056 2 13.7025 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C10.2975 22 8.6944 21.5746 7.29117 20.8242ZM7.58075 18.711L8.23428 19.0605C9.38248 19.6745 10.6655 20 12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 13.3345 4.32549 14.6175 4.93949 15.7657L5.28896 16.4192L4.63416 19.3658L7.58075 18.711Z" }, child: [] }] })(e2);
}
function Eo4(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M7.24264 17.9967H3V13.754L14.435 2.319C14.8256 1.92848 15.4587 1.92848 15.8492 2.319L18.6777 5.14743C19.0682 5.53795 19.0682 6.17112 18.6777 6.56164L7.24264 17.9967ZM3 19.9967H21V21.9967H3V19.9967Z" }, child: [] }] })(e2);
}
function Bo4(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M23 12L15.9289 19.0711L14.5147 17.6569L20.1716 12L14.5147 6.34317L15.9289 4.92896L23 12ZM3.82843 12L9.48528 17.6569L8.07107 19.0711L1 12L8.07107 4.92896L9.48528 6.34317L3.82843 12Z" }, child: [] }] })(e2);
}
function je(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M3 8L9.00319 2H19.9978C20.5513 2 21 2.45531 21 2.9918V21.0082C21 21.556 20.5551 22 20.0066 22H3.9934C3.44476 22 3 21.5501 3 20.9932V8ZM10 4V9H5V20H19V4H10Z" }, child: [] }] })(e2);
}
function Lo3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M3 4H21V6H3V4ZM5 19H19V21H5V19ZM3 14H21V16H3V14ZM5 9H19V11H5V9Z" }, child: [] }] })(e2);
}
function Ro2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M3 4H21V6H3V4ZM3 19H21V21H3V19ZM3 14H21V16H3V14ZM3 9H21V11H3V9Z" }, child: [] }] })(e2);
}
function Oo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M3 4H21V6H3V4ZM3 19H17V21H3V19ZM3 14H21V16H3V14ZM3 9H17V11H3V9Z" }, child: [] }] })(e2);
}
function Io3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M3 4H21V6H3V4ZM7 19H21V21H7V19ZM3 14H21V16H3V14ZM7 9H21V11H7V9Z" }, child: [] }] })(e2);
}
function Po4(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M8 11H12.5C13.8807 11 15 9.88071 15 8.5C15 7.11929 13.8807 6 12.5 6H8V11ZM18 15.5C18 17.9853 15.9853 20 13.5 20H6V4H12.5C14.9853 4 17 6.01472 17 8.5C17 9.70431 16.5269 10.7981 15.7564 11.6058C17.0979 12.3847 18 13.837 18 15.5ZM8 13V18H13.5C14.8807 18 16 16.8807 16 15.5C16 14.1193 14.8807 13 13.5 13H8Z" }, child: [] }] })(e2);
}
function No3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M3.41436 5.99995L5.70726 3.70706L4.29304 2.29285L0.585938 5.99995L4.29304 9.70706L5.70726 8.29285L3.41436 5.99995ZM9.58594 5.99995L7.29304 3.70706L8.70726 2.29285L12.4144 5.99995L8.70726 9.70706L7.29304 8.29285L9.58594 5.99995ZM14.0002 2.99995H21.0002C21.5524 2.99995 22.0002 3.44767 22.0002 3.99995V20C22.0002 20.5522 21.5524 21 21.0002 21H3.00015C2.44787 21 2.00015 20.5522 2.00015 20V12H4.00015V19H20.0002V4.99995H14.0002V2.99995Z" }, child: [] }] })(e2);
}
function st(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M5.55397 22H3.3999L10.9999 3H12.9999L20.5999 22H18.4458L16.0458 16H7.95397L5.55397 22ZM8.75397 14H15.2458L11.9999 5.88517L8.75397 14Z" }, child: [] }] })(e2);
}
function pe3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M13 20H11V13H4V20H2V4H4V11H11V4H13V20ZM21.0005 8V20H19.0005L19 10.204L17 10.74V8.67L19.5005 8H21.0005Z" }, child: [] }] })(e2);
}
function Ce3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M4 4V11H11V4H13V20H11V13H4V20H2V4H4ZM18.5 8C20.5711 8 22.25 9.67893 22.25 11.75C22.25 12.6074 21.9623 13.3976 21.4781 14.0292L21.3302 14.2102L18.0343 18H22V20H15L14.9993 18.444L19.8207 12.8981C20.0881 12.5908 20.25 12.1893 20.25 11.75C20.25 10.7835 19.4665 10 18.5 10C17.5818 10 16.8288 10.7071 16.7558 11.6065L16.75 11.75H14.75C14.75 9.67893 16.4289 8 18.5 8Z" }, child: [] }] })(e2);
}
function ve3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M22 8L21.9984 10L19.4934 12.883C21.0823 13.3184 22.25 14.7728 22.25 16.5C22.25 18.5711 20.5711 20.25 18.5 20.25C16.674 20.25 15.1528 18.9449 14.8184 17.2166L16.7821 16.8352C16.9384 17.6413 17.6481 18.25 18.5 18.25C19.4665 18.25 20.25 17.4665 20.25 16.5C20.25 15.5335 19.4665 14.75 18.5 14.75C18.214 14.75 17.944 14.8186 17.7056 14.9403L16.3992 13.3932L19.3484 10H15V8H22ZM4 4V11H11V4H13V20H11V13H4V20H2V4H4Z" }, child: [] }] })(e2);
}
function Pt4(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M13 20H11V13H4V20H2V4H4V11H11V4H13V20ZM22 8V16H23.5V18H22V20H20V18H14.5V16.66L19.5 8H22ZM20 11.133L17.19 16H20V11.133Z" }, child: [] }] })(e2);
}
function Nt3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M22 8V10H17.6769L17.2126 12.6358C17.5435 12.5472 17.8912 12.5 18.25 12.5C20.4591 12.5 22.25 14.2909 22.25 16.5C22.25 18.7091 20.4591 20.5 18.25 20.5C16.4233 20.5 14.8827 19.2756 14.4039 17.6027L16.3271 17.0519C16.5667 17.8881 17.3369 18.5 18.25 18.5C19.3546 18.5 20.25 17.6046 20.25 16.5C20.25 15.3954 19.3546 14.5 18.25 14.5C17.6194 14.5 17.057 14.7918 16.6904 15.2478L14.8803 14.3439L16 8H22ZM4 4V11H11V4H13V20H11V13H4V20H2V4H4Z" }, child: [] }] })(e2);
}
function At4(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M21.097 8L18.499 12.5C20.7091 12.5 22.5 14.2909 22.5 16.5C22.5 18.7091 20.7091 20.5 18.5 20.5C16.2909 20.5 14.5 18.7091 14.5 16.5C14.5 15.7636 14.699 15.0737 15.0461 14.4811L18.788 8H21.097ZM4 4V11H11V4H13V20H11V13H4V20H2V4H4ZM18.5 14.5C17.3954 14.5 16.5 15.3954 16.5 16.5C16.5 17.6046 17.3954 18.5 18.5 18.5C19.6046 18.5 20.5 17.6046 20.5 16.5C20.5 15.3954 19.6046 14.5 18.5 14.5Z" }, child: [] }] })(e2);
}
function Ao3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M3 4H21V6H3V4ZM3 19H21V21H3V19ZM11 14H21V16H11V14ZM11 9H21V11H11V9ZM3 12.5L7 9V16L3 12.5Z" }, child: [] }] })(e2);
}
function Zo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M3 4H21V6H3V4ZM3 19H21V21H3V19ZM11 14H21V16H11V14ZM11 9H21V11H11V9ZM7 12.5L3 16V9L7 12.5Z" }, child: [] }] })(e2);
}
function dt3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M8 5H11V19H8V21H16V19H13V5H16V3H8V5ZM2 7C1.44772 7 1 7.44772 1 8V16C1 16.5523 1.44772 17 2 17H8V15H3V9H8V7H2ZM16 9H21V15H16V17H22C22.5523 17 23 16.5523 23 16V8C23 7.44772 22.5523 7 22 7H16V9Z" }, child: [] }] })(e2);
}
function Do2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M15 20H7V18H9.92661L12.0425 6H9V4H17V6H14.0734L11.9575 18H15V20Z" }, child: [] }] })(e2);
}
function Fo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M17 17H22V19H19V22H17V17ZM7 7H2V5H5V2H7V7ZM18.364 15.5355L16.9497 14.1213L18.364 12.7071C20.3166 10.7545 20.3166 7.58866 18.364 5.63604C16.4113 3.68342 13.2455 3.68342 11.2929 5.63604L9.87868 7.05025L8.46447 5.63604L9.87868 4.22183C12.6123 1.48816 17.0445 1.48816 19.7782 4.22183C22.5118 6.9555 22.5118 11.3877 19.7782 14.1213L18.364 15.5355ZM15.5355 18.364L14.1213 19.7782C11.3877 22.5118 6.9555 22.5118 4.22183 19.7782C1.48816 17.0445 1.48816 12.6123 4.22183 9.87868L5.63604 8.46447L7.05025 9.87868L5.63604 11.2929C3.68342 13.2455 3.68342 16.4113 5.63604 18.364C7.58866 20.3166 10.7545 20.3166 12.7071 18.364L14.1213 16.9497L15.5355 18.364ZM14.8284 7.75736L16.2426 9.17157L9.17157 16.2426L7.75736 14.8284L14.8284 7.75736Z" }, child: [] }] })(e2);
}
function Zt3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M18.3638 15.5355L16.9496 14.1213L18.3638 12.7071C20.3164 10.7545 20.3164 7.58866 18.3638 5.63604C16.4112 3.68341 13.2453 3.68341 11.2927 5.63604L9.87849 7.05025L8.46428 5.63604L9.87849 4.22182C12.6122 1.48815 17.0443 1.48815 19.778 4.22182C22.5117 6.95549 22.5117 11.3876 19.778 14.1213L18.3638 15.5355ZM15.5353 18.364L14.1211 19.7782C11.3875 22.5118 6.95531 22.5118 4.22164 19.7782C1.48797 17.0445 1.48797 12.6123 4.22164 9.87868L5.63585 8.46446L7.05007 9.87868L5.63585 11.2929C3.68323 13.2455 3.68323 16.4113 5.63585 18.364C7.58847 20.3166 10.7543 20.3166 12.7069 18.364L14.1211 16.9497L15.5353 18.364ZM14.8282 7.75736L16.2425 9.17157L9.17139 16.2426L7.75717 14.8284L14.8282 7.75736Z" }, child: [] }] })(e2);
}
function Dt4(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M8.00008 6V9H5.00008V6H8.00008ZM3.00008 4V11H10.0001V4H3.00008ZM13.0001 4H21.0001V6H13.0001V4ZM13.0001 11H21.0001V13H13.0001V11ZM13.0001 18H21.0001V20H13.0001V18ZM10.7072 16.2071L9.29297 14.7929L6.00008 18.0858L4.20718 16.2929L2.79297 17.7071L6.00008 20.9142L10.7072 16.2071Z" }, child: [] }] })(e2);
}
function Ft3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M8 4H21V6H8V4ZM5 3V6H6V7H3V6H4V4H3V3H5ZM3 14V11.5H5V11H3V10H6V12.5H4V13H6V14H3ZM5 19.5H3V18.5H5V18H3V17H6V21H3V20H5V19.5ZM8 11H21V13H8V11ZM8 18H21V20H8V18Z" }, child: [] }] })(e2);
}
function Gt2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M8 4H21V6H8V4ZM4.5 6.5C3.67157 6.5 3 5.82843 3 5C3 4.17157 3.67157 3.5 4.5 3.5C5.32843 3.5 6 4.17157 6 5C6 5.82843 5.32843 6.5 4.5 6.5ZM4.5 13.5C3.67157 13.5 3 12.8284 3 12C3 11.1716 3.67157 10.5 4.5 10.5C5.32843 10.5 6 11.1716 6 12C6 12.8284 5.32843 13.5 4.5 13.5ZM4.5 20.4C3.67157 20.4 3 19.7284 3 18.9C3 18.0716 3.67157 17.4 4.5 17.4C5.32843 17.4 6 18.0716 6 18.9C6 19.7284 5.32843 20.4 4.5 20.4ZM8 11H21V13H8V11ZM8 18H21V20H8V18Z" }, child: [] }] })(e2);
}
function Go2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M20 3C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3H20ZM11 5H5V10.999H7V9L10 12L7 15V13H5V19H11V17H13V19H19V13H17V15L14 12L17 9V10.999H19V5H13V7H11V5ZM13 13V15H11V13H13ZM13 9V11H11V9H13Z" }, child: [] }] })(e2);
}
function zo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M21 20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3H20C20.5523 3 21 3.44772 21 4V20ZM19 11V5H13.001V7H15L12 10L9 7H11V5H5V11H7V13H5V19H11V17H9L12 14L15 17H13.001V19H19V13H17V11H19ZM11 13H9V11H11V13ZM15 13H13V11H15V13Z" }, child: [] }] })(e2);
}
function zt3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M21 4H3V6H21V4ZM21 11H8V13H21V11ZM21 18H8V20H21V18ZM5 11H3V20H5V11Z" }, child: [] }] })(e2);
}
function Uo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M17.1538 14C17.3846 14.5161 17.5 15.0893 17.5 15.7196C17.5 17.0625 16.9762 18.1116 15.9286 18.867C14.8809 19.6223 13.4335 20 11.5862 20C9.94674 20 8.32335 19.6185 6.71592 18.8555V16.6009C8.23538 17.4783 9.7908 17.917 11.3822 17.917C13.9333 17.917 15.2128 17.1846 15.2208 15.7196C15.2208 15.0939 15.0049 14.5598 14.5731 14.1173C14.5339 14.0772 14.4939 14.0381 14.4531 14H3V12H21V14H17.1538ZM13.076 11H7.62908C7.4566 10.8433 7.29616 10.6692 7.14776 10.4778C6.71592 9.92084 6.5 9.24559 6.5 8.45207C6.5 7.21602 6.96583 6.165 7.89749 5.299C8.82916 4.43299 10.2706 4 12.2219 4C13.6934 4 15.1009 4.32808 16.4444 4.98426V7.13591C15.2448 6.44921 13.9293 6.10587 12.4978 6.10587C10.0187 6.10587 8.77917 6.88793 8.77917 8.45207C8.77917 8.87172 8.99709 9.23796 9.43293 9.55079C9.86878 9.86362 10.4066 10.1135 11.0463 10.3004C11.6665 10.4816 12.3431 10.7148 13.076 11H13.076Z" }, child: [] }] })(e2);
}
function jo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M13 10V14H19V10H13ZM11 10H5V14H11V10ZM13 19H19V16H13V19ZM11 19V16H5V19H11ZM13 5V8H19V5H13ZM11 5H5V8H11V5ZM4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3Z" }, child: [] }] })(e2);
}
function $e(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M13 6V21H11V6H5V4H19V6H13Z" }, child: [] }] })(e2);
}
function $o2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M8 3V12C8 14.2091 9.79086 16 12 16C14.2091 16 16 14.2091 16 12V3H18V12C18 15.3137 15.3137 18 12 18C8.68629 18 6 15.3137 6 12V3H8ZM4 20H20V22H4V20Z" }, child: [] }] })(e2);
}
function Wo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M2 3.9934C2 3.44476 2.45531 3 2.9918 3H21.0082C21.556 3 22 3.44495 22 3.9934V20.0066C22 20.5552 21.5447 21 21.0082 21H2.9918C2.44405 21 2 20.5551 2 20.0066V3.9934ZM8 5V19H16V5H8ZM4 5V7H6V5H4ZM18 5V7H20V5H18ZM4 9V11H6V9H4ZM18 9V11H20V9H18ZM4 13V15H6V13H4ZM18 13V15H20V13H18ZM4 17V19H6V17H4ZM18 17V19H20V17H18Z" }, child: [] }] })(e2);
}
function Ut3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M5 11.1005L7 9.1005L12.5 14.6005L16 11.1005L19 14.1005V5H5V11.1005ZM4 3H20C20.5523 3 21 3.44772 21 4V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3ZM15.5 10C14.6716 10 14 9.32843 14 8.5C14 7.67157 14.6716 7 15.5 7C16.3284 7 17 7.67157 17 8.5C17 9.32843 16.3284 10 15.5 10Z" }, child: [] }] })(e2);
}
function qo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M21 15V18H24V20H21V23H19V20H16V18H19V15H21ZM21.0082 3C21.556 3 22 3.44495 22 3.9934L22.0007 13.3417C21.3749 13.1204 20.7015 13 20 13V5H4L4.001 19L13.2929 9.70715C13.6528 9.34604 14.22 9.31823 14.6123 9.62322L14.7065 9.70772L18.2521 13.2586C15.791 14.0069 14 16.2943 14 19C14 19.7015 14.1204 20.3749 14.3417 21.0007L2.9918 21C2.44405 21 2 20.5551 2 20.0066V3.9934C2 3.44476 2.45531 3 2.9918 3H21.0082ZM8 7C9.10457 7 10 7.89543 10 9C10 10.1046 9.10457 11 8 11C6.89543 11 6 10.1046 6 9C6 7.89543 6.89543 7 8 7Z" }, child: [] }] })(e2);
}
function Ko2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M20 3C20.5523 3 21 3.44772 21 4V5.757L19 7.757V5H5V13.1L9 9.1005L13.328 13.429L12.0012 14.7562L11.995 18.995L16.2414 19.0012L17.571 17.671L18.8995 19H19V16.242L21 14.242V20C21 20.5523 20.5523 21 20 21H4C3.44772 21 3 20.5523 3 20V4C3 3.44772 3.44772 3 4 3H20ZM21.7782 7.80761L23.1924 9.22183L15.4142 17L13.9979 16.9979L14 15.5858L21.7782 7.80761ZM15.5 7C16.3284 7 17 7.67157 17 8.5C17 9.32843 16.3284 10 15.5 10C14.6716 10 14 9.32843 14 8.5C14 7.67157 14.6716 7 15.5 7Z" }, child: [] }] })(e2);
}
function jt2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M22 18V20H2V18H22ZM2 3.5L10 8.5L2 13.5V3.5ZM22 11V13H12V11H22ZM22 4V6H12V4H22Z" }, child: [] }] })(e2);
}
function Xo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M3 3.9934C3 3.44476 3.44495 3 3.9934 3H20.0066C20.5552 3 21 3.44495 21 3.9934V20.0066C21 20.5552 20.5551 21 20.0066 21H3.9934C3.44476 21 3 20.5551 3 20.0066V3.9934ZM10.6219 8.41459C10.5562 8.37078 10.479 8.34741 10.4 8.34741C10.1791 8.34741 10 8.52649 10 8.74741V15.2526C10 15.3316 10.0234 15.4088 10.0672 15.4745C10.1897 15.6583 10.4381 15.708 10.6219 15.5854L15.5008 12.3328C15.5447 12.3035 15.5824 12.2658 15.6117 12.2219C15.7343 12.0381 15.6846 11.7897 15.5008 11.6672L10.6219 8.41459Z" }, child: [] }] })(e2);
}
function $t4(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M2 16.0001H5.88889L11.1834 20.3319C11.2727 20.405 11.3846 20.4449 11.5 20.4449C11.7761 20.4449 12 20.2211 12 19.9449V4.05519C12 3.93977 11.9601 3.8279 11.887 3.73857C11.7121 3.52485 11.3971 3.49335 11.1834 3.66821L5.88889 8.00007H2C1.44772 8.00007 1 8.44778 1 9.00007V15.0001C1 15.5524 1.44772 16.0001 2 16.0001ZM23 12C23 15.292 21.5539 18.2463 19.2622 20.2622L17.8445 18.8444C19.7758 17.1937 21 14.7398 21 12C21 9.26016 19.7758 6.80629 17.8445 5.15557L19.2622 3.73779C21.5539 5.75368 23 8.70795 23 12ZM18 12C18 10.0883 17.106 8.38548 15.7133 7.28673L14.2842 8.71584C15.3213 9.43855 16 10.64 16 12C16 13.36 15.3213 14.5614 14.2842 15.2841L15.7133 16.7132C17.106 15.6145 18 13.9116 18 12Z" }, child: [] }] })(e2);
}
function Yo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M11 11V5H13V11H19V13H13V19H11V13H5V11H11Z" }, child: [] }] })(e2);
}
function Jo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M9.9997 15.1709L19.1921 5.97852L20.6063 7.39273L9.9997 17.9993L3.63574 11.6354L5.04996 10.2212L9.9997 15.1709Z" }, child: [] }] })(e2);
}
function Qo2(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M17 6H22V8H20V21C20 21.5523 19.5523 22 19 22H5C4.44772 22 4 21.5523 4 21V8H2V6H7V3C7 2.44772 7.44772 2 8 2H16C16.5523 2 17 2.44772 17 3V6ZM18 8H6V20H18V8ZM9 4V6H15V4H9Z" }, child: [] }] })(e2);
}
function er(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M17 6H22V8H20V21C20 21.5523 19.5523 22 19 22H5C4.44772 22 4 21.5523 4 21V8H2V6H7V3C7 2.44772 7.44772 2 8 2H16C16.5523 2 17 2.44772 17 3V6ZM9 11V17H11V11H9ZM13 11V17H15V11H13ZM9 4V6H15V4H9Z" }, child: [] }] })(e2);
}
function tr3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M4 19H20V12H22V20C22 20.5523 21.5523 21 21 21H3C2.44772 21 2 20.5523 2 20V12H4V19ZM14 9H19L12 16L5 9H10V3H14V9Z" }, child: [] }] })(e2);
}
function nr(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M10 6V8H5V19H16V14H18V20C18 20.5523 17.5523 21 17 21H4C3.44772 21 3 20.5523 3 20V7C3 6.44772 3.44772 6 4 6H10ZM21 3V12L17.206 8.207L11.2071 14.2071L9.79289 12.7929L15.792 6.793L12 3H21Z" }, child: [] }] })(e2);
}
function or(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M5 10C3.9 10 3 10.9 3 12C3 13.1 3.9 14 5 14C6.1 14 7 13.1 7 12C7 10.9 6.1 10 5 10ZM19 10C17.9 10 17 10.9 17 12C17 13.1 17.9 14 19 14C20.1 14 21 13.1 21 12C21 10.9 20.1 10 19 10ZM12 10C10.9 10 10 10.9 10 12C10 13.1 10.9 14 12 14C13.1 14 14 13.1 14 12C14 10.9 13.1 10 12 10Z" }, child: [] }] })(e2);
}
function rr(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M5 11V13H19V11H5Z" }, child: [] }] })(e2);
}
function ir(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM8 13C8 15.2091 9.79086 17 12 17C14.2091 17 16 15.2091 16 13H8ZM8 11C8.82843 11 9.5 10.3284 9.5 9.5C9.5 8.67157 8.82843 8 8 8C7.17157 8 6.5 8.67157 6.5 9.5C6.5 10.3284 7.17157 11 8 11ZM16 11C16.8284 11 17.5 10.3284 17.5 9.5C17.5 8.67157 16.8284 8 16 8C15.1716 8 14.5 8.67157 14.5 9.5C14.5 10.3284 15.1716 11 16 11Z" }, child: [] }] })(e2);
}
function ut(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "currentColor" }, child: [{ tag: "path", attr: { d: "M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 20C16.4183 20 20 16.4183 20 12C20 7.58172 16.4183 4 12 4C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20ZM8 13H16C16 15.2091 14.2091 17 12 17C9.79086 17 8 15.2091 8 13ZM8 11C7.17157 11 6.5 10.3284 6.5 9.5C6.5 8.67157 7.17157 8 8 8C8.82843 8 9.5 8.67157 9.5 9.5C9.5 10.3284 8.82843 11 8 11ZM16 11C15.1716 11 14.5 10.3284 14.5 9.5C14.5 8.67157 15.1716 8 16 8C16.8284 8 17.5 8.67157 17.5 9.5C17.5 10.3284 16.8284 11 16 11Z" }, child: [] }] })(e2);
}
var lr = {
  bold: Po4,
  italic: Do2,
  underline: $o2,
  strike: Uo2,
  code: Bo4
};
function cr(e2, t2) {
  return e2 in t2.schema.styleSchema && t2.schema.styleSchema[e2].type === e2 && t2.schema.styleSchema[e2].propSchema === "boolean";
}
var de3 = (e2) => {
  const t2 = M6(), n = w2(), o2 = v7(), r4 = R4({
    editor: o2,
    selector: ({ editor: s2 }) => {
      var a3;
      if (
        // The editor is read-only.
        !(!s2.isEditable || // The style is not in the schema.
        !cr(e2.basicTextStyle, s2) || // None of the selected blocks have inline content
        !(((a3 = s2.getSelection()) == null ? void 0 : a3.blocks) || [
          s2.getTextCursorPosition().block
        ]).find((u2) => u2.content !== void 0))
      )
        return e2.basicTextStyle in s2.getActiveStyles() ? { active: true } : { active: false };
    }
  }), i3 = (0, import_react12.useCallback)(
    (s2) => {
      o2.focus(), o2.toggleStyles({ [s2]: true });
    },
    [o2, e2]
  );
  if (r4 === void 0)
    return null;
  const c3 = lr[e2.basicTextStyle];
  return (0, import_jsx_runtime10.jsx)(
    n.FormattingToolbar.Button,
    {
      className: "bn-button",
      "data-test": e2.basicTextStyle,
      onClick: () => i3(e2.basicTextStyle),
      isSelected: r4.active,
      label: t2.formatting_toolbar[e2.basicTextStyle].tooltip,
      mainTooltip: t2.formatting_toolbar[e2.basicTextStyle].tooltip,
      secondaryTooltip: L2(
        t2.formatting_toolbar[e2.basicTextStyle].secondary_tooltip,
        t2.generic.ctrl_shortcut
      ),
      icon: (0, import_jsx_runtime10.jsx)(c3, {})
    }
  );
};
var Pe3 = (e2) => {
  const t2 = e2.textColor || "default", n = e2.backgroundColor || "default", o2 = e2.size || 16, r4 = (0, import_react12.useMemo)(
    () => ({
      pointerEvents: "none",
      fontSize: (o2 * 0.75).toString() + "px",
      height: o2.toString() + "px",
      lineHeight: o2.toString() + "px",
      textAlign: "center",
      width: o2.toString() + "px"
    }),
    [o2]
  );
  return (0, import_jsx_runtime10.jsx)(
    "div",
    {
      className: "bn-color-icon",
      "data-background-color": n,
      "data-text-color": t2,
      style: r4,
      children: "A"
    }
  );
};
var mt3 = [
  "default",
  "gray",
  "brown",
  "red",
  "orange",
  "yellow",
  "green",
  "blue",
  "purple",
  "pink"
];
var xe3 = (e2) => {
  const t2 = w2(), n = M6();
  return (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
    (0, import_jsx_runtime10.jsx)(() => e2.text ? (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
      (0, import_jsx_runtime10.jsx)(t2.Generic.Menu.Label, { children: n.color_picker.text_title }),
      mt3.map((i3) => (0, import_jsx_runtime10.jsx)(
        t2.Generic.Menu.Item,
        {
          onClick: () => {
            e2.onClick && e2.onClick(), e2.text.setColor(i3);
          },
          "data-test": "text-color-" + i3,
          icon: (0, import_jsx_runtime10.jsx)(Pe3, { textColor: i3, size: e2.iconSize }),
          checked: e2.text.color === i3,
          children: n.color_picker.colors[i3]
        },
        "text-color-" + i3
      ))
    ] }) : null, {}),
    (0, import_jsx_runtime10.jsx)(() => e2.background ? (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
      (0, import_jsx_runtime10.jsx)(t2.Generic.Menu.Label, { children: n.color_picker.background_title }),
      mt3.map((i3) => (0, import_jsx_runtime10.jsx)(
        t2.Generic.Menu.Item,
        {
          onClick: () => {
            e2.onClick && e2.onClick(), e2.background.setColor(i3);
          },
          "data-test": "background-color-" + i3,
          icon: (0, import_jsx_runtime10.jsx)(Pe3, { backgroundColor: i3, size: e2.iconSize }),
          checked: e2.background.color === i3,
          children: n.color_picker.colors[i3]
        },
        "background-color-" + i3
      ))
    ] }) : null, {})
  ] });
};
function ue3(e2, t2) {
  return `${e2}Color` in t2.schema.styleSchema && t2.schema.styleSchema[`${e2}Color`].type === `${e2}Color` && t2.schema.styleSchema[`${e2}Color`].propSchema === "string";
}
var ar = () => {
  const e2 = w2(), t2 = M6(), n = v7(), o2 = ue3("text", n), r4 = ue3("background", n), i3 = R4({
    editor: n,
    selector: ({ editor: a3 }) => {
      var m2;
      if (
        // The editor is read-only.
        !a3.isEditable || // None of the selected blocks have inline content
        !(((m2 = a3.getSelection()) == null ? void 0 : m2.blocks) || [
          a3.getTextCursorPosition().block
        ]).find((h7) => h7.content !== void 0)
      )
        return;
      const u2 = ue3("text", a3), d = ue3("background", a3);
      if (!(!u2 && !d))
        return {
          textColor: u2 ? a3.getActiveStyles().textColor || "default" : void 0,
          backgroundColor: d ? a3.getActiveStyles().backgroundColor || "default" : void 0
        };
    }
  }), c3 = (0, import_react12.useCallback)(
    (a3) => {
      if (!o2)
        throw Error(
          "Tried to set text color, but style does not exist in editor schema."
        );
      a3 === "default" ? n.removeStyles({ textColor: a3 }) : n.addStyles({ textColor: a3 }), setTimeout(() => {
        n.focus();
      });
    },
    [n, o2]
  ), s2 = (0, import_react12.useCallback)(
    (a3) => {
      if (!r4)
        throw Error(
          "Tried to set background color, but style does not exist in editor schema."
        );
      a3 === "default" ? n.removeStyles({ backgroundColor: a3 }) : n.addStyles({ backgroundColor: a3 }), setTimeout(() => {
        n.focus();
      });
    },
    [r4, n]
  );
  return i3 === void 0 ? null : (0, import_jsx_runtime10.jsxs)(e2.Generic.Menu.Root, { children: [
    (0, import_jsx_runtime10.jsx)(e2.Generic.Menu.Trigger, { children: (0, import_jsx_runtime10.jsx)(
      e2.FormattingToolbar.Button,
      {
        className: "bn-button",
        "data-test": "colors",
        label: t2.formatting_toolbar.colors.tooltip,
        mainTooltip: t2.formatting_toolbar.colors.tooltip,
        icon: (0, import_jsx_runtime10.jsx)(
          Pe3,
          {
            textColor: i3.textColor,
            backgroundColor: i3.backgroundColor,
            size: 20
          }
        )
      }
    ) }),
    (0, import_jsx_runtime10.jsx)(
      e2.Generic.Menu.Dropdown,
      {
        className: "bn-menu-dropdown bn-color-picker-dropdown",
        children: (0, import_jsx_runtime10.jsx)(
          xe3,
          {
            text: i3.textColor ? {
              color: i3.textColor,
              setColor: c3
            } : void 0,
            background: i3.backgroundColor ? {
              color: i3.backgroundColor,
              setColor: s2
            } : void 0
          }
        )
      }
    )
  ] });
};
var ft = (e2) => {
  for (const t2 of ko2)
    if (e2.startsWith(t2))
      return e2;
  return `${Co}://${e2}`;
};
var Wt2 = (e2) => {
  const t2 = w2(), n = M6(), { editLink: o2 } = T3(vo), { url: r4, text: i3, showTextField: c3 } = e2, [s2, a3] = (0, import_react12.useState)(r4), [u2, d] = (0, import_react12.useState)(i3);
  (0, import_react12.useEffect)(() => {
    a3(r4), d(i3);
  }, [i3, r4]);
  const m2 = (0, import_react12.useCallback)(
    (b4) => {
      var p4, C3;
      b4.key === "Enter" && (b4.preventDefault(), o2(ft(s2), u2, e2.range.from), (p4 = e2.setToolbarOpen) == null || p4.call(e2, false), (C3 = e2.setToolbarPositionFrozen) == null || C3.call(e2, false));
    },
    [o2, s2, u2, e2]
  ), h7 = (0, import_react12.useCallback)(
    (b4) => a3(b4.currentTarget.value),
    []
  ), f6 = (0, import_react12.useCallback)(
    (b4) => d(b4.currentTarget.value),
    []
  ), g = (0, import_react12.useCallback)(() => {
    var b4, p4;
    o2(ft(s2), u2, e2.range.from), (b4 = e2.setToolbarOpen) == null || b4.call(e2, false), (p4 = e2.setToolbarPositionFrozen) == null || p4.call(e2, false);
  }, [o2, s2, u2, e2]);
  return (0, import_jsx_runtime10.jsxs)(t2.Generic.Form.Root, { children: [
    (0, import_jsx_runtime10.jsx)(
      t2.Generic.Form.TextInput,
      {
        className: "bn-text-input",
        name: "url",
        icon: (0, import_jsx_runtime10.jsx)(Zt3, {}),
        autoFocus: true,
        placeholder: n.link_toolbar.form.url_placeholder,
        value: s2,
        onKeyDown: m2,
        onChange: h7,
        onSubmit: g
      }
    ),
    c3 !== false && (0, import_jsx_runtime10.jsx)(
      t2.Generic.Form.TextInput,
      {
        className: "bn-text-input",
        name: "title",
        icon: (0, import_jsx_runtime10.jsx)($e, {}),
        placeholder: n.link_toolbar.form.title_placeholder,
        value: u2,
        onKeyDown: m2,
        onChange: f6,
        onSubmit: g
      }
    )
  ] });
};
function sr(e2) {
  return "link" in e2.schema.inlineContentSchema && e2.schema.inlineContentSchema.link === "link";
}
var dr = () => {
  const e2 = v7(), t2 = w2(), n = M6(), o2 = T3(yo2), { showSelection: r4 } = T3(f2), [i3, c3] = (0, import_react12.useState)(false);
  (0, import_react12.useEffect)(() => (r4(i3), () => r4(false)), [i3, r4]);
  const s2 = R4({
    editor: e2,
    selector: ({ editor: a3 }) => {
      var u2;
      if (
        // The editor is read-only.
        !(!a3.isEditable || // Links are not in the schema.
        !sr(a3) || // Table cells are selected.
        To(a3.prosemirrorState.selection) || // None of the selected blocks have inline content
        !(((u2 = a3.getSelection()) == null ? void 0 : u2.blocks) || [
          a3.getTextCursorPosition().block
        ]).find((d) => d.content !== void 0))
      )
        return {
          url: a3.getSelectedLinkUrl(),
          text: a3.getSelectedText(),
          range: {
            from: a3.prosemirrorState.selection.from,
            to: a3.prosemirrorState.selection.to
          }
        };
    }
  });
  return (0, import_react12.useEffect)(() => {
    var u2;
    const a3 = (d) => {
      (d.ctrlKey || d.metaKey) && d.key === "k" && (c3(true), d.preventDefault());
    };
    return (u2 = e2.domElement) == null || u2.addEventListener("keydown", a3), () => {
      var d;
      (d = e2.domElement) == null || d.removeEventListener("keydown", a3);
    };
  }, [e2.domElement]), s2 === void 0 ? null : (0, import_jsx_runtime10.jsxs)(t2.Generic.Popover.Root, { open: i3, children: [
    (0, import_jsx_runtime10.jsx)(t2.Generic.Popover.Trigger, { children: (0, import_jsx_runtime10.jsx)(
      t2.FormattingToolbar.Button,
      {
        className: "bn-button",
        "data-test": "createLink",
        label: n.formatting_toolbar.link.tooltip,
        mainTooltip: n.formatting_toolbar.link.tooltip,
        secondaryTooltip: L2(
          n.formatting_toolbar.link.secondary_tooltip,
          n.generic.ctrl_shortcut
        ),
        icon: (0, import_jsx_runtime10.jsx)(Zt3, {}),
        onClick: () => c3(true)
      }
    ) }),
    (0, import_jsx_runtime10.jsx)(
      t2.Generic.Popover.Content,
      {
        className: "bn-popover-content bn-form-popover",
        variant: "form-popover",
        children: (0, import_jsx_runtime10.jsx)(
          Wt2,
          {
            url: s2.url || "",
            text: s2.text,
            range: s2.range,
            showTextField: false,
            setToolbarOpen: (a3) => o2.store.setState(a3)
          }
        )
      }
    )
  ] });
};
var ur = () => {
  const e2 = M6(), t2 = w2(), n = v7(), o2 = R4({
    editor: n,
    selector: ({ editor: a3 }) => {
      var m2;
      if (!a3.isEditable)
        return;
      const u2 = ((m2 = a3.getSelection()) == null ? void 0 : m2.blocks) || [
        a3.getTextCursorPosition().block
      ];
      if (u2.length !== 1)
        return;
      const d = u2[0];
      if (Lo(d, a3, d.type, {
        url: "string",
        caption: "string"
      }))
        return d;
    }
  }), [r4, i3] = (0, import_react12.useState)();
  (0, import_react12.useEffect)(() => {
    o2 !== void 0 && i3(o2.props.caption);
  }, [o2]);
  const c3 = (0, import_react12.useCallback)(
    (a3) => i3(a3.currentTarget.value),
    []
  ), s2 = (0, import_react12.useCallback)(
    (a3) => {
      o2 !== void 0 && b2(n, o2.type, {
        caption: "string"
      }) && a3.key === "Enter" && (a3.preventDefault(), n.updateBlock(o2.id, {
        props: {
          caption: r4
        }
      }));
    },
    [o2, r4, n]
  );
  return o2 === void 0 ? null : (0, import_jsx_runtime10.jsxs)(t2.Generic.Popover.Root, { children: [
    (0, import_jsx_runtime10.jsx)(t2.Generic.Popover.Trigger, { children: (0, import_jsx_runtime10.jsx)(
      t2.FormattingToolbar.Button,
      {
        className: "bn-button",
        label: e2.formatting_toolbar.file_caption.tooltip,
        mainTooltip: e2.formatting_toolbar.file_caption.tooltip,
        icon: (0, import_jsx_runtime10.jsx)(dt3, {})
      }
    ) }),
    (0, import_jsx_runtime10.jsx)(
      t2.Generic.Popover.Content,
      {
        className: "bn-popover-content bn-form-popover",
        variant: "form-popover",
        children: (0, import_jsx_runtime10.jsx)(t2.Generic.Form.Root, { children: (0, import_jsx_runtime10.jsx)(
          t2.Generic.Form.TextInput,
          {
            name: "file-caption",
            icon: (0, import_jsx_runtime10.jsx)(dt3, {}),
            value: r4 || "",
            autoFocus: true,
            placeholder: e2.formatting_toolbar.file_caption.input_placeholder,
            onKeyDown: s2,
            onChange: c3
          }
        ) })
      }
    )
  ] });
};
var mr = () => {
  const e2 = M6(), t2 = w2(), n = v7(), o2 = R4({
    editor: n,
    selector: ({ editor: i3 }) => {
      var a3;
      if (!i3.isEditable)
        return;
      const c3 = ((a3 = i3.getSelection()) == null ? void 0 : a3.blocks) || [
        i3.getTextCursorPosition().block
      ];
      if (c3.length !== 1)
        return;
      const s2 = c3[0];
      if (Lo(s2, i3, s2.type, {
        url: "string"
      }))
        return s2;
    }
  }), r4 = (0, import_react12.useCallback)(() => {
    o2 !== void 0 && (n.focus(), n.removeBlocks([o2.id]));
  }, [o2, n]);
  return o2 === void 0 ? null : (0, import_jsx_runtime10.jsx)(
    t2.FormattingToolbar.Button,
    {
      className: "bn-button",
      label: e2.formatting_toolbar.file_delete.tooltip[o2.type] || e2.formatting_toolbar.file_delete.tooltip.file,
      mainTooltip: e2.formatting_toolbar.file_delete.tooltip[o2.type] || e2.formatting_toolbar.file_delete.tooltip.file,
      icon: (0, import_jsx_runtime10.jsx)(Qo2, {}),
      onClick: r4
    }
  );
};
var fr = () => {
  const e2 = M6(), t2 = w2(), n = v7(), o2 = R4({
    editor: n,
    selector: ({ editor: a3 }) => {
      var m2;
      if (!a3.isEditable)
        return;
      const u2 = ((m2 = a3.getSelection()) == null ? void 0 : m2.blocks) || [
        a3.getTextCursorPosition().block
      ];
      if (u2.length !== 1)
        return;
      const d = u2[0];
      if (Lo(d, a3, d.type, {
        url: "string",
        name: "string"
      }))
        return d;
    }
  }), [r4, i3] = (0, import_react12.useState)();
  (0, import_react12.useEffect)(() => {
    o2 !== void 0 && i3(o2.props.name);
  }, [o2]);
  const c3 = (0, import_react12.useCallback)(
    (a3) => i3(a3.currentTarget.value),
    []
  ), s2 = (0, import_react12.useCallback)(
    (a3) => {
      o2 !== void 0 && b2(n, o2.type, {
        name: "string"
      }) && a3.key === "Enter" && (a3.preventDefault(), n.updateBlock(o2.id, {
        props: {
          name: r4
        }
      }));
    },
    [o2, r4, n]
  );
  return o2 === void 0 ? null : (0, import_jsx_runtime10.jsxs)(t2.Generic.Popover.Root, { children: [
    (0, import_jsx_runtime10.jsx)(t2.Generic.Popover.Trigger, { children: (0, import_jsx_runtime10.jsx)(
      t2.FormattingToolbar.Button,
      {
        className: "bn-button",
        label: e2.formatting_toolbar.file_rename.tooltip[o2.type] || e2.formatting_toolbar.file_rename.tooltip.file,
        mainTooltip: e2.formatting_toolbar.file_rename.tooltip[o2.type] || e2.formatting_toolbar.file_rename.tooltip.file,
        icon: (0, import_jsx_runtime10.jsx)(st, {})
      }
    ) }),
    (0, import_jsx_runtime10.jsx)(
      t2.Generic.Popover.Content,
      {
        className: "bn-popover-content bn-form-popover",
        variant: "form-popover",
        children: (0, import_jsx_runtime10.jsx)(t2.Generic.Form.Root, { children: (0, import_jsx_runtime10.jsx)(
          t2.Generic.Form.TextInput,
          {
            name: "file-name",
            icon: (0, import_jsx_runtime10.jsx)(st, {}),
            value: r4 || "",
            autoFocus: true,
            placeholder: e2.formatting_toolbar.file_rename.input_placeholder[o2.type] || e2.formatting_toolbar.file_rename.input_placeholder.file,
            onKeyDown: s2,
            onChange: c3
          }
        ) })
      }
    )
  ] });
};
var hr2 = () => {
  const e2 = M6(), t2 = w2(), n = v7(), o2 = R4({
    editor: n,
    selector: ({ editor: r4 }) => {
      var s2;
      if (!r4.isEditable)
        return;
      const i3 = ((s2 = r4.getSelection()) == null ? void 0 : s2.blocks) || [
        r4.getTextCursorPosition().block
      ];
      if (i3.length !== 1)
        return;
      const c3 = i3[0];
      if (Lo(c3, r4, c3.type, {
        url: "string"
      }))
        return c3;
    }
  });
  return o2 === void 0 ? null : (0, import_jsx_runtime10.jsxs)(t2.Generic.Popover.Root, { position: "bottom", children: [
    (0, import_jsx_runtime10.jsx)(t2.Generic.Popover.Trigger, { children: (0, import_jsx_runtime10.jsx)(
      t2.FormattingToolbar.Button,
      {
        className: "bn-button",
        mainTooltip: e2.formatting_toolbar.file_replace.tooltip[o2.type] || e2.formatting_toolbar.file_replace.tooltip.file,
        label: e2.formatting_toolbar.file_replace.tooltip[o2.type] || e2.formatting_toolbar.file_replace.tooltip.file,
        icon: (0, import_jsx_runtime10.jsx)(Ko2, {})
      }
    ) }),
    (0, import_jsx_runtime10.jsx)(
      t2.Generic.Popover.Content,
      {
        className: "bn-popover-content bn-panel-popover",
        variant: "panel-popover",
        children: (0, import_jsx_runtime10.jsx)(Et3, { blockId: o2.id })
      }
    )
  ] });
};
var gr = () => {
  const e2 = M6(), t2 = w2(), n = v7(), o2 = R4({
    editor: n,
    selector: ({ editor: i3 }) => {
      var c3;
      if (
        // The editor is read-only.
        !(!i3.isEditable || // None of the selected blocks have inline content
        !(((c3 = i3.getSelection()) == null ? void 0 : c3.blocks) || [
          i3.getTextCursorPosition().block
        ]).find((s2) => s2.content !== void 0))
      )
        return {
          canNestBlock: i3.canNestBlock()
        };
    }
  }), r4 = (0, import_react12.useCallback)(() => {
    o2 !== void 0 && o2.canNestBlock && (n.focus(), n.nestBlock());
  }, [n, o2]);
  return o2 === void 0 ? null : (0, import_jsx_runtime10.jsx)(
    t2.FormattingToolbar.Button,
    {
      className: "bn-button",
      "data-test": "nestBlock",
      onClick: r4,
      isDisabled: !o2.canNestBlock,
      label: e2.formatting_toolbar.nest.tooltip,
      mainTooltip: e2.formatting_toolbar.nest.tooltip,
      secondaryTooltip: L2(
        e2.formatting_toolbar.nest.secondary_tooltip,
        e2.generic.ctrl_shortcut
      ),
      icon: (0, import_jsx_runtime10.jsx)(Zo2, {})
    }
  );
};
var br3 = () => {
  const e2 = M6(), t2 = w2(), n = v7(), o2 = R4({
    editor: n,
    selector: ({ editor: i3 }) => {
      var c3;
      if (
        // The editor is read-only.
        !(!i3.isEditable || // None of the selected blocks have inline content
        !(((c3 = i3.getSelection()) == null ? void 0 : c3.blocks) || [
          i3.getTextCursorPosition().block
        ]).find((s2) => s2.content !== void 0))
      )
        return {
          canUnnestBlock: i3.canUnnestBlock()
        };
    }
  }), r4 = (0, import_react12.useCallback)(() => {
    o2 !== void 0 && o2.canUnnestBlock && (n.focus(), n.unnestBlock());
  }, [n, o2]);
  return o2 === void 0 ? null : (0, import_jsx_runtime10.jsx)(
    t2.FormattingToolbar.Button,
    {
      className: "bn-button",
      "data-test": "unnestBlock",
      onClick: r4,
      isDisabled: !o2.canUnnestBlock,
      label: e2.formatting_toolbar.unnest.tooltip,
      mainTooltip: e2.formatting_toolbar.unnest.tooltip,
      secondaryTooltip: L2(
        e2.formatting_toolbar.unnest.secondary_tooltip,
        e2.generic.ctrl_shortcut
      ),
      icon: (0, import_jsx_runtime10.jsx)(Ao3, {})
    }
  );
};
var pr = (e2) => [
  {
    name: e2.slash_menu.paragraph.title,
    type: "paragraph",
    icon: $e
  },
  {
    name: e2.slash_menu.heading.title,
    type: "heading",
    props: { level: 1, isToggleable: false },
    icon: pe3
  },
  {
    name: e2.slash_menu.heading_2.title,
    type: "heading",
    props: { level: 2, isToggleable: false },
    icon: Ce3
  },
  {
    name: e2.slash_menu.heading_3.title,
    type: "heading",
    props: { level: 3, isToggleable: false },
    icon: ve3
  },
  {
    name: e2.slash_menu.heading_4.title,
    type: "heading",
    props: { level: 4, isToggleable: false },
    icon: Pt4
  },
  {
    name: e2.slash_menu.heading_5.title,
    type: "heading",
    props: { level: 5, isToggleable: false },
    icon: Nt3
  },
  {
    name: e2.slash_menu.heading_6.title,
    type: "heading",
    props: { level: 6, isToggleable: false },
    icon: At4
  },
  {
    name: e2.slash_menu.toggle_heading.title,
    type: "heading",
    props: { level: 1, isToggleable: true },
    icon: pe3
  },
  {
    name: e2.slash_menu.toggle_heading_2.title,
    type: "heading",
    props: { level: 2, isToggleable: true },
    icon: Ce3
  },
  {
    name: e2.slash_menu.toggle_heading_3.title,
    type: "heading",
    props: { level: 3, isToggleable: true },
    icon: ve3
  },
  {
    name: e2.slash_menu.quote.title,
    type: "quote",
    icon: zt3
  },
  {
    name: e2.slash_menu.toggle_list.title,
    type: "toggleListItem",
    icon: jt2
  },
  {
    name: e2.slash_menu.bullet_list.title,
    type: "bulletListItem",
    icon: Gt2
  },
  {
    name: e2.slash_menu.numbered_list.title,
    type: "numberedListItem",
    icon: Ft3
  },
  {
    name: e2.slash_menu.check_list.title,
    type: "checkListItem",
    icon: Dt4
  }
];
var Cr = (e2) => {
  const t2 = w2(), n = v7(), o2 = R4({
    editor: n,
    selector: ({ editor: a3 }) => {
      var u2;
      return ((u2 = a3.getSelection()) == null ? void 0 : u2.blocks) || [a3.getTextCursorPosition().block];
    }
  }), r4 = o2[0], i3 = (0, import_react12.useMemo)(
    () => (e2.items || pr(n.dictionary)).filter(
      (a3) => b2(
        n,
        a3.type,
        Object.fromEntries(
          Object.entries(a3.props || {}).map(([u2, d]) => [
            u2,
            typeof d
          ])
        )
      )
    ),
    [n, e2.items]
  ), c3 = (0, import_react12.useMemo)(() => i3.map((a3) => {
    const u2 = a3.icon, d = a3.type === r4.type, m2 = Object.entries(a3.props || {}).filter(
      ([h7, f6]) => f6 !== r4.props[h7]
    ).length === 0;
    return {
      text: a3.name,
      icon: (0, import_jsx_runtime10.jsx)(u2, { size: 16 }),
      onClick: () => {
        n.focus(), n.transact(() => {
          for (const h7 of o2)
            n.updateBlock(h7, {
              type: a3.type,
              props: a3.props
            });
        });
      },
      isSelected: d && m2
    };
  }), [
    n,
    i3,
    r4.props,
    r4.type,
    o2
  ]);
  return !(0, import_react12.useMemo)(
    () => c3.find((a3) => a3.isSelected) !== void 0,
    [c3]
  ) || !n.isEditable ? null : (0, import_jsx_runtime10.jsx)(
    t2.FormattingToolbar.Select,
    {
      className: "bn-select",
      items: c3
    }
  );
};
var vr = () => {
  const e2 = M6(), t2 = w2(), n = T3("comments"), { store: o2 } = T3(yo2), r4 = (0, import_react12.useCallback)(() => {
    n.startPendingComment(), o2.setState(false);
  }, [n, o2]);
  return (0, import_jsx_runtime10.jsx)(
    t2.FormattingToolbar.Button,
    {
      className: "bn-button",
      label: e2.formatting_toolbar.comment.tooltip,
      mainTooltip: e2.formatting_toolbar.comment.tooltip,
      icon: (0, import_jsx_runtime10.jsx)(It4, {}),
      onClick: r4
    }
  );
};
var wr = () => v7().getExtension("comments") ? (0, import_jsx_runtime10.jsx)(vr, {}) : null;
var kr = () => {
  const e2 = M6(), t2 = w2(), n = v7(), o2 = (0, import_react12.useCallback)(() => {
    n._tiptapEditor.chain().focus().addPendingComment().run();
  }, [n]);
  return (
    // We manually check if a comment extension (like liveblocks) is installed
    // By adding default support for this, the user doesn't need to customize the formatting toolbar
    !n._tiptapEditor.commands.addPendingComment || !n.isEditable ? null : (0, import_jsx_runtime10.jsx)(
      t2.FormattingToolbar.Button,
      {
        className: "bn-button",
        label: e2.formatting_toolbar.comment.tooltip,
        mainTooltip: e2.formatting_toolbar.comment.tooltip,
        icon: (0, import_jsx_runtime10.jsx)(It4, {}),
        onClick: o2
      }
    )
  );
};
function Ne2(e2, t2) {
  try {
    const n = new URL(e2, t2);
    if (n.protocol !== "javascript:")
      return n.href;
  } catch {
  }
  return "#";
}
var Hr = () => {
  const e2 = M6(), t2 = w2(), n = v7(), o2 = R4({
    editor: n,
    selector: ({ editor: i3 }) => {
      var a3;
      const c3 = ((a3 = i3.getSelection()) == null ? void 0 : a3.blocks) || [
        i3.getTextCursorPosition().block
      ];
      if (c3.length !== 1)
        return;
      const s2 = c3[0];
      if (Lo(s2, i3, s2.type, {
        url: "string"
      }))
        return s2;
    }
  }), r4 = (0, import_react12.useCallback)(() => {
    o2 !== void 0 && (n.focus(), n.resolveFileUrl ? n.resolveFileUrl(o2.props.url).then(
      (i3) => window.open(Ne2(i3, window.location.href))
    ) : window.open(Ne2(o2.props.url, window.location.href)));
  }, [o2, n]);
  return o2 === void 0 ? null : (0, import_jsx_runtime10.jsx)(
    t2.FormattingToolbar.Button,
    {
      className: "bn-button",
      label: e2.formatting_toolbar.file_download.tooltip[o2.type] || e2.formatting_toolbar.file_download.tooltip.file,
      mainTooltip: e2.formatting_toolbar.file_download.tooltip[o2.type] || e2.formatting_toolbar.file_download.tooltip.file,
      icon: (0, import_jsx_runtime10.jsx)(tr3, {}),
      onClick: r4
    }
  );
};
var xr = () => {
  const e2 = M6(), t2 = w2(), n = v7(), o2 = R4({
    editor: n,
    selector: ({ editor: i3 }) => {
      var a3;
      if (!i3.isEditable)
        return;
      const c3 = ((a3 = i3.getSelection()) == null ? void 0 : a3.blocks) || [
        i3.getTextCursorPosition().block
      ];
      if (c3.length !== 1)
        return;
      const s2 = c3[0];
      if (Lo(s2, i3, s2.type, {
        url: "string",
        showPreview: "boolean"
      }))
        return s2;
    }
  }), r4 = (0, import_react12.useCallback)(() => {
    o2 !== void 0 && b2(n, o2.type, {
      showPreview: "boolean"
    }) && n.updateBlock(o2.id, {
      props: {
        showPreview: !o2.props.showPreview
      }
    });
  }, [o2, n]);
  return o2 === void 0 ? null : (0, import_jsx_runtime10.jsx)(
    t2.FormattingToolbar.Button,
    {
      className: "bn-button",
      label: "Toggle preview",
      mainTooltip: e2.formatting_toolbar.file_preview_toggle.tooltip,
      icon: (0, import_jsx_runtime10.jsx)(qo2, {}),
      isSelected: o2.props.showPreview,
      onClick: r4
    }
  );
};
var yr = () => {
  const e2 = M6(), t2 = w2(), n = v7(), o2 = T3(To2), r4 = R4({
    editor: n,
    selector: ({ editor: c3 }) => {
      var u2;
      if (!c3.isEditable || !c3.settings.tables.splitCells)
        return;
      const s2 = ((u2 = c3.getSelection()) == null ? void 0 : u2.blocks) || [
        c3.getTextCursorPosition().block
      ];
      if (s2.length !== 1)
        return;
      const a3 = s2[0];
      if (a3.type === "table")
        return {
          mergeDirection: o2.getMergeDirection(a3)
        };
    }
  }), i3 = (0, import_react12.useCallback)(() => {
    o2 == null || o2.mergeCells();
  }, [o2]);
  return r4 === void 0 ? null : (0, import_jsx_runtime10.jsx)(
    t2.FormattingToolbar.Button,
    {
      className: "bn-button",
      label: e2.formatting_toolbar.table_cell_merge.tooltip,
      mainTooltip: e2.formatting_toolbar.table_cell_merge.tooltip,
      icon: r4.mergeDirection === "horizontal" ? (0, import_jsx_runtime10.jsx)(Go2, {}) : (0, import_jsx_runtime10.jsx)(zo2, {}),
      onClick: i3
    }
  );
};
var Sr = () => v7().getExtension(To2) ? (0, import_jsx_runtime10.jsx)(yr, {}) : null;
var Mr = {
  left: Oo2,
  center: Lo3,
  right: Io3,
  justify: Ro2
};
var Be3 = (e2) => {
  const t2 = w2(), n = M6(), o2 = v7(), r4 = R4({
    editor: o2,
    selector: ({ editor: s2 }) => {
      var d, m2;
      if (!s2.isEditable)
        return;
      const a3 = ((d = s2.getSelection()) == null ? void 0 : d.blocks) || [
        s2.getTextCursorPosition().block
      ], u2 = a3[0];
      if (Lo(u2, s2, u2.type, {
        textAlignment: h3.textAlignment
      }))
        return {
          textAlignment: u2.props.textAlignment,
          blocks: a3
        };
      if (a3.length === 1 && Lo(u2, s2, "table"))
        return ((m2 = s2.getExtension(To2)) == null ? void 0 : m2.getCellSelection()) ? {
          textAlignment: S(
            u2.content.rows[0].cells[0]
          ).props.textAlignment,
          blocks: [u2]
        } : void 0;
    }
  }), i3 = (0, import_react12.useCallback)(
    (s2) => {
      var a3;
      if (r4 !== void 0) {
        o2.focus();
        for (const u2 of r4.blocks)
          if (Lo(u2, o2, u2.type, {
            textAlignment: h3.textAlignment
          }) && b2(o2, u2.type, {
            textAlignment: h3.textAlignment
          }))
            o2.updateBlock(u2, {
              props: { textAlignment: s2 }
            });
          else if (u2.type === "table") {
            const d = (a3 = o2.getExtension(To2)) == null ? void 0 : a3.getCellSelection();
            if (!d)
              continue;
            const m2 = u2.content.rows.map(
              (h7) => ({
                ...h7,
                cells: h7.cells.map((f6) => S(f6))
              })
            );
            d.cells.forEach(({ row: h7, col: f6 }) => {
              m2[h7].cells[f6].props.textAlignment = s2;
            }), o2.updateBlock(u2, {
              type: "table",
              content: {
                ...u2.content,
                type: "tableContent",
                rows: m2
              }
            }), o2.setTextCursorPosition(u2);
          }
      }
    },
    [o2, r4]
  );
  if (r4 === void 0)
    return null;
  const c3 = Mr[e2.textAlignment];
  return (0, import_jsx_runtime10.jsx)(
    t2.FormattingToolbar.Button,
    {
      className: "bn-button",
      "data-test": `alignText${e2.textAlignment.slice(0, 1).toUpperCase() + e2.textAlignment.slice(1)}`,
      onClick: () => i3(e2.textAlignment),
      isSelected: r4.textAlignment === e2.textAlignment,
      label: n.formatting_toolbar[`align_${e2.textAlignment}`].tooltip,
      mainTooltip: n.formatting_toolbar[`align_${e2.textAlignment}`].tooltip,
      icon: (0, import_jsx_runtime10.jsx)(c3, {})
    }
  );
};
var Vr = (e2) => [
  (0, import_jsx_runtime10.jsx)(Cr, { items: e2 }, "blockTypeSelect"),
  (0, import_jsx_runtime10.jsx)(Sr, {}, "tableCellMergeButton"),
  (0, import_jsx_runtime10.jsx)(ur, {}, "fileCaptionButton"),
  (0, import_jsx_runtime10.jsx)(hr2, {}, "replaceFileButton"),
  (0, import_jsx_runtime10.jsx)(fr, {}, "fileRenameButton"),
  (0, import_jsx_runtime10.jsx)(mr, {}, "fileDeleteButton"),
  (0, import_jsx_runtime10.jsx)(Hr, {}, "fileDownloadButton"),
  (0, import_jsx_runtime10.jsx)(xr, {}, "filePreviewButton"),
  (0, import_jsx_runtime10.jsx)(de3, { basicTextStyle: "bold" }, "boldStyleButton"),
  (0, import_jsx_runtime10.jsx)(de3, { basicTextStyle: "italic" }, "italicStyleButton"),
  (0, import_jsx_runtime10.jsx)(
    de3,
    {
      basicTextStyle: "underline"
    },
    "underlineStyleButton"
  ),
  (0, import_jsx_runtime10.jsx)(de3, { basicTextStyle: "strike" }, "strikeStyleButton"),
  (0, import_jsx_runtime10.jsx)(Be3, { textAlignment: "left" }, "textAlignLeftButton"),
  (0, import_jsx_runtime10.jsx)(Be3, { textAlignment: "center" }, "textAlignCenterButton"),
  (0, import_jsx_runtime10.jsx)(Be3, { textAlignment: "right" }, "textAlignRightButton"),
  (0, import_jsx_runtime10.jsx)(ar, {}, "colorStyleButton"),
  (0, import_jsx_runtime10.jsx)(gr, {}, "nestBlockButton"),
  (0, import_jsx_runtime10.jsx)(br3, {}, "unnestBlockButton"),
  (0, import_jsx_runtime10.jsx)(dr, {}, "createLinkButton"),
  (0, import_jsx_runtime10.jsx)(wr, {}, "addCommentButton"),
  (0, import_jsx_runtime10.jsx)(kr, {}, "addTiptapCommentButton")
];
var qt3 = (e2) => {
  const t2 = w2();
  return (0, import_jsx_runtime10.jsx)(
    t2.FormattingToolbar.Root,
    {
      className: "bn-toolbar bn-formatting-toolbar",
      children: e2.children || Vr(e2.blockTypeSelectItems)
    }
  );
};
var Tr = (e2) => {
  switch (e2) {
    case "left":
      return "top-start";
    case "center":
      return "top";
    case "right":
      return "top-end";
    default:
      return "top-start";
  }
};
var _r = (e2) => {
  const t2 = v7(), n = T3(yo2, {
    editor: t2
  }), o2 = E3(yo2, {
    editor: t2
  }), r4 = R4({
    editor: t2,
    selector: ({ editor: a3 }) => n.store.state ? {
      from: a3.prosemirrorState.selection.from,
      to: a3.prosemirrorState.selection.to
    } : void 0
  }), i3 = R4({
    editor: t2,
    selector: ({ editor: a3 }) => {
      const u2 = a3.getTextCursorPosition().block;
      return Lo(u2, a3, u2.type, {
        textAlignment: h3.textAlignment
      }) ? Tr(u2.props.textAlignment) : "top-start";
    }
  }), c3 = (0, import_react12.useMemo)(
    () => ({
      useFloatingOptions: {
        open: o2,
        // Needed as hooks like `useDismiss` call `onOpenChange` to change the
        // open state.
        onOpenChange: (a3, u2, d) => {
          n.store.setState(a3), d === "escape-key" && t2.focus();
        },
        placement: i3,
        middleware: [offset3(10), shift4(), flip3()]
      },
      elementProps: {
        style: {
          zIndex: 40
        }
      },
      ...e2.floatingUIOptions
    }),
    [o2, i3, e2.floatingUIOptions, n.store, t2]
  ), s2 = e2.formattingToolbar || qt3;
  return (0, import_jsx_runtime10.jsx)(Ue, { position: r4, ...c3, children: o2 && (0, import_jsx_runtime10.jsx)(s2, {}) });
};
var Er = (e2) => {
  const t2 = w2(), n = M6(), { deleteLink: o2 } = T3(vo);
  return (0, import_jsx_runtime10.jsx)(
    t2.LinkToolbar.Button,
    {
      className: "bn-button",
      label: n.link_toolbar.delete.tooltip,
      mainTooltip: n.link_toolbar.delete.tooltip,
      isSelected: false,
      onClick: () => {
        var r4;
        o2(e2.range.from), (r4 = e2.setToolbarOpen) == null || r4.call(e2, false);
      },
      icon: (0, import_jsx_runtime10.jsx)(Fo2, {})
    }
  );
};
var Br = (e2) => {
  const t2 = w2(), n = M6();
  return (0, import_jsx_runtime10.jsxs)(
    t2.Generic.Popover.Root,
    {
      onOpenChange: e2.setToolbarPositionFrozen,
      children: [
        (0, import_jsx_runtime10.jsx)(t2.Generic.Popover.Trigger, { children: (0, import_jsx_runtime10.jsx)(
          t2.LinkToolbar.Button,
          {
            className: "bn-button",
            mainTooltip: n.link_toolbar.edit.tooltip,
            isSelected: false,
            children: n.link_toolbar.edit.text
          }
        ) }),
        (0, import_jsx_runtime10.jsx)(
          t2.Generic.Popover.Content,
          {
            className: "bn-popover-content bn-form-popover",
            variant: "form-popover",
            children: (0, import_jsx_runtime10.jsx)(
              Wt2,
              {
                url: e2.url,
                text: e2.text,
                range: e2.range,
                setToolbarOpen: e2.setToolbarOpen,
                setToolbarPositionFrozen: e2.setToolbarPositionFrozen
              }
            )
          }
        )
      ]
    }
  );
};
var Lr = (e2) => {
  const t2 = w2(), n = M6();
  return (0, import_jsx_runtime10.jsx)(
    t2.LinkToolbar.Button,
    {
      className: "bn-button",
      mainTooltip: n.link_toolbar.open.tooltip,
      label: n.link_toolbar.open.tooltip,
      isSelected: false,
      onClick: () => {
        window.open(Ne2(e2.url, window.location.href), "_blank");
      },
      icon: (0, import_jsx_runtime10.jsx)(nr, {})
    }
  );
};
var Rr = (e2) => {
  const t2 = w2();
  return (0, import_jsx_runtime10.jsx)(t2.LinkToolbar.Root, { className: "bn-toolbar bn-link-toolbar", children: e2.children || (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
    (0, import_jsx_runtime10.jsx)(
      Br,
      {
        url: e2.url,
        text: e2.text,
        range: e2.range,
        setToolbarOpen: e2.setToolbarOpen,
        setToolbarPositionFrozen: e2.setToolbarPositionFrozen
      }
    ),
    (0, import_jsx_runtime10.jsx)(Lr, { url: e2.url }),
    (0, import_jsx_runtime10.jsx)(
      Er,
      {
        range: e2.range,
        setToolbarOpen: e2.setToolbarOpen
      }
    )
  ] }) });
};
var Or = (e2) => {
  const t2 = v7(), [n, o2] = (0, import_react12.useState)(false), [r4, i3] = (0, import_react12.useState)(false), c3 = T3(vo), [s2, a3] = (0, import_react12.useState)(void 0);
  (0, import_react12.useEffect)(() => {
    var p4;
    const h7 = () => {
      const C3 = c3.getLinkAtSelection();
      if (!C3) {
        a3(void 0), r4 || o2(false);
        return;
      }
      a3({
        cursorType: "text",
        url: C3.mark.attrs.href,
        text: C3.text,
        range: C3.range,
        element: c3.getLinkElementAtPos(C3.range.from)
      }), r4 || o2(true);
    }, f6 = (C3) => {
      if (s2 !== void 0 && s2.cursorType === "text" || !(C3.target instanceof HTMLElement))
        return;
      const _2 = c3.getLinkAtElement(C3.target);
      _2 && a3({
        cursorType: "mouse",
        url: _2.mark.attrs.href,
        text: _2.text,
        range: _2.range,
        element: c3.getLinkElementAtPos(_2.range.from)
      });
    }, g = t2.onChange(h7), b4 = t2.onSelectionChange(h7);
    return (p4 = t2.domElement) == null || p4.addEventListener("mouseover", f6), () => {
      var C3;
      g(), b4(), (C3 = t2.domElement) == null || C3.removeEventListener("mouseover", f6);
    };
  }, [t2, c3, s2, r4]);
  const u2 = (0, import_react12.useMemo)(
    () => ({
      useFloatingOptions: {
        open: n,
        onOpenChange: (h7, f6, g) => {
          r4 || s2 !== void 0 && s2.cursorType === "text" && g === "hover" || (g === "escape-key" && t2.focus(), o2(h7));
        },
        placement: "top-start",
        middleware: [offset3(10), flip3()]
      },
      useHoverProps: {
        // `useHover` hook only enabled when a link is hovered with the
        // mouse.
        enabled: s2 !== void 0 && s2.cursorType === "mouse",
        delay: {
          open: 250,
          close: 250
        },
        handleClose: safePolygon()
      },
      elementProps: {
        style: {
          zIndex: 50
        }
      },
      ...e2.floatingUIOptions
    }),
    [t2, s2, e2.floatingUIOptions, n, r4]
  ), d = (0, import_react12.useMemo)(
    () => s2 != null && s2.element ? { element: s2.element } : void 0,
    [s2 == null ? void 0 : s2.element]
  );
  if (!t2.isEditable)
    return null;
  const m2 = e2.linkToolbar || Rr;
  return (0, import_jsx_runtime10.jsx)(U4, { reference: d, ...u2, children: s2 && (0, import_jsx_runtime10.jsx)(
    m2,
    {
      url: s2.url,
      text: s2.text,
      range: s2.range,
      setToolbarOpen: o2,
      setToolbarPositionFrozen: i3
    }
  ) });
};
function Ir(e2) {
  return k2({ attr: { viewBox: "0 0 1024 1024" }, child: [{ tag: "path", attr: { d: "M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8Z" }, child: [] }, { tag: "path", attr: { d: "M192 474h672q8 0 8 8v60q0 8-8 8H160q-8 0-8-8v-60q0-8 8-8Z" }, child: [] }] })(e2);
}
var Pr = () => {
  const e2 = w2(), t2 = M6(), n = v7(), o2 = T3(_n), r4 = E3(Bo2, {
    editor: n,
    selector: (c3) => c3 == null ? void 0 : c3.block
  }), i3 = (0, import_react12.useCallback)(() => {
    if (r4 === void 0)
      return;
    const c3 = r4.content;
    if (c3 !== void 0 && Array.isArray(c3) && c3.length === 0)
      n.setTextCursorPosition(r4), o2.openSuggestionMenu("/");
    else {
      const a3 = n.insertBlocks(
        [{ type: "paragraph" }],
        r4,
        "after"
      )[0];
      n.setTextCursorPosition(a3), o2.openSuggestionMenu("/");
    }
  }, [r4, n, o2]);
  return r4 === void 0 ? null : (0, import_jsx_runtime10.jsx)(
    e2.SideMenu.Button,
    {
      className: "bn-button",
      label: t2.side_menu.add_block_label,
      icon: (0, import_jsx_runtime10.jsx)(Ir, { size: 24, onClick: i3, "data-test": "dragHandleAdd" })
    }
  );
};
function Kt3(e2) {
  return k2({ attr: { viewBox: "0 0 24 24" }, child: [{ tag: "path", attr: { fill: "none", d: "M0 0h24v24H0V0z" }, child: [] }, { tag: "path", attr: { d: "M11 18c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2zm-2-8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 4c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" }, child: [] }] })(e2);
}
function Nr(e2) {
  return k2({ attr: { viewBox: "0 0 24 24" }, child: [{ tag: "path", attr: { fill: "none", d: "M0 0h24v24H0z" }, child: [] }, { tag: "path", attr: { d: "m7 10 5 5 5-5z" }, child: [] }] })(e2);
}
var Ar = (e2) => {
  const t2 = w2(), n = v7(), o2 = E3(Bo2, {
    editor: n,
    selector: (r4) => r4 == null ? void 0 : r4.block
  });
  return o2 === void 0 || !Lo(o2, n, o2.type, {
    textColor: "string"
  }) && !Lo(o2, n, o2.type, {
    backgroundColor: "string"
  }) ? null : (0, import_jsx_runtime10.jsxs)(t2.Generic.Menu.Root, { position: "right", sub: true, children: [
    (0, import_jsx_runtime10.jsx)(t2.Generic.Menu.Trigger, { sub: true, children: (0, import_jsx_runtime10.jsx)(
      t2.Generic.Menu.Item,
      {
        className: "bn-menu-item",
        subTrigger: true,
        children: e2.children
      }
    ) }),
    (0, import_jsx_runtime10.jsx)(
      t2.Generic.Menu.Dropdown,
      {
        sub: true,
        className: "bn-menu-dropdown bn-color-picker-dropdown",
        children: (0, import_jsx_runtime10.jsx)(
          xe3,
          {
            iconSize: 18,
            text: Lo(o2, n, o2.type, {
              textColor: "string"
            }) && b2(n, o2.type, {
              textColor: "string"
            }) ? {
              color: o2.props.textColor,
              setColor: (r4) => n.updateBlock(o2, {
                type: o2.type,
                props: { textColor: r4 }
              })
            } : void 0,
            background: Lo(o2, n, o2.type, {
              backgroundColor: "string"
            }) && b2(n, o2.type, {
              backgroundColor: "string"
            }) ? {
              color: o2.props.backgroundColor,
              setColor: (r4) => n.updateBlock(o2, {
                props: { backgroundColor: r4 }
              })
            } : void 0
          }
        )
      }
    )
  ] });
};
var Zr = (e2) => {
  const t2 = w2(), n = v7(), o2 = E3(Bo2, {
    editor: n,
    selector: (r4) => r4 == null ? void 0 : r4.block
  });
  return o2 === void 0 ? null : (0, import_jsx_runtime10.jsx)(
    t2.Generic.Menu.Item,
    {
      className: "bn-menu-item",
      onClick: () => n.removeBlocks([o2]),
      children: e2.children
    }
  );
};
var Dr = (e2) => {
  const t2 = w2(), n = v7(), o2 = E3(Bo2, {
    editor: n,
    selector: (i3) => i3 == null ? void 0 : i3.block
  });
  if (o2 === void 0 || o2.type !== "table" || !n.settings.tables.headers)
    return null;
  const r4 = !!o2.content.headerRows;
  return (0, import_jsx_runtime10.jsx)(
    t2.Generic.Menu.Item,
    {
      className: "bn-menu-item",
      checked: r4,
      onClick: () => {
        n.updateBlock(o2, {
          content: {
            ...o2.content,
            headerRows: r4 ? void 0 : 1
          }
        });
      },
      children: e2.children
    }
  );
};
var Fr = (e2) => {
  const t2 = w2(), n = v7(), o2 = E3(Bo2, {
    editor: n,
    selector: (i3) => i3 == null ? void 0 : i3.block
  });
  if (o2 === void 0 || o2.type !== "table" || !n.settings.tables.headers)
    return null;
  const r4 = !!o2.content.headerCols;
  return (0, import_jsx_runtime10.jsx)(
    t2.Generic.Menu.Item,
    {
      className: "bn-menu-item",
      checked: r4,
      onClick: () => {
        n.updateBlock(o2, {
          content: {
            ...o2.content,
            headerCols: r4 ? void 0 : 1
          }
        });
      },
      children: e2.children
    }
  );
};
var Gr = (e2) => {
  const t2 = w2(), n = M6();
  return (0, import_jsx_runtime10.jsx)(
    t2.Generic.Menu.Dropdown,
    {
      className: "bn-menu-dropdown bn-drag-handle-menu",
      children: e2.children || (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
        (0, import_jsx_runtime10.jsx)(Zr, { children: n.drag_handle.delete_menuitem }),
        (0, import_jsx_runtime10.jsx)(Ar, { children: n.drag_handle.colors_menuitem }),
        (0, import_jsx_runtime10.jsx)(Dr, { children: n.drag_handle.header_row_menuitem }),
        (0, import_jsx_runtime10.jsx)(Fr, { children: n.drag_handle.header_column_menuitem })
      ] })
    }
  );
};
var zr = (e2) => {
  const t2 = w2(), n = M6(), o2 = T3(Bo2), r4 = E3(Bo2, {
    selector: (c3) => c3 == null ? void 0 : c3.block
  });
  if (r4 === void 0)
    return null;
  const i3 = e2.dragHandleMenu || Gr;
  return (0, import_jsx_runtime10.jsxs)(
    t2.Generic.Menu.Root,
    {
      onOpenChange: (c3) => {
        c3 ? o2.freezeMenu() : o2.unfreezeMenu();
      },
      position: "left",
      children: [
        (0, import_jsx_runtime10.jsx)(t2.Generic.Menu.Trigger, { children: (0, import_jsx_runtime10.jsx)(
          t2.SideMenu.Button,
          {
            label: n.side_menu.drag_handle_label,
            draggable: true,
            onDragStart: (c3) => o2.blockDragStart(c3, r4),
            onDragEnd: o2.blockDragEnd,
            className: "bn-button",
            icon: (0, import_jsx_runtime10.jsx)(Kt3, { size: 24, "data-test": "dragHandle" })
          }
        ) }),
        (0, import_jsx_runtime10.jsx)(i3, { children: e2.children })
      ]
    }
  );
};
var Ur = (e2) => {
  const t2 = w2(), n = v7(), o2 = E3(Bo2, {
    editor: n,
    selector: (i3) => i3 == null ? void 0 : i3.block
  }), r4 = (0, import_react12.useMemo)(() => {
    var c3;
    if (o2 === void 0)
      return {};
    const i3 = {
      "data-block-type": o2.type
    };
    return o2.type === "heading" && (i3["data-level"] = o2.props.level.toString()), (c3 = n.schema.blockSpecs[o2.type].implementation.meta) != null && c3.fileBlockAccept && (o2.props.url ? i3["data-url"] = "true" : i3["data-url"] = "false"), i3;
  }, [o2, n.schema.blockSpecs]);
  return (0, import_jsx_runtime10.jsx)(t2.SideMenu.Root, { className: "bn-side-menu", ...r4, children: e2.children || (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
    (0, import_jsx_runtime10.jsx)(Pr, {}),
    (0, import_jsx_runtime10.jsx)(zr, { dragHandleMenu: e2.dragHandleMenu })
  ] }) });
};
var jr = (e2) => {
  const t2 = E3(Bo2, {
    selector: (c3) => c3 !== void 0 ? {
      show: c3.show,
      block: c3.block
    } : void 0
  }), { show: n, block: o2 } = t2 || {}, r4 = (0, import_react12.useMemo)(
    () => ({
      useFloatingOptions: {
        open: n,
        placement: "left-start"
      },
      useDismissProps: {
        enabled: false
      },
      elementProps: {
        style: {
          zIndex: 20
        }
      },
      ...e2.floatingUIOptions
    }),
    [e2.floatingUIOptions, n]
  ), i3 = e2.sideMenu || Ur;
  return (0, import_jsx_runtime10.jsx)(Bt3, { blockId: n ? o2 == null ? void 0 : o2.id : void 0, ...r4, children: (o2 == null ? void 0 : o2.id) && (0, import_jsx_runtime10.jsx)(i3, {}) });
};
async function $r(e2, t2) {
  return (await c2(e2, t2)).map(
    ({ id: n, onItemClick: o2 }) => ({
      id: n,
      onItemClick: o2,
      icon: n
    })
  );
}
function Wr(e2) {
  const t2 = w2(), n = M6(), { items: o2, loadingState: r4, selectedIndex: i3, onItemClick: c3, columns: s2 } = e2, a3 = r4 === "loading-initial" || r4 === "loading" ? (0, import_jsx_runtime10.jsx)(
    t2.GridSuggestionMenu.Loader,
    {
      className: "bn-grid-suggestion-menu-loader",
      columns: s2
    }
  ) : null, u2 = (0, import_react12.useMemo)(() => {
    const d = [];
    for (let m2 = 0; m2 < o2.length; m2++) {
      const h7 = o2[m2];
      d.push(
        (0, import_jsx_runtime10.jsx)(
          t2.GridSuggestionMenu.Item,
          {
            className: "bn-grid-suggestion-menu-item",
            item: h7,
            id: `bn-grid-suggestion-menu-item-${m2}`,
            isSelected: m2 === i3,
            onClick: () => c3 == null ? void 0 : c3(h7)
          },
          h7.id
        )
      );
    }
    return d;
  }, [t2, o2, c3, i3]);
  return (0, import_jsx_runtime10.jsxs)(
    t2.GridSuggestionMenu.Root,
    {
      id: "bn-grid-suggestion-menu",
      columns: s2,
      className: "bn-grid-suggestion-menu",
      children: [
        a3,
        u2,
        u2.length === 0 && e2.loadingState === "loaded" && (0, import_jsx_runtime10.jsx)(
          t2.GridSuggestionMenu.EmptyItem,
          {
            className: "bn-grid-suggestion-menu-empty-item",
            columns: s2,
            children: n.suggestion_menu.no_items_title
          }
        )
      ]
    }
  );
}
function Xt3(e2, t2, n, o2 = 3) {
  const r4 = (0, import_react12.useRef)(0);
  (0, import_react12.useEffect)(() => {
    t2 !== void 0 && (e2.length > 0 ? r4.current = t2.length : t2.length - r4.current > o2 && n());
  }, [n, o2, e2.length, t2]);
}
function Yt3(e2, t2) {
  const [n, o2] = (0, import_react12.useState)([]), [r4, i3] = (0, import_react12.useState)(false), c3 = (0, import_react12.useRef)(void 0), s2 = (0, import_react12.useRef)(void 0);
  return (0, import_react12.useEffect)(() => {
    const a3 = e2;
    c3.current = e2, i3(true), t2(e2).then((u2) => {
      c3.current === a3 && (o2(u2), i3(false), s2.current = a3);
    });
  }, [e2, t2]), {
    items: n || [],
    // The query that was used to retrieve the last set of items may not be the
    // same as the current query as the items from the current query may not
    // have been retrieved yet. This is useful when using the returns of this
    // hook in other hooks.
    usedQuery: s2.current,
    loadingState: s2.current === void 0 ? "loading-initial" : r4 ? "loading" : "loaded"
  };
}
function qr(e2, t2, n, o2, r4) {
  const [i3, c3] = (0, import_react12.useState)(0), s2 = o2 !== void 0 && o2 > 1;
  return (0, import_react12.useEffect)(() => {
    var u2;
    const a3 = (d) => (d.key === "ArrowLeft" && (d.preventDefault(), n.length && c3((i3 - 1 + n.length) % n.length)), d.key === "ArrowRight" && (d.preventDefault(), n.length && c3((i3 + 1 + n.length) % n.length)), d.key === "ArrowUp" ? (d.preventDefault(), n.length && c3(
      (i3 - o2 + n.length) % n.length
    ), true) : d.key === "ArrowDown" ? (d.preventDefault(), n.length && c3((i3 + o2) % n.length), true) : d.key === "Enter" && !d.isComposing ? (d.stopPropagation(), d.preventDefault(), n.length && (r4 == null || r4(n[i3])), true) : false);
    return (u2 = e2.domElement) == null || u2.addEventListener(
      "keydown",
      a3,
      true
    ), () => {
      var d;
      (d = e2.domElement) == null || d.removeEventListener(
        "keydown",
        a3,
        true
      );
    };
  }, [e2.domElement, n, i3, r4, o2, s2]), (0, import_react12.useEffect)(() => {
    c3(0);
  }, [t2]), {
    selectedIndex: n.length === 0 ? void 0 : i3
  };
}
function Kr(e2) {
  const n = q3().setContentEditableProps, o2 = v7(), {
    getItems: r4,
    gridSuggestionMenuComponent: i3,
    query: c3,
    clearQuery: s2,
    closeMenu: a3,
    onItemClick: u2,
    columns: d
  } = e2, m2 = (0, import_react12.useCallback)(
    (C3) => {
      a3(), s2(), u2 == null || u2(C3);
    },
    [u2, a3, s2]
  ), { items: h7, usedQuery: f6, loadingState: g } = Yt3(
    c3,
    r4
  );
  Xt3(h7, f6, a3);
  const { selectedIndex: b4 } = qr(
    o2,
    c3,
    h7,
    d,
    m2
  );
  return (0, import_react12.useEffect)(() => (n((C3) => ({
    ...C3,
    "aria-expanded": true,
    "aria-controls": "bn-suggestion-menu"
  })), () => {
    n((C3) => ({
      ...C3,
      "aria-expanded": false,
      "aria-controls": void 0
    }));
  }), [n]), (0, import_react12.useEffect)(() => (n((C3) => ({
    ...C3,
    "aria-activedescendant": b4 ? "bn-suggestion-menu-item-" + b4 : void 0
  })), () => {
    n((C3) => ({
      ...C3,
      "aria-activedescendant": void 0
    }));
  }), [n, b4]), (0, import_jsx_runtime10.jsx)(
    i3,
    {
      items: h7,
      onItemClick: m2,
      loadingState: g,
      selectedIndex: b4,
      columns: d
    }
  );
}
function Xr(e2) {
  const t2 = v7(), {
    triggerCharacter: n,
    gridSuggestionMenuComponent: o2,
    columns: r4,
    minQueryLength: i3,
    onItemClick: c3,
    getItems: s2
  } = e2, a3 = (0, import_react12.useMemo)(() => c3 || ((g) => {
    g.onItemClick(t2);
  }), [t2, c3]), u2 = (0, import_react12.useMemo)(() => s2 || (async (g) => await $r(
    t2,
    g
  )), [t2, s2]), d = T3(_n);
  (0, import_react12.useEffect)(() => {
    d.addTriggerCharacter(n);
  }, [d, n]);
  const m2 = E3(_n), h7 = E3(_n, {
    selector: (g) => {
      var b4;
      return {
        // Use first child as the editor DOM element may itself be scrollable.
        // For FloatingUI to auto-update the position during scrolling, the
        // `contextElement` must be a descendant of the scroll container.
        element: ((b4 = t2.domElement) == null ? void 0 : b4.firstChild) || void 0,
        getBoundingClientRect: () => (g == null ? void 0 : g.referencePos) || new DOMRect()
      };
    }
  }), f6 = (0, import_react12.useMemo)(
    () => ({
      useFloatingOptions: {
        open: (m2 == null ? void 0 : m2.show) && (m2 == null ? void 0 : m2.triggerCharacter) === n,
        onOpenChange: (g) => {
          g || d.closeMenu();
        },
        placement: "bottom-start",
        middleware: [
          offset3(10),
          // Flips the menu placement to maximize the space available, and prevents
          // the menu from being cut off by the confines of the screen.
          autoPlacement3({
            allowedPlacements: ["bottom-start", "top-start"],
            padding: 10
          }),
          shift4(),
          size4({
            apply({ elements: g, availableHeight: b4 }) {
              g.floating.style.maxHeight = `${Math.max(0, b4)}px`;
            },
            padding: 10
          })
        ]
      },
      elementProps: {
        // Prevents editor blurring when clicking the scroll bar.
        onMouseDownCapture: (g) => g.preventDefault(),
        style: {
          zIndex: 70
        }
      },
      ...e2.floatingUIOptions
    }),
    [
      e2.floatingUIOptions,
      m2 == null ? void 0 : m2.show,
      m2 == null ? void 0 : m2.triggerCharacter,
      d,
      n
    ]
  );
  return !m2 || !m2.ignoreQueryLength && i3 && (m2.query.startsWith(" ") || m2.query.length < i3) ? null : (0, import_jsx_runtime10.jsx)(U4, { reference: h7, ...f6, children: n && (0, import_jsx_runtime10.jsx)(
    Kr,
    {
      query: m2.query,
      closeMenu: d.closeMenu,
      clearQuery: d.clearQuery,
      getItems: u2,
      columns: r4,
      gridSuggestionMenuComponent: o2 || Wr,
      onItemClick: a3
    }
  ) });
}
function Yr(e2) {
  const t2 = w2(), n = M6(), { items: o2, loadingState: r4, selectedIndex: i3, onItemClick: c3 } = e2, s2 = r4 === "loading-initial" || r4 === "loading" ? (0, import_jsx_runtime10.jsx)(
    t2.SuggestionMenu.Loader,
    {
      className: "bn-suggestion-menu-loader"
    }
  ) : null, a3 = (0, import_react12.useMemo)(() => {
    let u2;
    const d = [];
    for (let m2 = 0; m2 < o2.length; m2++) {
      const h7 = o2[m2];
      h7.group !== u2 && (u2 = h7.group, d.push(
        (0, import_jsx_runtime10.jsx)(
          t2.SuggestionMenu.Label,
          {
            className: "bn-suggestion-menu-label",
            children: u2
          },
          u2
        )
      )), d.push(
        (0, import_jsx_runtime10.jsx)(
          t2.SuggestionMenu.Item,
          {
            className: D2(
              "bn-suggestion-menu-item",
              h7.size === "small" ? "bn-suggestion-menu-item-small" : ""
            ),
            item: h7,
            id: `bn-suggestion-menu-item-${m2}`,
            isSelected: m2 === i3,
            onClick: () => c3 == null ? void 0 : c3(h7)
          },
          h7.title
        )
      );
    }
    return d;
  }, [t2, o2, c3, i3]);
  return (0, import_jsx_runtime10.jsxs)(
    t2.SuggestionMenu.Root,
    {
      id: "bn-suggestion-menu",
      className: "bn-suggestion-menu",
      children: [
        a3,
        a3.length === 0 && (e2.loadingState === "loading" || e2.loadingState === "loaded") && (0, import_jsx_runtime10.jsx)(
          t2.SuggestionMenu.EmptyItem,
          {
            className: "bn-suggestion-menu-item",
            children: n.suggestion_menu.no_items_title
          }
        ),
        s2
      ]
    }
  );
}
function Jr(e2, t2) {
  const [n, o2] = (0, import_react12.useState)(0);
  return {
    selectedIndex: n,
    setSelectedIndex: o2,
    handler: (r4) => {
      if (r4.key === "ArrowUp")
        return r4.preventDefault(), e2.length && o2((n - 1 + e2.length) % e2.length), true;
      if (r4.key === "ArrowDown")
        return r4.preventDefault(), e2.length && o2((n + 1) % e2.length), true;
      const i3 = Qr(r4) ? r4.nativeEvent.isComposing : r4.isComposing;
      return r4.key === "Enter" && !i3 ? (r4.preventDefault(), r4.stopPropagation(), e2.length && (t2 == null || t2(e2[n])), true) : false;
    }
  };
}
function Qr(e2) {
  return e2.nativeEvent !== void 0;
}
function ei(e2, t2, n, o2, r4) {
  const { selectedIndex: i3, setSelectedIndex: c3, handler: s2 } = Jr(n, o2);
  return (0, import_react12.useEffect)(() => {
    var a3;
    return (a3 = r4 || e2.domElement) == null || a3.addEventListener("keydown", s2, true), () => {
      var u2;
      (u2 = r4 || e2.domElement) == null || u2.removeEventListener(
        "keydown",
        s2,
        true
      );
    };
  }, [e2.domElement, n, i3, o2, r4, s2]), (0, import_react12.useEffect)(() => {
    c3(0);
  }, [t2, c3]), {
    selectedIndex: n.length === 0 ? void 0 : i3
  };
}
function ti(e2) {
  const n = q3().setContentEditableProps, o2 = v7(), {
    getItems: r4,
    suggestionMenuComponent: i3,
    query: c3,
    clearQuery: s2,
    closeMenu: a3,
    onItemClick: u2
  } = e2, d = (0, import_react12.useCallback)(
    (p4) => {
      a3(), s2(), u2 == null || u2(p4);
    },
    [u2, a3, s2]
  ), { items: m2, usedQuery: h7, loadingState: f6 } = Yt3(
    c3,
    r4
  );
  Xt3(m2, h7, a3);
  const { selectedIndex: g } = ei(
    o2,
    c3,
    m2,
    d
  );
  return (0, import_react12.useEffect)(() => (n((p4) => ({
    ...p4,
    "aria-expanded": true,
    "aria-controls": "bn-suggestion-menu"
  })), () => {
    n((p4) => ({
      ...p4,
      "aria-expanded": false,
      "aria-controls": void 0
    }));
  }), [n]), (0, import_react12.useEffect)(() => (n((p4) => ({
    ...p4,
    "aria-activedescendant": g ? "bn-suggestion-menu-item-" + g : void 0
  })), () => {
    n((p4) => ({
      ...p4,
      "aria-activedescendant": void 0
    }));
  }), [n, g]), (0, import_jsx_runtime10.jsx)(
    i3,
    {
      items: m2,
      onItemClick: d,
      loadingState: f6,
      selectedIndex: g
    }
  );
}
var ni = {
  heading: pe3,
  heading_2: Ce3,
  heading_3: ve3,
  heading_4: Pt4,
  heading_5: Nt3,
  heading_6: At4,
  toggle_heading: pe3,
  toggle_heading_2: Ce3,
  toggle_heading_3: ve3,
  quote: zt3,
  toggle_list: jt2,
  numbered_list: Ft3,
  bullet_list: Gt2,
  check_list: Dt4,
  paragraph: $e,
  table: jo2,
  image: Ut3,
  video: Wo2,
  audio: $t4,
  file: je,
  emoji: ir,
  code_block: No3,
  divider: rr
};
function oi(e2) {
  return Bo(e2).map((t2) => {
    const n = ni[t2.key];
    return {
      ...t2,
      icon: (0, import_jsx_runtime10.jsx)(n, { size: 18 })
    };
  });
}
function ri(e2) {
  const t2 = v7(), {
    triggerCharacter: n,
    suggestionMenuComponent: o2,
    minQueryLength: r4,
    onItemClick: i3,
    getItems: c3
  } = e2, s2 = (0, import_react12.useMemo)(() => i3 || ((f6) => {
    f6.onItemClick(t2);
  }), [t2, i3]), a3 = (0, import_react12.useMemo)(() => c3 || (async (f6) => Ao(
    oi(t2),
    f6
  )), [t2, c3]), u2 = T3(_n);
  (0, import_react12.useEffect)(() => {
    u2.addTriggerCharacter(n);
  }, [u2, n]);
  const d = E3(_n), m2 = E3(_n, {
    selector: (f6) => {
      var g;
      return {
        // Use first child as the editor DOM element may itself be scrollable.
        // For FloatingUI to auto-update the position during scrolling, the
        // `contextElement` must be a descendant of the scroll container.
        element: ((g = t2.domElement) == null ? void 0 : g.firstChild) || void 0,
        getBoundingClientRect: () => (f6 == null ? void 0 : f6.referencePos) || new DOMRect()
      };
    }
  }), h7 = (0, import_react12.useMemo)(
    () => ({
      useFloatingOptions: {
        open: (d == null ? void 0 : d.show) && (d == null ? void 0 : d.triggerCharacter) === n,
        onOpenChange: (f6) => {
          f6 || u2.closeMenu();
        },
        placement: "bottom-start",
        middleware: [
          offset3(10),
          // Flips the menu placement to maximize the space available, and prevents
          // the menu from being cut off by the confines of the screen.
          autoPlacement3({
            allowedPlacements: ["bottom-start", "top-start"],
            padding: 10
          }),
          shift4(),
          size4({
            apply({ elements: f6, availableHeight: g }) {
              f6.floating.style.maxHeight = `${Math.max(0, g)}px`;
            },
            padding: 10
          })
        ]
      },
      elementProps: {
        // Prevents editor blurring when clicking the scroll bar.
        onMouseDownCapture: (f6) => f6.preventDefault(),
        style: {
          zIndex: 80
        }
      },
      ...e2.floatingUIOptions
    }),
    [
      e2.floatingUIOptions,
      d == null ? void 0 : d.show,
      d == null ? void 0 : d.triggerCharacter,
      u2,
      n
    ]
  );
  return !d || !d.ignoreQueryLength && r4 && (d.query.startsWith(" ") || d.query.length < r4) ? null : (0, import_jsx_runtime10.jsx)(U4, { reference: m2, ...h7, children: n && (0, import_jsx_runtime10.jsx)(
    ti,
    {
      query: d.query,
      closeMenu: u2.closeMenu,
      clearQuery: u2.clearQuery,
      getItems: a3,
      suggestionMenuComponent: o2 || Yr,
      onItemClick: s2
    }
  ) });
}
var ii = (e2, t2 = 0.3) => {
  const n = Math.floor(e2) + t2, o2 = Math.ceil(e2) - t2;
  return e2 >= n && e2 <= o2 ? Math.round(e2) : e2 < n ? Math.floor(e2) : Math.ceil(e2);
};
var li3 = (e2) => {
  const t2 = w2(), n = v7(), o2 = T3(To2), r4 = E3(To2, {
    selector: (d) => d == null ? void 0 : d.block
  }), i3 = (0, import_react12.useRef)(false), [c3, s2] = (0, import_react12.useState)(), a3 = (0, import_react12.useCallback)(
    (d) => {
      o2.freezeHandles(), e2.hideOtherElements(true), r4 && (s2({
        originalContent: r4.content,
        originalCroppedContent: {
          rows: o2.cropEmptyRowsOrColumns(
            r4,
            e2.orientation === "addOrRemoveColumns" ? "columns" : "rows"
          )
        },
        startPos: e2.orientation === "addOrRemoveColumns" ? d.clientX : d.clientY
      }), i3.current = false, d.preventDefault());
    },
    [r4, e2, o2]
  ), u2 = (0, import_react12.useCallback)(() => {
    !r4 || i3.current || n.updateBlock(r4, {
      type: "table",
      content: {
        ...r4.content,
        rows: e2.orientation === "addOrRemoveColumns" ? o2.addRowsOrColumns(r4, "columns", 1) : o2.addRowsOrColumns(r4, "rows", 1)
      }
    });
  }, [r4, n, e2.orientation, o2]);
  return (0, import_react12.useEffect)(() => {
    const d = (m2) => {
      var C3, _2;
      if (!r4)
        return;
      if (!c3)
        throw new Error("editingState is undefined");
      i3.current = true;
      const h7 = (e2.orientation === "addOrRemoveColumns" ? m2.clientX : m2.clientY) - c3.startPos, f6 = e2.orientation === "addOrRemoveColumns" ? ((C3 = c3.originalCroppedContent.rows[0]) == null ? void 0 : C3.cells.length) ?? 0 : c3.originalCroppedContent.rows.length, g = e2.orientation === "addOrRemoveColumns" ? ((_2 = c3.originalContent.rows[0]) == null ? void 0 : _2.cells.length) ?? 0 : c3.originalContent.rows.length, b4 = e2.orientation === "addOrRemoveColumns" ? r4.content.rows[0].cells.length : r4.content.rows.length, p4 = g + ii(
        h7 / (e2.orientation === "addOrRemoveColumns" ? Ie : Mo),
        0.3
      );
      p4 >= f6 && p4 > 0 && p4 !== b4 && (n.updateBlock(r4, {
        type: "table",
        content: {
          ...r4.content,
          rows: e2.orientation === "addOrRemoveColumns" ? o2.addRowsOrColumns(
            {
              type: "table",
              content: c3.originalCroppedContent
            },
            "columns",
            p4 - f6
          ) : o2.addRowsOrColumns(
            {
              type: "table",
              content: c3.originalCroppedContent
            },
            "rows",
            p4 - f6
          )
        }
      }), r4.content && n.setTextCursorPosition(r4));
    };
    return c3 && window.addEventListener("mousemove", d), () => {
      window.removeEventListener("mousemove", d);
    };
  }, [r4, c3, n, e2.orientation, o2]), (0, import_react12.useEffect)(() => {
    const d = () => {
      e2.hideOtherElements(false), o2.unfreezeHandles(), s2(void 0);
    };
    return c3 && window.addEventListener("mouseup", d), () => {
      window.removeEventListener("mouseup", d);
    };
  }, [c3, e2, o2]), n.isEditable ? (0, import_jsx_runtime10.jsx)(
    t2.TableHandle.ExtendButton,
    {
      className: D2(
        "bn-extend-button",
        e2.orientation === "addOrRemoveColumns" ? "bn-extend-button-add-remove-columns" : "bn-extend-button-add-remove-rows",
        c3 !== null ? "bn-extend-button-editing" : ""
      ),
      onClick: u2,
      onMouseDown: a3,
      children: e2.children || (0, import_jsx_runtime10.jsx)(Yo2, { size: 18, "data-test": "extendButton" })
    }
  ) : null;
};
var ht2 = (e2) => {
  const t2 = w2(), n = M6(), o2 = T3(To2), r4 = E3(To2, {
    selector: (i3) => e2.orientation === "column" ? i3 == null ? void 0 : i3.colIndex : i3 == null ? void 0 : i3.rowIndex
  });
  return o2 === void 0 || r4 === void 0 ? null : (0, import_jsx_runtime10.jsx)(
    t2.Generic.Menu.Item,
    {
      onClick: () => {
        o2.addRowOrColumn(
          r4,
          e2.orientation === "row" ? { orientation: "row", side: e2.side } : { orientation: "column", side: e2.side }
        );
      },
      children: n.table_handle[`add_${e2.side}_menuitem`]
    }
  );
};
var ci = (e2) => {
  const t2 = w2(), n = M6(), o2 = T3(To2), r4 = E3(To2, {
    selector: (i3) => e2.orientation === "column" ? i3 == null ? void 0 : i3.colIndex : i3 == null ? void 0 : i3.rowIndex
  });
  return o2 === void 0 || r4 === void 0 ? null : (0, import_jsx_runtime10.jsx)(
    t2.Generic.Menu.Item,
    {
      onClick: () => o2.removeRowOrColumn(r4, e2.orientation),
      children: e2.orientation === "row" ? n.table_handle.delete_row_menuitem : n.table_handle.delete_column_menuitem
    }
  );
};
var ai = (e2) => {
  const t2 = w2(), n = M6(), o2 = v7(), r4 = T3(To2), { block: i3, index: c3 } = E3(To2, {
    selector: (d) => ({
      block: d == null ? void 0 : d.block,
      index: e2.orientation === "column" ? d == null ? void 0 : d.colIndex : d == null ? void 0 : d.rowIndex
    })
  }), s2 = (0, import_react12.useMemo)(() => r4 === void 0 || i3 === void 0 || c3 === void 0 ? [] : e2.orientation === "row" ? r4.getCellsAtRowHandle(i3, c3) : r4.getCellsAtColumnHandle(i3, c3), [i3, c3, e2.orientation, r4]), a3 = (d, m2) => {
    if (i3 === void 0)
      return;
    const h7 = i3.content.rows.map((f6) => ({
      ...f6,
      cells: f6.cells.map((g) => S(g))
    }));
    s2.forEach(({ row: f6, col: g }) => {
      m2 === "text" ? h7[f6].cells[g].props.textColor = d : h7[f6].cells[g].props.backgroundColor = d;
    }), o2.updateBlock(i3, {
      type: "table",
      content: {
        ...i3.content,
        rows: h7
      }
    }), o2.setTextCursorPosition(i3);
  };
  if (!s2 || !s2[0] || !r4 || o2.settings.tables.cellTextColor === false && o2.settings.tables.cellBackgroundColor === false)
    return null;
  const u2 = S(s2[0].cell);
  return (0, import_jsx_runtime10.jsxs)(t2.Generic.Menu.Root, { position: "right", sub: true, children: [
    (0, import_jsx_runtime10.jsx)(t2.Generic.Menu.Trigger, { sub: true, children: (0, import_jsx_runtime10.jsx)(
      t2.Generic.Menu.Item,
      {
        className: "bn-menu-item",
        subTrigger: true,
        children: e2.children || n.drag_handle.colors_menuitem
      }
    ) }),
    (0, import_jsx_runtime10.jsx)(
      t2.Generic.Menu.Dropdown,
      {
        sub: true,
        className: "bn-menu-dropdown bn-color-picker-dropdown",
        children: (0, import_jsx_runtime10.jsx)(
          xe3,
          {
            iconSize: 18,
            text: o2.settings.tables.cellTextColor ? {
              // All cells have the same text color
              color: s2.every(
                ({ cell: d }) => R(d) && d.props.textColor === u2.props.textColor
              ) ? u2.props.textColor : "default",
              setColor: (d) => {
                a3(d, "text");
              }
            } : void 0,
            background: o2.settings.tables.cellBackgroundColor ? {
              color: s2.every(
                ({ cell: d }) => R(d) && d.props.backgroundColor === u2.props.backgroundColor
              ) ? u2.props.backgroundColor : "default",
              setColor: (d) => a3(d, "background")
            } : void 0
          }
        )
      }
    )
  ] });
};
var si = (e2) => {
  const t2 = w2(), n = M6(), o2 = v7(), r4 = T3(To2), { block: i3, index: c3 } = E3(To2, {
    selector: (a3) => ({
      block: a3 == null ? void 0 : a3.block,
      index: e2.orientation === "column" ? a3 == null ? void 0 : a3.colIndex : a3 == null ? void 0 : a3.rowIndex
    })
  });
  if (r4 === void 0 || i3 === void 0 || c3 !== 0 || e2.orientation !== "row" || !o2.settings.tables.headers)
    return null;
  const s2 = !!i3.content.headerRows;
  return (0, import_jsx_runtime10.jsx)(
    t2.Generic.Menu.Item,
    {
      className: "bn-menu-item",
      checked: s2,
      onClick: () => {
        o2.updateBlock(i3, {
          ...i3,
          content: {
            ...i3.content,
            headerRows: s2 ? void 0 : 1
          }
        });
      },
      children: n.drag_handle.header_row_menuitem
    }
  );
};
var di = (e2) => {
  const t2 = w2(), n = M6(), o2 = v7(), r4 = T3(To2), i3 = E3(To2, {
    selector: (a3) => a3 == null ? void 0 : a3.block
  }), c3 = E3(To2, {
    selector: (a3) => e2.orientation === "column" ? a3 == null ? void 0 : a3.colIndex : a3 == null ? void 0 : a3.rowIndex
  });
  if (!r4 || c3 !== 0 || !i3 || e2.orientation !== "column" || !o2.settings.tables.headers)
    return null;
  const s2 = !!i3.content.headerCols;
  return (0, import_jsx_runtime10.jsx)(
    t2.Generic.Menu.Item,
    {
      className: "bn-menu-item",
      checked: s2,
      onClick: () => {
        o2.updateBlock(i3, {
          ...i3,
          content: {
            ...i3.content,
            headerCols: s2 ? void 0 : 1
          }
        });
      },
      children: n.drag_handle.header_column_menuitem
    }
  );
};
var ui = (e2) => {
  const t2 = w2();
  return (0, import_jsx_runtime10.jsx)(t2.Generic.Menu.Dropdown, { className: "bn-table-handle-menu", children: e2.children || (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
    (0, import_jsx_runtime10.jsx)(ci, { orientation: e2.orientation }),
    (0, import_jsx_runtime10.jsx)(
      ht2,
      {
        orientation: e2.orientation,
        side: e2.orientation === "row" ? "above" : "left"
      }
    ),
    (0, import_jsx_runtime10.jsx)(
      ht2,
      {
        orientation: e2.orientation,
        side: e2.orientation === "row" ? "below" : "right"
      }
    ),
    (0, import_jsx_runtime10.jsx)(si, { orientation: e2.orientation }),
    (0, import_jsx_runtime10.jsx)(di, { orientation: e2.orientation }),
    (0, import_jsx_runtime10.jsx)(ai, { orientation: e2.orientation })
  ] }) });
};
var mi = (e2) => {
  const t2 = v7(), n = w2(), [o2, r4] = (0, import_react12.useState)(false), i3 = e2.tableHandleMenu || ui, c3 = T3(To2), s2 = E3(To2), a3 = (0, import_react12.useMemo)(() => !c3 || !s2 || !s2.block || s2.block.type !== "table" ? false : e2.orientation === "column" ? c3.getCellsAtColumnHandle(s2.block, s2.colIndex).every(({ cell: u2 }) => A(u2) === 1) : c3.getCellsAtRowHandle(s2.block, s2.rowIndex).every(({ cell: u2 }) => D(u2) === 1), [e2.orientation, s2, c3]);
  return s2 ? (0, import_jsx_runtime10.jsxs)(
    n.Generic.Menu.Root,
    {
      onOpenChange: (u2) => {
        u2 ? (c3.freezeHandles(), e2.hideOtherElements(true)) : (c3.unfreezeHandles(), e2.hideOtherElements(false), t2.focus());
      },
      position: "right",
      children: [
        (0, import_jsx_runtime10.jsx)(n.Generic.Menu.Trigger, { children: (0, import_jsx_runtime10.jsx)(
          n.TableHandle.Root,
          {
            className: D2(
              "bn-table-handle",
              o2 ? "bn-table-handle-dragging" : "",
              a3 ? "" : "bn-table-handle-not-draggable"
            ),
            draggable: a3,
            onDragStart: (u2) => {
              r4(true), e2.hideOtherElements(true), e2.orientation === "column" ? c3.colDragStart(u2) : c3.rowDragStart(u2);
            },
            onDragEnd: () => {
              c3.dragEnd(), e2.hideOtherElements(false), r4(false);
            },
            style: e2.orientation === "column" ? { transform: "rotate(0.25turn)" } : void 0,
            children: e2.children || (0, import_jsx_runtime10.jsx)(Kt3, { size: 24, "data-test": "tableHandle" })
          }
        ) }),
        (0, import_jsx_runtime10.jsx)(i3, { orientation: e2.orientation })
      ]
    }
  ) : null;
};
var fi = (e2) => {
  var u2, d;
  const t2 = w2(), n = M6(), o2 = v7(), { block: r4, colIndex: i3, rowIndex: c3 } = E3(
    To2,
    {
      selector: (m2) => ({
        block: m2 == null ? void 0 : m2.block,
        colIndex: m2 == null ? void 0 : m2.colIndex,
        rowIndex: m2 == null ? void 0 : m2.rowIndex
      })
    }
  ), s2 = (m2, h7) => {
    if (r4 === void 0 || i3 === void 0 || c3 === void 0)
      return;
    const f6 = r4.content.rows.map((g) => ({
      ...g,
      cells: g.cells.map((b4) => S(b4))
    }));
    h7 === "text" ? f6[c3].cells[i3].props.textColor = m2 : f6[c3].cells[i3].props.backgroundColor = m2, o2.updateBlock(r4, {
      type: "table",
      content: {
        ...r4.content,
        rows: f6
      }
    }), o2.setTextCursorPosition(r4);
  };
  if (r4 === void 0 || i3 === void 0 || c3 === void 0)
    return null;
  const a3 = (d = (u2 = r4.content.rows[c3]) == null ? void 0 : u2.cells) == null ? void 0 : d[i3];
  return !a3 || o2.settings.tables.cellTextColor === false && o2.settings.tables.cellBackgroundColor === false ? null : (0, import_jsx_runtime10.jsxs)(t2.Generic.Menu.Root, { position: "right", sub: true, children: [
    (0, import_jsx_runtime10.jsx)(t2.Generic.Menu.Trigger, { sub: true, children: (0, import_jsx_runtime10.jsx)(
      t2.Generic.Menu.Item,
      {
        className: "bn-menu-item",
        subTrigger: true,
        children: e2.children || n.drag_handle.colors_menuitem
      }
    ) }),
    (0, import_jsx_runtime10.jsx)(
      t2.Generic.Menu.Dropdown,
      {
        sub: true,
        className: "bn-menu-dropdown bn-color-picker-dropdown",
        children: (0, import_jsx_runtime10.jsx)(
          xe3,
          {
            iconSize: 18,
            text: o2.settings.tables.cellTextColor ? {
              color: R(a3) ? a3.props.textColor : "default",
              setColor: (m2) => s2(m2, "text")
            } : void 0,
            background: o2.settings.tables.cellBackgroundColor ? {
              color: R(a3) ? a3.props.backgroundColor : "default",
              setColor: (m2) => s2(m2, "background")
            } : void 0
          }
        )
      }
    )
  ] });
};
var hi = () => {
  var a3, u2;
  const e2 = w2(), t2 = M6(), n = v7(), o2 = T3(To2), { block: r4, colIndex: i3, rowIndex: c3 } = E3(
    To2,
    {
      selector: (d) => ({
        block: d == null ? void 0 : d.block,
        colIndex: d == null ? void 0 : d.colIndex,
        rowIndex: d == null ? void 0 : d.rowIndex
      })
    }
  );
  if (r4 === void 0 || i3 === void 0 || c3 === void 0)
    return null;
  const s2 = (u2 = (a3 = r4.content.rows[c3]) == null ? void 0 : a3.cells) == null ? void 0 : u2[i3];
  return !s2 || !R(s2) || D(s2) === 1 && A(s2) === 1 || !n.settings.tables.splitCells ? null : (0, import_jsx_runtime10.jsx)(
    e2.Generic.Menu.Item,
    {
      onClick: () => {
        o2.splitCell({
          row: c3,
          col: i3
        });
      },
      children: t2.table_handle.split_cell_menuitem
    }
  );
};
var gi = (e2) => {
  const t2 = w2();
  return (0, import_jsx_runtime10.jsx)(
    t2.Generic.Menu.Dropdown,
    {
      className: "bn-menu-dropdown bn-table-handle-menu",
      children: e2.children || (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
        (0, import_jsx_runtime10.jsx)(hi, {}),
        (0, import_jsx_runtime10.jsx)(fi, {})
      ] })
    }
  );
};
var bi = (e2) => {
  const t2 = w2(), n = v7(), o2 = T3(To2), r4 = e2.tableCellMenu || gi;
  return !n.settings.tables.splitCells && !n.settings.tables.cellBackgroundColor && !n.settings.tables.cellTextColor ? null : (0, import_jsx_runtime10.jsxs)(
    t2.Generic.Menu.Root,
    {
      onOpenChange: (i3) => {
        i3 ? (o2.freezeHandles(), e2.hideOtherElements(true)) : (o2.unfreezeHandles(), e2.hideOtherElements(false), n.focus());
      },
      position: "right",
      children: [
        (0, import_jsx_runtime10.jsx)(t2.Generic.Menu.Trigger, { children: (0, import_jsx_runtime10.jsx)(t2.Generic.Menu.Button, { className: "bn-table-cell-handle", children: e2.children || (0, import_jsx_runtime10.jsx)(Nr, { size: 12, "data-test": "tableCellHandle" }) }) }),
        (0, import_jsx_runtime10.jsx)(r4, {})
      ]
    }
  );
};
var pi = (e2) => {
  const t2 = v7(), [n, o2] = (0, import_react12.useState)(), r4 = E3(To2), i3 = (0, import_react12.useMemo)(() => {
    const d = {};
    if (r4 === void 0)
      return {};
    const m2 = Tt2(
      r4.block.id,
      t2.prosemirrorState.doc
    );
    if (!m2)
      return {};
    const h7 = m2.posBeforeNode + 1, f6 = t2.prosemirrorView.domAtPos(
      h7 + 1
    ).node;
    if (!(f6 instanceof Element))
      return {};
    if (d.tableReference = { element: f6 }, r4.rowIndex === void 0 || r4.colIndex === void 0)
      return d;
    const g = t2.prosemirrorState.doc.resolve(h7 + 1).posAtIndex(r4.rowIndex), b4 = t2.prosemirrorState.doc.resolve(g + 1).posAtIndex(r4.colIndex), p4 = t2.prosemirrorView.domAtPos(b4 + 1).node;
    return p4 instanceof Element ? (d.cellReference = { element: p4 }, d.rowReference = {
      element: f6,
      getBoundingClientRect: () => {
        const C3 = f6.getBoundingClientRect(), _2 = p4.getBoundingClientRect();
        return new DOMRect(
          C3.x,
          r4.draggingState && r4.draggingState.draggedCellOrientation === "row" ? r4.draggingState.mousePos - _2.height / 2 : _2.y,
          C3.width,
          _2.height
        );
      }
    }, d.columnReference = {
      element: f6,
      getBoundingClientRect: () => {
        const C3 = f6.getBoundingClientRect(), _2 = p4.getBoundingClientRect();
        return new DOMRect(
          r4.draggingState && r4.draggingState.draggedCellOrientation === "col" ? r4.draggingState.mousePos - _2.width / 2 : _2.x,
          C3.y,
          _2.width,
          C3.height
        );
      }
    }, d) : {};
  }, [t2, r4]), c3 = (0, import_react12.useMemo)(
    () => r4 !== void 0 ? {
      rowTableHandle: {
        useFloatingOptions: {
          open: r4.show && r4.rowIndex !== void 0 && (!n || n === "rowTableHandle"),
          placement: "left",
          middleware: [offset3(-10)]
        },
        elementProps: {
          style: {
            zIndex: 10
          }
        }
      },
      columnTableHandle: {
        useFloatingOptions: {
          open: r4.show && r4.colIndex !== void 0 && (!n || n === "columnTableHandle"),
          placement: "top",
          middleware: [offset3(-12)]
        },
        elementProps: {
          style: {
            zIndex: 10
          }
        }
      },
      tableCellHandle: {
        useFloatingOptions: {
          open: r4.show && r4.rowIndex !== void 0 && r4.colIndex !== void 0 && (!n || n === "tableCellHandle"),
          placement: "top-end",
          middleware: [offset3({ mainAxis: -15, crossAxis: -1 })]
        },
        elementProps: {
          style: {
            zIndex: 10
          }
        }
      },
      extendRowsButton: {
        useFloatingOptions: {
          open: r4.show && r4.showAddOrRemoveRowsButton && (!n || n === "extendRowsButton"),
          placement: "bottom",
          middleware: [
            size4({
              apply({ rects: d, elements: m2 }) {
                Object.assign(m2.floating.style, {
                  width: `${d.reference.width}px`
                });
              }
            })
          ]
        },
        elementProps: {
          style: {
            zIndex: 10
          }
        }
      },
      extendColumnsButton: {
        useFloatingOptions: {
          open: r4.show && r4.showAddOrRemoveColumnsButton && (!n || n === "extendColumnsButton"),
          placement: "right",
          middleware: [
            size4({
              apply({ rects: d, elements: m2 }) {
                Object.assign(m2.floating.style, {
                  height: `${d.reference.height}px`
                });
              }
            })
          ]
        },
        elementProps: {
          style: {
            zIndex: 10
          }
        }
      }
    } : void 0,
    [n, r4]
  );
  if (!r4)
    return null;
  const s2 = e2.tableHandle || mi, a3 = e2.extendButton || li3, u2 = e2.tableCellHandle || bi;
  return (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
    (0, import_jsx_runtime10.jsx)(
      U4,
      {
        reference: i3 == null ? void 0 : i3.rowReference,
        ...c3 == null ? void 0 : c3.rowTableHandle,
        children: r4.show && r4.rowIndex !== void 0 && (!n || n === "rowTableHandle") && (0, import_jsx_runtime10.jsx)(
          s2,
          {
            orientation: "row",
            hideOtherElements: (d) => o2(d ? "rowTableHandle" : void 0)
          }
        )
      }
    ),
    (0, import_jsx_runtime10.jsx)(
      U4,
      {
        reference: i3 == null ? void 0 : i3.columnReference,
        ...c3 == null ? void 0 : c3.columnTableHandle,
        children: r4.show && r4.colIndex !== void 0 && (!n || n === "columnTableHandle") && (0, import_jsx_runtime10.jsx)(
          s2,
          {
            orientation: "column",
            hideOtherElements: (d) => o2(d ? "columnTableHandle" : void 0)
          }
        )
      }
    ),
    (0, import_jsx_runtime10.jsx)(
      U4,
      {
        reference: i3 == null ? void 0 : i3.cellReference,
        ...c3 == null ? void 0 : c3.tableCellHandle,
        children: r4.show && r4.rowIndex !== void 0 && r4.colIndex !== void 0 && (!n || n === "tableCellHandle") && (0, import_jsx_runtime10.jsx)(
          u2,
          {
            hideOtherElements: (d) => o2(d ? "tableCellHandle" : void 0)
          }
        )
      }
    ),
    (0, import_jsx_runtime10.jsx)(
      U4,
      {
        reference: i3 == null ? void 0 : i3.tableReference,
        ...c3 == null ? void 0 : c3.extendRowsButton,
        children: r4.show && r4.showAddOrRemoveRowsButton && (!n || n === "extendRowsButton") && (0, import_jsx_runtime10.jsx)(
          a3,
          {
            orientation: "addOrRemoveRows",
            hideOtherElements: (d) => o2(d ? "extendRowsButton" : void 0)
          }
        )
      }
    ),
    (0, import_jsx_runtime10.jsx)(
      U4,
      {
        reference: i3 == null ? void 0 : i3.tableReference,
        ...c3 == null ? void 0 : c3.extendColumnsButton,
        children: r4.show && r4.showAddOrRemoveColumnsButton && (!n || n === "extendColumnsButton") && (0, import_jsx_runtime10.jsx)(
          a3,
          {
            orientation: "addOrRemoveColumns",
            hideOtherElements: (d) => o2(d ? "extendColumnsButton" : void 0)
          }
        )
      }
    )
  ] });
};
var Ci = (0, import_react12.lazy)(
  () => Promise.resolve().then(() => ll)
);
var vi = (0, import_react12.lazy)(
  () => Promise.resolve().then(() => al)
);
function wi(e2) {
  const t2 = v7();
  if (!t2)
    throw new Error(
      "BlockNoteDefaultUI must be used within a BlockNoteContext.Provider"
    );
  return (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
    t2.getExtension(yo2) && e2.formattingToolbar !== false && (0, import_jsx_runtime10.jsx)(_r, {}),
    t2.getExtension(vo) && e2.linkToolbar !== false && (0, import_jsx_runtime10.jsx)(Or, {}),
    t2.getExtension(_n) && e2.slashMenu !== false && (0, import_jsx_runtime10.jsx)(ri, { triggerCharacter: "/" }),
    t2.getExtension(_n) && e2.emojiPicker !== false && (0, import_jsx_runtime10.jsx)(
      Xr,
      {
        triggerCharacter: ":",
        columns: 10,
        minQueryLength: 2
      }
    ),
    t2.getExtension(Bo2) && e2.sideMenu !== false && (0, import_jsx_runtime10.jsx)(jr, {}),
    t2.getExtension(I2) && e2.filePanel !== false && (0, import_jsx_runtime10.jsx)(uo3, {}),
    t2.getExtension(To2) && e2.tableHandles !== false && (0, import_jsx_runtime10.jsx)(pi, {}),
    t2.getExtension(ne) && e2.comments !== false && (0, import_jsx_runtime10.jsxs)(import_react12.Suspense, { children: [
      (0, import_jsx_runtime10.jsx)(Ci, {}),
      (0, import_jsx_runtime10.jsx)(vi, {})
    ] })
  ] });
}
function ki(e2, t2) {
  const n = q3();
  t2 || (t2 = n == null ? void 0 : n.editor), (0, import_react12.useEffect)(() => {
    if (!t2)
      throw new Error(
        "'editor' is required, either from BlockNoteContext or as a function argument"
      );
    return t2.onChange(e2);
  }, [e2, t2]);
}
function Hi(e2, t2, n) {
  const o2 = q3();
  t2 || (t2 = o2 == null ? void 0 : o2.editor), (0, import_react12.useEffect)(() => {
    if (!t2)
      throw new Error(
        "'editor' is required, either from BlockNoteContext or as a function argument"
      );
    return t2.onSelectionChange(e2, n);
  }, [e2, t2, n]);
}
var xi = () => {
  const e2 = (0, import_react12.useMemo)(
    () => {
      var c3;
      return (c3 = window.matchMedia) == null ? void 0 : c3.call(window, "(prefers-color-scheme: dark)");
    },
    []
  ), t2 = (0, import_react12.useMemo)(
    () => {
      var c3;
      return (c3 = window.matchMedia) == null ? void 0 : c3.call(window, "(prefers-color-scheme: light)");
    },
    []
  ), n = e2 == null ? void 0 : e2.matches, o2 = t2 == null ? void 0 : t2.matches, [r4, i3] = (0, import_react12.useState)(n ? "dark" : o2 ? "light" : "no-preference");
  return (0, import_react12.useEffect)(() => {
    i3(n ? "dark" : o2 ? "light" : "no-preference");
  }, [n, o2]), (0, import_react12.useEffect)(() => {
    if (typeof (e2 == null ? void 0 : e2.addEventListener) == "function") {
      const c3 = ({ matches: a3 }) => a3 && i3("dark"), s2 = ({ matches: a3 }) => a3 && i3("light");
      return e2 == null || e2.addEventListener("change", c3), t2 == null || t2.addEventListener("change", s2), () => {
        e2 == null || e2.removeEventListener("change", c3), t2 == null || t2.removeEventListener("change", s2);
      };
    } else {
      const c3 = () => i3(
        e2.matches ? "dark" : t2.matches ? "light" : "no-preference"
      );
      return e2 == null || e2.addEventListener("change", c3), t2 == null || t2.addEventListener("change", c3), () => {
        e2 == null || e2.removeEventListener("change", c3), t2 == null || t2.removeEventListener("change", c3);
      };
    }
  }, [e2, t2]), typeof window.matchMedia != "function", r4;
};
var Jt4 = (0, import_react12.createContext)(void 0);
function yi() {
  return (0, import_react12.useContext)(Jt4);
}
function Si() {
  const e2 = /* @__PURE__ */ new Set();
  let t2 = {};
  return {
    /**
     * Subscribe to the editor instance's changes.
     */
    subscribe(n) {
      return e2.add(n), () => {
        e2.delete(n);
      };
    },
    getSnapshot() {
      return t2;
    },
    getServerSnapshot() {
      return t2;
    },
    /**
     * Adds a new NodeView Renderer to the editor.
     */
    setRenderer(n, o2) {
      t2 = {
        ...t2,
        [n]: (0, import_react_dom5.createPortal)(o2.reactElement, o2.element, n)
      }, e2.forEach((r4) => r4());
    },
    /**
     * Removes a NodeView Renderer from the editor.
     */
    removeRenderer(n) {
      const o2 = { ...t2 };
      delete o2[n], t2 = o2, e2.forEach((r4) => r4());
    }
  };
}
var Mi = ({
  contentComponent: e2
}) => {
  const t2 = (0, import_react12.useSyncExternalStore)(
    e2.subscribe,
    e2.getSnapshot,
    e2.getServerSnapshot
  );
  return (0, import_jsx_runtime10.jsx)(import_jsx_runtime10.Fragment, { children: Object.values(t2) });
};
var Vi = (0, import_react12.forwardRef)((e2, t2) => {
  const [n, o2] = (0, import_react12.useState)();
  return (0, import_react12.useImperativeHandle)(t2, () => (r4, i3) => {
    (0, import_react_dom5.flushSync)(() => {
      o2({ node: r4, container: i3 });
    }), o2(void 0);
  }, []), (0, import_jsx_runtime10.jsx)(import_jsx_runtime10.Fragment, { children: n && (0, import_react_dom5.createPortal)(n.node, n.container) });
});
var gt3 = () => {
};
function Ti(e2, t2) {
  const {
    editor: n,
    className: o2,
    theme: r4,
    children: i3,
    editable: c3,
    onSelectionChange: s2,
    onChange: a3,
    formattingToolbar: u2,
    linkToolbar: d,
    slashMenu: m2,
    emojiPicker: h7,
    sideMenu: f6,
    filePanel: g,
    tableHandles: b4,
    comments: p4,
    autoFocus: C3,
    renderEditor: _2 = true,
    ...N3
  } = e2, [O2, $6] = (0, import_react12.useState)(), B4 = q3(), I4 = xi(), K6 = (B4 == null ? void 0 : B4.colorSchemePreference) || I4, ne3 = r4 || (K6 === "dark" ? "dark" : "light");
  ki(a3 || gt3, n), Hi(s2 || gt3, n), (0, import_react12.useEffect)(() => {
    n.isEditable = c3 !== false;
  }, [c3, n]);
  const z2 = (0, import_react12.useCallback)(
    (rn3) => {
      n.elementRenderer = rn3;
    },
    [n]
  ), Q3 = (0, import_react12.useMemo)(() => ({
    ...B4,
    editor: n,
    setContentEditableProps: $6,
    colorSchemePreference: ne3
  }), [B4, n, ne3]), on3 = (0, import_react12.useMemo)(() => ({
    editorProps: {
      autoFocus: C3,
      contentEditableProps: O2
    },
    defaultUIProps: {
      formattingToolbar: u2,
      linkToolbar: d,
      slashMenu: m2,
      emojiPicker: h7,
      sideMenu: f6,
      filePanel: g,
      tableHandles: b4,
      comments: p4
    }
  }), [
    C3,
    O2,
    u2,
    d,
    m2,
    h7,
    f6,
    g,
    b4,
    p4
  ]);
  return (0, import_jsx_runtime10.jsx)(_t5.Provider, { value: Q3, children: (0, import_jsx_runtime10.jsxs)(Jt4.Provider, { value: on3, children: [
    (0, import_jsx_runtime10.jsx)(Vi, { ref: z2 }),
    (0, import_jsx_runtime10.jsx)(
      _i,
      {
        className: o2,
        renderEditor: _2,
        editable: c3,
        editorColorScheme: ne3,
        ref: t2,
        ...N3,
        children: i3
      }
    )
  ] }) });
}
var _i = import_react12.default.forwardRef(
  ({ className: e2, renderEditor: t2, editable: n, editorColorScheme: o2, children: r4, ...i3 }, c3) => (0, import_jsx_runtime10.jsx)(
    "div",
    {
      className: D2("bn-container", o2, e2),
      "data-color-scheme": o2,
      ...i3,
      ref: c3,
      children: t2 ? (0, import_jsx_runtime10.jsx)(Ei, { editable: n, children: r4 }) : r4
    }
  )
);
var yl = import_react12.default.forwardRef(Ti);
var Ei = (e2) => {
  const t2 = yi(), n = v7(), o2 = (0, import_react12.useMemo)(() => Si(), []), r4 = (0, import_react12.useCallback)(
    (i3) => {
      e2.editable !== void 0 && e2.editable !== n.isEditable && (n.isEditable = e2.editable), n._tiptapEditor.contentComponent = o2, i3 ? n.mount(i3) : n.unmount();
    },
    [n, o2, e2.editable]
  );
  return (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
    (0, import_jsx_runtime10.jsx)(Mi, { contentComponent: o2 }),
    (0, import_jsx_runtime10.jsx)(Bi, { ...t2.editorProps, ...e2, mount: r4 }),
    (0, import_jsx_runtime10.jsx)(wi, { ...t2.defaultUIProps }),
    e2.children
  ] });
};
var Bi = (e2) => {
  const { autoFocus: t2, mount: n, contentEditableProps: o2 } = e2;
  return (0, import_jsx_runtime10.jsx)(
    "div",
    {
      "aria-autocomplete": "list",
      "aria-haspopup": "listbox",
      "data-bn-autofocus": t2,
      ref: n,
      ...o2
    }
  );
};
function Y4(e2, t2) {
  let n;
  const o2 = document.createElement("div");
  let r4;
  if (t2 != null && t2.elementRenderer)
    t2.elementRenderer(
      e2((a3) => n = a3 || void 0),
      o2
    );
  else {
    if (!(t2 != null && t2.headless))
      throw new Error(
        "elementRenderer not available, expected headless editor"
      );
    r4 = (0, import_client.createRoot)(o2), (0, import_react_dom5.flushSync)(() => {
      r4.render(e2((a3) => n = a3 || void 0));
    });
  }
  if (!o2.childElementCount)
    return console.warn("ReactInlineContentSpec: renderHTML() failed"), {
      dom: document.createElement("span")
    };
  n == null || n.setAttribute("data-tmp-find", "true");
  const i3 = o2.cloneNode(true), c3 = i3.firstElementChild, s2 = i3.querySelector(
    "[data-tmp-find]"
  );
  return s2 == null || s2.removeAttribute("data-tmp-find"), r4 == null || r4.unmount(), {
    dom: c3,
    contentDOM: s2 || void 0
  };
}
function Le3(e2) {
  var t2;
  return (
    // Creates `blockContent` element
    (0, import_jsx_runtime10.jsx)(
      NodeViewWrapper,
      {
        onDragOver: (n) => n.preventDefault(),
        ...Object.fromEntries(
          Object.entries(e2.domAttributes || {}).filter(
            ([n]) => n !== "class"
          )
        ),
        className: D2(
          "bn-block-content",
          ((t2 = e2.domAttributes) == null ? void 0 : t2.class) || ""
        ),
        "data-content-type": e2.blockType,
        ...Object.fromEntries(
          Object.entries(e2.blockProps).filter(([n, o2]) => {
            const r4 = e2.propSchema[n];
            return o2 !== r4.default;
          }).map(([n, o2]) => [W(n), o2])
        ),
        "data-file-block": e2.isFileBlock === true || void 0,
        children: e2.children
      }
    )
  );
}
function ye2(e2, t2, n) {
  return (o2 = {}) => {
    const r4 = typeof e2 == "function" ? e2(o2) : e2, i3 = typeof t2 == "function" ? t2(o2) : t2, c3 = n ? typeof n == "function" ? n(o2) : n : void 0;
    return {
      config: r4,
      implementation: {
        ...i3,
        toExternalHTML(s2, a3) {
          const u2 = i3.toExternalHTML || i3.render;
          return Y4((m2) => (0, import_jsx_runtime10.jsx)(
            Le3,
            {
              blockType: s2.type,
              blockProps: s2.props,
              propSchema: r4.propSchema,
              domAttributes: this.blockContentDOMAttributes,
              children: (0, import_jsx_runtime10.jsx)(
                u2,
                {
                  block: s2,
                  editor: a3,
                  contentRef: (h7) => {
                    m2(h7), h7 && (h7.className = D2(
                      "bn-inline-content",
                      h7.className
                    ));
                  }
                }
              )
            }
          ), a3);
        },
        render(s2, a3) {
          if (this.renderType === "nodeView")
            return ReactNodeViewRenderer(
              (u2) => {
                var f6;
                const d = kt2(
                  u2.getPos,
                  a3,
                  u2.editor,
                  r4.type
                ), m2 = useReactNodeView().nodeViewContentRef;
                if (!m2)
                  throw new Error("nodeViewContentRef is not set");
                const h7 = i3.render;
                return (0, import_jsx_runtime10.jsx)(
                  Le3,
                  {
                    blockType: d.type,
                    blockProps: d.props,
                    propSchema: r4.propSchema,
                    isFileBlock: !!((f6 = i3.meta) != null && f6.fileBlockAccept),
                    domAttributes: this.blockContentDOMAttributes,
                    children: (0, import_jsx_runtime10.jsx)(
                      h7,
                      {
                        block: d,
                        editor: a3,
                        contentRef: (g) => {
                          m2(g), g && (g.className = D2(
                            "bn-inline-content",
                            g.className
                          ), g.dataset.nodeViewContent = "");
                        }
                      }
                    )
                  }
                );
              },
              {
                className: "bn-react-node-view-renderer"
              }
            )(this.props);
          {
            const u2 = i3.render;
            return Y4((m2) => (0, import_jsx_runtime10.jsx)(
              Le3,
              {
                blockType: s2.type,
                blockProps: s2.props,
                propSchema: r4.propSchema,
                domAttributes: this.blockContentDOMAttributes,
                children: (0, import_jsx_runtime10.jsx)(
                  u2,
                  {
                    block: s2,
                    editor: a3,
                    contentRef: (h7) => {
                      m2(h7), h7 && (h7.className = D2(
                        "bn-inline-content",
                        h7.className
                      ));
                    }
                  }
                )
              }
            ), a3);
          }
        }
      },
      extensions: c3
    };
  };
}
function We(e2) {
  const t2 = v7(), [n, o2] = (0, import_react12.useState)("loading"), [r4, i3] = (0, import_react12.useState)();
  if ((0, import_react12.useEffect)(() => {
    let c3 = true;
    return (async () => {
      let s2 = "";
      o2("loading");
      try {
        s2 = t2.resolveFileUrl ? await t2.resolveFileUrl(e2) : e2;
      } catch {
        o2("error");
        return;
      }
      c3 && (o2("loaded"), i3(s2));
    })(), () => {
      c3 = false;
    };
  }, [t2, e2]), n !== "loaded")
    return {
      loadingState: n
    };
  if (!r4)
    throw new Error("Finished fetching file but did not get download URL.");
  return {
    loadingState: n,
    downloadUrl: r4
  };
}
var qe = (e2) => (0, import_jsx_runtime10.jsxs)("figure", { children: [
  e2.children,
  (0, import_jsx_runtime10.jsx)("figcaption", { children: e2.caption })
] });
function Li(e2) {
  const t2 = v7();
  (0, import_react12.useEffect)(() => t2.onUploadEnd(e2), [e2, t2]);
}
function Ri(e2) {
  const t2 = v7();
  (0, import_react12.useEffect)(() => t2.onUploadStart(e2), [e2, t2]);
}
function Qt3(e2) {
  const [t2, n] = (0, import_react12.useState)(false);
  return Ri((o2) => {
    o2 === e2 && n(true);
  }), Li((o2) => {
    o2 === e2 && n(false);
  }), t2;
}
var Oi = (e2) => {
  const t2 = v7(), n = M6(), o2 = T3(I2), r4 = (0, import_react12.useCallback)(
    (c3) => {
      c3.preventDefault();
    },
    []
  ), i3 = (0, import_react12.useCallback)(() => {
    t2.isEditable && e2.editor.transact(() => o2.showMenu(e2.block.id));
  }, [t2.isEditable, o2, e2.block.id, e2.editor]);
  return (0, import_jsx_runtime10.jsxs)(
    "div",
    {
      className: "bn-add-file-button",
      onMouseDown: r4,
      onClick: i3,
      children: [
        (0, import_jsx_runtime10.jsx)("div", { className: "bn-add-file-button-icon", children: e2.buttonIcon || (0, import_jsx_runtime10.jsx)(je, { size: 24 }) }),
        (0, import_jsx_runtime10.jsx)("div", { className: "bn-add-file-button-text", children: e2.block.type in n.file_blocks.add_button_text ? n.file_blocks.add_button_text[e2.block.type] : n.file_blocks.add_button_text.file })
      ]
    }
  );
};
var Ii = (e2) => (0, import_jsx_runtime10.jsxs)(
  "div",
  {
    className: "bn-file-name-with-icon",
    contentEditable: false,
    draggable: false,
    children: [
      (0, import_jsx_runtime10.jsx)("div", { className: "bn-file-icon", children: (0, import_jsx_runtime10.jsx)(je, { size: 24 }) }),
      (0, import_jsx_runtime10.jsx)("p", { className: "bn-file-name", children: e2.block.props.name })
    ]
  }
);
var Ke = (e2) => {
  const t2 = Qt3(e2.block.id);
  return (0, import_jsx_runtime10.jsx)(
    "div",
    {
      className: "bn-file-block-content-wrapper",
      onMouseEnter: e2.onMouseEnter,
      onMouseLeave: e2.onMouseLeave,
      style: e2.style,
      children: t2 ? (
        // Show loader while a file is being uploaded.
        (0, import_jsx_runtime10.jsx)("div", { className: "bn-file-loading-preview", children: "Loading..." })
      ) : e2.block.props.url === "" ? (
        // Show the add file button if the file has not been uploaded yet.
        (0, import_jsx_runtime10.jsx)(Oi, { ...e2 })
      ) : (
        // Show the file preview, or the file name and icon.
        (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
          e2.block.props.showPreview === false || !e2.children ? (
            // Show file name and icon.
            (0, import_jsx_runtime10.jsx)(Ii, { ...e2 })
          ) : (
            // Show preview.
            e2.children
          ),
          e2.block.props.caption && // Show the caption if there is one.
          (0, import_jsx_runtime10.jsx)("p", { className: "bn-file-caption", children: e2.block.props.caption })
        ] })
      )
    }
  );
};
var Se2 = (e2) => (0, import_jsx_runtime10.jsxs)("div", { children: [
  e2.children,
  (0, import_jsx_runtime10.jsx)("p", { children: e2.caption })
] });
var Pi = (e2) => {
  const t2 = We(e2.block.props.url);
  return (0, import_jsx_runtime10.jsx)(
    "audio",
    {
      className: "bn-audio",
      src: t2.loadingState === "loading" ? e2.block.props.url : t2.downloadUrl,
      controls: true,
      contentEditable: false,
      draggable: false
    }
  );
};
var Ni = (e2) => {
  if (!e2.block.props.url)
    return (0, import_jsx_runtime10.jsx)("p", { children: "Add audio" });
  const t2 = e2.block.props.showPreview ? (0, import_jsx_runtime10.jsx)("audio", { src: e2.block.props.url }) : (0, import_jsx_runtime10.jsx)("a", { href: e2.block.props.url, children: e2.block.props.name || e2.block.props.url });
  return e2.block.props.caption ? e2.block.props.showPreview ? (0, import_jsx_runtime10.jsx)(qe, { caption: e2.block.props.caption, children: t2 }) : (0, import_jsx_runtime10.jsx)(Se2, { caption: e2.block.props.caption, children: t2 }) : t2;
};
var Ai = (e2) => (0, import_jsx_runtime10.jsx)(
  Ke,
  {
    ...e2,
    buttonIcon: (0, import_jsx_runtime10.jsx)($t4, { size: 24 }),
    children: (0, import_jsx_runtime10.jsx)(Pi, { ...e2 })
  }
);
var Sl = ye2(
  _t3,
  (e2) => ({
    render: Ai,
    parse: Vt(e2),
    toExternalHTML: Ni,
    runsBefore: ["file"]
  })
);
var Ml = ye2(Zt, {
  render: (e2) => (0, import_jsx_runtime10.jsx)(Ke, { ...e2 }),
  parse: zt(),
  toExternalHTML: (e2) => {
    if (!e2.block.props.url)
      return (0, import_jsx_runtime10.jsx)("p", { children: "Add file" });
    const t2 = (0, import_jsx_runtime10.jsx)("a", { href: e2.block.props.url, children: e2.block.props.name || e2.block.props.url });
    return e2.block.props.caption ? (0, import_jsx_runtime10.jsx)(Se2, { caption: e2.block.props.caption, children: t2 }) : t2;
  }
});
var en3 = (e2) => {
  const [t2, n] = (0, import_react12.useState)(void 0), [o2, r4] = (0, import_react12.useState)(
    e2.block.props.previewWidth
  ), [i3, c3] = (0, import_react12.useState)(false), s2 = (0, import_react12.useRef)(null);
  (0, import_react12.useEffect)(() => {
    const f6 = (b4) => {
      var N3, O2;
      let p4;
      const C3 = "touches" in b4 ? b4.touches[0].clientX : b4.clientX;
      e2.block.props.textAlignment === "center" ? t2.handleUsed === "left" ? p4 = t2.initialWidth + (t2.initialClientX - C3) * 2 : p4 = t2.initialWidth + (C3 - t2.initialClientX) * 2 : t2.handleUsed === "left" ? p4 = t2.initialWidth + t2.initialClientX - C3 : p4 = t2.initialWidth + C3 - t2.initialClientX, r4(
        Math.min(
          Math.max(p4, 64),
          ((O2 = (N3 = e2.editor.domElement) == null ? void 0 : N3.firstElementChild) == null ? void 0 : O2.clientWidth) || Number.MAX_VALUE
        )
      );
    }, g = () => {
      n(void 0), e2.editor.updateBlock(e2.block, {
        props: {
          previewWidth: o2
        }
      });
    };
    return t2 && (window.addEventListener("mousemove", f6), window.addEventListener("touchmove", f6), window.addEventListener("mouseup", g), window.addEventListener("touchend", g)), () => {
      window.removeEventListener("mousemove", f6), window.removeEventListener("touchmove", f6), window.removeEventListener("mouseup", g), window.removeEventListener("touchend", g);
    };
  }, [e2, t2, o2]);
  const a3 = (0, import_react12.useCallback)(() => {
    e2.editor.isEditable && c3(true);
  }, [e2.editor.isEditable]), u2 = (0, import_react12.useCallback)(() => {
    c3(false);
  }, []), d = (0, import_react12.useCallback)(
    (f6) => {
      f6.preventDefault();
      const g = "touches" in f6 ? f6.touches[0].clientX : f6.clientX;
      n({
        handleUsed: "left",
        initialWidth: s2.current.clientWidth,
        initialClientX: g
      });
    },
    []
  ), m2 = (0, import_react12.useCallback)(
    (f6) => {
      f6.preventDefault();
      const g = "touches" in f6 ? f6.touches[0].clientX : f6.clientX;
      n({
        handleUsed: "right",
        initialWidth: s2.current.clientWidth,
        initialClientX: g
      });
    },
    []
  ), h7 = Qt3(e2.block.id);
  return (0, import_jsx_runtime10.jsx)(
    Ke,
    {
      ...e2,
      onMouseEnter: a3,
      onMouseLeave: u2,
      style: e2.block.props.url && !h7 && e2.block.props.showPreview ? {
        width: o2 ? `${o2}px` : "fit-content"
      } : void 0,
      children: (0, import_jsx_runtime10.jsxs)(
        "div",
        {
          className: "bn-visual-media-wrapper",
          style: { position: "relative" },
          ref: s2,
          children: [
            e2.children,
            (i3 || t2) && (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
              (0, import_jsx_runtime10.jsx)(
                "div",
                {
                  className: "bn-resize-handle",
                  style: { left: "4px" },
                  onMouseDown: d,
                  onTouchStart: d
                }
              ),
              (0, import_jsx_runtime10.jsx)(
                "div",
                {
                  className: "bn-resize-handle",
                  style: { right: "4px" },
                  onMouseDown: m2,
                  onTouchStart: m2
                }
              )
            ] }),
            t2 && (0, import_jsx_runtime10.jsx)(
              "div",
              {
                style: {
                  position: "absolute",
                  height: "100%",
                  width: "100%"
                }
              }
            )
          ]
        }
      )
    }
  );
};
var Zi = (e2) => {
  const t2 = We(e2.block.props.url);
  return (0, import_jsx_runtime10.jsx)(
    "img",
    {
      className: "bn-visual-media",
      src: t2.loadingState === "loading" ? e2.block.props.url : t2.downloadUrl,
      alt: e2.block.props.caption || "BlockNote image",
      contentEditable: false,
      draggable: false
    }
  );
};
var Di = (e2) => {
  if (!e2.block.props.url)
    return (0, import_jsx_runtime10.jsx)("p", { children: "Add image" });
  const t2 = e2.block.props.showPreview ? (0, import_jsx_runtime10.jsx)(
    "img",
    {
      src: e2.block.props.url,
      alt: e2.block.props.name || e2.block.props.caption || "BlockNote image",
      width: e2.block.props.previewWidth
    }
  ) : (0, import_jsx_runtime10.jsx)("a", { href: e2.block.props.url, children: e2.block.props.name || e2.block.props.url });
  return e2.block.props.caption ? e2.block.props.showPreview ? (0, import_jsx_runtime10.jsx)(qe, { caption: e2.block.props.caption, children: t2 }) : (0, import_jsx_runtime10.jsx)(Se2, { caption: e2.block.props.caption, children: t2 }) : t2;
};
var Fi = (e2) => (0, import_jsx_runtime10.jsx)(
  en3,
  {
    ...e2,
    buttonIcon: (0, import_jsx_runtime10.jsx)(Ut3, { size: 24 }),
    children: (0, import_jsx_runtime10.jsx)(Zi, { ...e2 })
  }
);
var Vl = ye2(
  tn,
  (e2) => ({
    render: Fi,
    parse: nn(e2),
    toExternalHTML: Di
  })
);
function Gi(e2) {
  return k2({ attr: { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, child: [{ tag: "path", attr: { d: "M14 3v4a1 1 0 0 0 1 1h4" }, child: [] }, { tag: "path", attr: { d: "M19 18v1a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-1" }, child: [] }, { tag: "path", attr: { d: "M3 14h3m4.5 0h3m4.5 0h3" }, child: [] }, { tag: "path", attr: { d: "M5 10v-5a2 2 0 0 1 2 -2h7l5 5v2" }, child: [] }] })(e2);
}
var zi = {
  page_break: Gi
};
function Tl(e2) {
  return U3(e2).map((t2) => {
    const n = zi[t2.key];
    return {
      ...t2,
      icon: (0, import_jsx_runtime10.jsx)(n, { size: 18 })
    };
  });
}
var Ui = (e2) => {
  const t2 = We(e2.block.props.url);
  return (0, import_jsx_runtime10.jsx)(
    "video",
    {
      className: "bn-visual-media",
      src: t2.loadingState === "loading" ? e2.block.props.url : t2.downloadUrl,
      controls: true,
      contentEditable: false,
      draggable: false
    }
  );
};
var ji = (e2) => {
  if (!e2.block.props.url)
    return (0, import_jsx_runtime10.jsx)("p", { children: "Add video" });
  const t2 = e2.block.props.showPreview ? (0, import_jsx_runtime10.jsx)("video", { src: e2.block.props.url }) : (0, import_jsx_runtime10.jsx)("a", { href: e2.block.props.url, children: e2.block.props.name || e2.block.props.url });
  return e2.block.props.caption ? e2.block.props.showPreview ? (0, import_jsx_runtime10.jsx)(qe, { caption: e2.block.props.caption, children: t2 }) : (0, import_jsx_runtime10.jsx)(Se2, { caption: e2.block.props.caption, children: t2 }) : t2;
};
var $i = (e2) => (0, import_jsx_runtime10.jsx)(
  en3,
  {
    ...e2,
    buttonIcon: (0, import_jsx_runtime10.jsx)(Xo2, { size: 24 }),
    children: (0, import_jsx_runtime10.jsx)(Ui, { ...e2 })
  }
);
var _l = ye2(
  An,
  (e2) => ({
    render: $i,
    parse: Pn(e2),
    toExternalHTML: ji
  })
);
var Wi = (e2, t2) => {
  if (t2.type === "toggled")
    return !e2;
  if (t2.type === "childAdded")
    return true;
  if (t2.type === "lastChildRemoved")
    return false;
  throw new O(t2);
};
var El = (e2) => {
  const { block: t2, editor: n, children: o2, toggledState: r4 } = e2, [i3, c3] = (0, import_react12.useReducer)(
    Wi,
    (r4 || Kt).get(t2)
  ), s2 = (m2) => {
    (r4 || Kt).set(
      n.getBlock(m2),
      !i3
    ), c3({
      type: "toggled"
    });
  }, a3 = (m2) => {
    (r4 || Kt).set(m2, true), c3({
      type: "childAdded"
    });
  }, u2 = (m2) => {
    (r4 || Kt).set(m2, false), c3({
      type: "lastChildRemoved"
    });
  }, d = R4({
    editor: n,
    selector: ({ editor: m2 }) => {
      if (!Lo(t2, m2, t2.type, { isToggleable: "boolean" }) && !t2.props.isToggleable)
        return 0;
      const h7 = m2.getBlock(t2), f6 = h7.children.length || 0;
      return f6 > d ? i3 || a3(h7) : f6 === 0 && f6 < d && i3 && u2(h7), f6;
    }
  });
  return "isToggleable" in t2.props && !t2.props.isToggleable ? o2 : (0, import_jsx_runtime10.jsxs)("div", { children: [
    (0, import_jsx_runtime10.jsxs)("div", { className: "bn-toggle-wrapper", "data-show-children": i3, children: [
      (0, import_jsx_runtime10.jsx)(
        "button",
        {
          className: "bn-toggle-button",
          type: "button",
          onMouseDown: (m2) => m2.preventDefault(),
          onClick: () => s2(n.getBlock(t2)),
          children: (0, import_jsx_runtime10.jsx)(
            "svg",
            {
              xmlns: "http://www.w3.org/2000/svg",
              height: "1em",
              viewBox: "0 -960 960 960",
              width: "1em",
              fill: "currentcolor",
              children: (0, import_jsx_runtime10.jsx)("path", { d: "M472-480 332-620q-18-18-18-44t18-44q18-18 44-18t44 18l183 183q9 9 14 21t5 24q0 12-5 24t-14 21L420-252q-18 18-44 18t-44-18q-18-18-18-44t18-44l140-140Z" })
            }
          )
        }
      ),
      o2
    ] }),
    n.isEditable && i3 && d === 0 && (0, import_jsx_runtime10.jsx)(
      "button",
      {
        className: "bn-toggle-add-block-button",
        type: "button",
        onClick: () => {
          const m2 = n.updateBlock(t2, {
            // Single empty block with default type.
            children: [{}]
          });
          n.setTextCursorPosition(m2.children[0].id, "end"), n.focus();
        },
        children: n.dictionary.toggle_blocks.add_block_button
      }
    )
  ] });
};
var Bl = (e2) => {
  const [t2, n] = (0, import_react12.useState)("none"), o2 = (0, import_react12.useRef)(null), r4 = v7(), i3 = E3(yo2, {
    editor: r4
  }), c3 = (0, import_react12.useMemo)(() => ({
    display: "flex",
    position: "fixed",
    bottom: 0,
    zIndex: "calc(var(--bn-ui-base-z-index) + 40)",
    transform: t2
  }), [t2]);
  if ((0, import_react12.useEffect)(() => {
    const a3 = window.visualViewport;
    function u2() {
      const d = document.body, m2 = a3.offsetLeft, h7 = a3.height - d.getBoundingClientRect().height + a3.offsetTop;
      n(
        `translate(${m2}px, ${h7}px) scale(${1 / a3.scale})`
      );
    }
    return window.visualViewport.addEventListener("scroll", u2), window.visualViewport.addEventListener("resize", u2), u2(), () => {
      window.visualViewport.removeEventListener("scroll", u2), window.visualViewport.removeEventListener("resize", u2);
    };
  }, []), !i3 && o2.current)
    return (0, import_jsx_runtime10.jsx)(
      "div",
      {
        ref: o2,
        style: c3,
        dangerouslySetInnerHTML: { __html: o2.current.innerHTML }
      }
    );
  const s2 = e2.formattingToolbar || qt3;
  return (0, import_jsx_runtime10.jsx)("div", { ref: o2, style: c3, children: (0, import_jsx_runtime10.jsx)(s2, {}) });
};
var Ll = (e2) => {
  const { blockId: t2, colIndex: n, rowIndex: o2, children: r4, ...i3 } = e2, c3 = v7(), s2 = (0, import_react12.useMemo)(() => {
    if (t2 === void 0 || n === void 0 || o2 === void 0)
      return;
    const a3 = Tt2(t2, c3.prosemirrorState.doc);
    if (!a3)
      return;
    const u2 = a3.posBeforeNode + 1, d = c3.prosemirrorState.doc.resolve(u2 + 1).posAtIndex(o2 || 0), m2 = c3.prosemirrorState.doc.resolve(d + 1).posAtIndex(n || 0), { node: h7 } = c3.prosemirrorView.domAtPos(m2 + 1);
    if (h7 instanceof Element)
      return h7;
  }, [c3, t2, n, o2]);
  return (0, import_jsx_runtime10.jsx)(U4, { reference: s2, ...i3, children: r4 });
};
function bt4(e2, t2, n) {
  const { refs: o2, update: r4, context: i3, floatingStyles: c3 } = useFloating2({
    open: t2,
    placement: e2 === "addOrRemoveColumns" ? "right" : "bottom",
    middleware: [
      size4({
        apply({ rects: u2, elements: d }) {
          Object.assign(
            d.floating.style,
            e2 === "addOrRemoveColumns" ? {
              height: `${u2.reference.height}px`
            } : {
              width: `${u2.reference.width}px`
            }
          );
        }
      })
    ]
  }), { isMounted: s2, styles: a3 } = useTransitionStyles(i3);
  return (0, import_react12.useEffect)(() => {
    r4();
  }, [n, r4]), (0, import_react12.useEffect)(() => {
    n !== null && o2.setReference({
      getBoundingClientRect: () => n
    });
  }, [e2, n, o2]), (0, import_react12.useMemo)(
    () => ({
      isMounted: s2,
      ref: o2.setFloating,
      style: {
        display: "flex",
        ...a3,
        ...c3
      }
    }),
    [c3, s2, o2.setFloating, a3]
  );
}
function Rl(e2, t2, n) {
  const o2 = bt4(
    "addOrRemoveRows",
    t2,
    n
  ), r4 = bt4(
    "addOrRemoveColumns",
    e2,
    n
  );
  return (0, import_react12.useMemo)(
    () => ({
      addOrRemoveRowsButton: o2,
      addOrRemoveColumnsButton: r4
    }),
    [r4, o2]
  );
}
function qi(e2, t2, n) {
  return n && n.draggedCellOrientation === "row" ? new DOMRect(
    t2.x,
    n.mousePos,
    t2.width,
    0
  ) : new DOMRect(
    t2.x,
    e2.y,
    t2.width,
    e2.height
  );
}
function Ki(e2, t2, n) {
  return n && n.draggedCellOrientation === "col" ? new DOMRect(
    n.mousePos,
    t2.y,
    0,
    t2.height
  ) : new DOMRect(
    e2.x,
    t2.y,
    e2.width,
    t2.height
  );
}
function Xi(e2) {
  return new DOMRect(
    e2.x,
    e2.y,
    e2.width,
    0
  );
}
function Re(e2, t2, n, o2, r4) {
  const { refs: i3, update: c3, context: s2, floatingStyles: a3 } = useFloating2({
    open: t2,
    placement: e2 === "row" ? "left" : e2 === "col" ? "top" : "bottom-end",
    middleware: [
      offset3(
        e2 === "row" ? -10 : e2 === "col" ? -12 : { mainAxis: 1, crossAxis: -1 }
      )
    ]
  }), { isMounted: u2, styles: d } = useTransitionStyles(s2);
  return (0, import_react12.useEffect)(() => {
    c3();
  }, [n, o2, c3]), (0, import_react12.useEffect)(() => {
    n === null || o2 === null || // Ignore cell handle when dragging
    r4 && e2 === "cell" || i3.setReference({
      getBoundingClientRect: () => (e2 === "row" ? qi : e2 === "col" ? Ki : Xi)(n, o2, r4)
    });
  }, [r4, e2, n, o2, i3]), (0, import_react12.useMemo)(
    () => ({
      isMounted: u2,
      ref: i3.setFloating,
      style: {
        display: "flex",
        ...d,
        ...a3
      }
    }),
    [a3, u2, i3.setFloating, d]
  );
}
function Ol(e2, t2, n, o2) {
  const r4 = Re(
    "row",
    e2,
    t2,
    n,
    o2
  ), i3 = Re(
    "col",
    e2,
    t2,
    n,
    o2
  ), c3 = Re(
    "cell",
    e2,
    t2,
    n,
    o2
  );
  return (0, import_react12.useMemo)(
    () => ({
      rowHandle: r4,
      colHandle: i3,
      cellHandle: c3
    }),
    [i3, r4, c3]
  );
}
var Xe = (e2 = {}, t2 = []) => (0, import_react12.useMemo)(() => {
  const n = Le2.create(e2);
  return window && (window.ProseMirror = n._tiptapEditor), n;
}, t2);
var Ye = (e2) => {
  const [t2, n] = (0, import_react12.useState)(false), o2 = R4({
    editor: e2.editor,
    selector: ({ editor: s2 }) => s2.isEmpty
  }), r4 = w2(), i3 = (0, import_react12.useCallback)(() => {
    n(true);
  }, []), c3 = (0, import_react12.useCallback)(() => {
    n(false);
  }, []);
  return (0, import_react12.useEffect)(() => {
    e2.editable && e2.autoFocus && e2.editor.focus();
  }, [e2.autoFocus, e2.editable, e2.editor]), (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
    (0, import_jsx_runtime10.jsx)(
      r4.Comments.Editor,
      {
        autoFocus: e2.autoFocus,
        className: "bn-comment-editor",
        editor: e2.editor,
        onFocus: i3,
        onBlur: c3,
        editable: e2.editable
      }
    ),
    e2.actions && (0, import_jsx_runtime10.jsx)("div", { className: "bn-comment-actions-wrapper", children: (0, import_jsx_runtime10.jsx)(e2.actions, { isFocused: t2, isEmpty: o2 }) })
  ] });
};
var me2;
async function Yi() {
  return me2 || (me2 = (async () => {
    const [e2, t2] = await Promise.all([
      import("./module-4GIHSJCO.js"),
      // use a dynamic import to encourage bundle-splitting
      // and a smaller initial client bundle size
      import("./native-JYCSL3WK.js")
    ]), n = "default" in e2 ? e2.default : e2, o2 = "default" in t2 ? t2.default : t2;
    return await n.init({ data: o2 }), { emojiMart: n, emojiData: o2 };
  })(), me2);
}
function Ji(e2) {
  const t2 = (0, import_react12.useRef)(null), n = (0, import_react12.useRef)(null);
  return n.current && n.current.update(e2), (0, import_react12.useEffect)(() => ((async () => {
    const { emojiMart: o2 } = await Yi();
    n.current = new o2.Picker({ ...e2, ref: t2 });
  })(), () => {
    n.current = null;
  }), []), import_react12.default.createElement("div", { ref: t2 });
}
var pt2 = (e2) => {
  const [t2, n] = (0, import_react12.useState)(false), o2 = w2(), r4 = v7(), i3 = q3();
  return (0, import_jsx_runtime10.jsxs)(o2.Generic.Popover.Root, { open: t2, children: [
    (0, import_jsx_runtime10.jsx)(o2.Generic.Popover.Trigger, { children: (0, import_jsx_runtime10.jsx)(
      "div",
      {
        onClick: (c3) => {
          var s2;
          c3.preventDefault(), c3.stopPropagation(), n(!t2), (s2 = e2.onOpenChange) == null || s2.call(e2, !t2);
        },
        style: {
          display: "flex",
          justifyContent: "center",
          alignItems: "center"
        },
        children: e2.children
      }
    ) }),
    (0, import_react_dom5.createPortal)(
      (0, import_jsx_runtime10.jsx)(
        o2.Generic.Popover.Content,
        {
          className: "bn-emoji-picker-popover",
          variant: "panel-popover",
          children: (0, import_jsx_runtime10.jsx)(
            Ji,
            {
              perLine: 7,
              onClickOutside: () => {
                var c3;
                n(false), (c3 = e2.onOpenChange) == null || c3.call(e2, false);
              },
              onEmojiSelect: (c3) => {
                var s2;
                e2.onEmojiSelect(c3), n(false), (s2 = e2.onOpenChange) == null || s2.call(e2, false);
              },
              theme: i3 == null ? void 0 : i3.colorSchemePreference
            }
          )
        }
      ),
      r4.domElement.parentElement
    )
  ] });
};
function Qi(e2) {
  return Je([e2]).get(e2);
}
function Je(e2) {
  const n = T3(ne).userStore, o2 = (0, import_react12.useCallback)(() => {
    const c3 = /* @__PURE__ */ new Map();
    for (const s2 of e2) {
      const a3 = n.getUser(s2);
      a3 && c3.set(s2, a3);
    }
    return c3;
  }, [n, e2]), r4 = (0, import_react12.useMemo)(() => ({
    current: o2()
  }), [o2]), i3 = (0, import_react12.useCallback)(
    (c3) => {
      const s2 = n.subscribe((a3) => {
        r4.current = o2(), c3();
      });
      return n.loadUsers(e2), s2;
    },
    [n, o2, e2, r4]
  );
  return (0, import_react12.useSyncExternalStore)(i3, () => r4.current);
}
var el = (e2) => {
  const t2 = w2(), n = M6(), o2 = T3(ne), r4 = e2.comment.reactions.find(
    (a3) => a3.emoji === e2.emoji
  );
  if (!r4)
    throw new Error(
      "Trying to render reaction badge for non-existing reaction"
    );
  const [i3, c3] = (0, import_react12.useState)([]), s2 = Je(i3);
  return (0, import_jsx_runtime10.jsx)(
    t2.Generic.Badge.Root,
    {
      className: D2("bn-badge", "bn-comment-reaction"),
      text: r4.userIds.length.toString(),
      icon: r4.emoji,
      isSelected: o2.threadStore.auth.canDeleteReaction(
        e2.comment,
        r4.emoji
      ),
      onClick: () => e2.onReactionSelect(r4.emoji),
      onMouseEnter: () => c3(r4.userIds),
      mainTooltip: n.comments.reactions.reacted_by,
      secondaryTooltip: `${Array.from(s2.values()).map((a3) => a3.username).join(`
`)}`
    },
    r4.emoji
  );
};
var { textColor: Il, backgroundColor: Pl, ...tl } = Fn;
var Qe = h5.create({
  blockSpecs: {
    paragraph: bn()
  },
  styleSpecs: tl
});
var nl = ({
  comment: e2,
  thread: t2,
  showResolveButton: n
}) => {
  const o2 = T3(ne), r4 = M6(), i3 = Xe({
    initialContent: e2.body,
    trailingBlock: false,
    dictionary: {
      ...r4,
      placeholders: {
        emptyDocument: r4.placeholders.edit_comment
      }
    },
    schema: o2.commentEditorSchema || Qe
  }), c3 = w2(), [s2, a3] = (0, import_react12.useState)(false), [u2, d] = (0, import_react12.useState)(false), m2 = o2.threadStore, h7 = (0, import_react12.useCallback)(() => {
    a3(true);
  }, []), f6 = (0, import_react12.useCallback)(() => {
    i3.replaceBlocks(i3.document, e2.body), a3(false);
  }, [i3, e2.body]), g = (0, import_react12.useCallback)(
    async (z2) => {
      await m2.updateComment({
        commentId: e2.id,
        comment: {
          body: i3.document
        },
        threadId: t2.id
      }), a3(false);
    },
    [e2, t2.id, i3, m2]
  ), b4 = (0, import_react12.useCallback)(async () => {
    await m2.deleteComment({
      commentId: e2.id,
      threadId: t2.id
    });
  }, [e2, t2.id, m2]), p4 = (0, import_react12.useCallback)(
    async (z2) => {
      m2.auth.canAddReaction(e2, z2) ? await m2.addReaction({
        threadId: t2.id,
        commentId: e2.id,
        emoji: z2
      }) : m2.auth.canDeleteReaction(e2, z2) && await m2.deleteReaction({
        threadId: t2.id,
        commentId: e2.id,
        emoji: z2
      });
    },
    [m2, e2, t2.id]
  ), C3 = (0, import_react12.useCallback)(async () => {
    await m2.resolveThread({
      threadId: t2.id
    });
  }, [t2.id, m2]), _2 = (0, import_react12.useCallback)(async () => {
    await m2.unresolveThread({
      threadId: t2.id
    });
  }, [t2.id, m2]), N3 = Qi(e2.userId);
  if (!e2.body)
    return null;
  let O2;
  const $6 = m2.auth.canAddReaction(e2), B4 = m2.auth.canDeleteComment(e2), I4 = m2.auth.canUpdateComment(e2), K6 = n && (t2.resolved ? m2.auth.canUnresolveThread(t2) : m2.auth.canResolveThread(t2));
  s2 || (O2 = (0, import_jsx_runtime10.jsxs)(
    c3.Generic.Toolbar.Root,
    {
      className: D2("bn-action-toolbar", "bn-comment-actions"),
      variant: "action-toolbar",
      children: [
        $6 && (0, import_jsx_runtime10.jsx)(
          pt2,
          {
            onEmojiSelect: (z2) => p4(z2.native),
            onOpenChange: d,
            children: (0, import_jsx_runtime10.jsx)(
              c3.Generic.Toolbar.Button,
              {
                mainTooltip: r4.comments.actions.add_reaction,
                variant: "compact",
                children: (0, import_jsx_runtime10.jsx)(ut, { size: 16 })
              },
              "add-reaction"
            )
          }
        ),
        K6 && (t2.resolved ? (0, import_jsx_runtime10.jsx)(
          c3.Generic.Toolbar.Button,
          {
            mainTooltip: "Re-open",
            variant: "compact",
            onClick: _2,
            children: (0, import_jsx_runtime10.jsx)(_o2, { size: 16 })
          },
          "reopen"
        ) : (0, import_jsx_runtime10.jsx)(
          c3.Generic.Toolbar.Button,
          {
            mainTooltip: r4.comments.actions.resolve,
            variant: "compact",
            onClick: C3,
            children: (0, import_jsx_runtime10.jsx)(Jo2, { size: 16 })
          },
          "resolve"
        )),
        (B4 || I4) && (0, import_jsx_runtime10.jsxs)(c3.Generic.Menu.Root, { position: "bottom-start", children: [
          (0, import_jsx_runtime10.jsx)(c3.Generic.Menu.Trigger, { children: (0, import_jsx_runtime10.jsx)(
            c3.Generic.Toolbar.Button,
            {
              mainTooltip: r4.comments.actions.more_actions,
              variant: "compact",
              children: (0, import_jsx_runtime10.jsx)(or, { size: 16 })
            },
            "more-actions"
          ) }),
          (0, import_jsx_runtime10.jsxs)(c3.Generic.Menu.Dropdown, { className: "bn-menu-dropdown", children: [
            I4 && (0, import_jsx_runtime10.jsx)(
              c3.Generic.Menu.Item,
              {
                icon: (0, import_jsx_runtime10.jsx)(Eo4, {}),
                onClick: h7,
                children: r4.comments.actions.edit_comment
              },
              "edit-comment"
            ),
            B4 && (0, import_jsx_runtime10.jsx)(
              c3.Generic.Menu.Item,
              {
                icon: (0, import_jsx_runtime10.jsx)(er, {}),
                onClick: b4,
                children: r4.comments.actions.delete_comment
              },
              "delete-comment"
            )
          ] })
        ] })
      ]
    }
  ));
  const ne3 = e2.createdAt.toLocaleDateString(void 0, {
    month: "short",
    day: "numeric"
  });
  if (!e2.body)
    throw new Error("soft deletes are not yet supported");
  return (0, import_jsx_runtime10.jsx)(
    c3.Comments.Comment,
    {
      authorInfo: N3 ?? "loading",
      timeString: ne3,
      edited: e2.updatedAt.getTime() !== e2.createdAt.getTime(),
      showActions: "hover",
      actions: O2,
      className: "bn-thread-comment",
      emojiPickerOpen: u2,
      children: (0, import_jsx_runtime10.jsx)(
        Ye,
        {
          autoFocus: s2,
          editor: i3,
          editable: s2,
          actions: e2.reactions.length > 0 || s2 ? ({ isEmpty: z2 }) => (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
            e2.reactions.length > 0 && !s2 && (0, import_jsx_runtime10.jsxs)(
              c3.Generic.Badge.Group,
              {
                className: D2(
                  "bn-badge-group",
                  "bn-comment-reactions"
                ),
                children: [
                  e2.reactions.map((Q3) => (0, import_jsx_runtime10.jsx)(
                    el,
                    {
                      comment: e2,
                      emoji: Q3.emoji,
                      onReactionSelect: p4
                    },
                    Q3.emoji
                  )),
                  $6 && (0, import_jsx_runtime10.jsx)(
                    pt2,
                    {
                      onEmojiSelect: (Q3) => p4(Q3.native),
                      onOpenChange: d,
                      children: (0, import_jsx_runtime10.jsx)(
                        c3.Generic.Badge.Root,
                        {
                          className: D2(
                            "bn-badge",
                            "bn-comment-add-reaction"
                          ),
                          text: "+",
                          icon: (0, import_jsx_runtime10.jsx)(ut, { size: 16 }),
                          mainTooltip: r4.comments.actions.add_reaction
                        }
                      )
                    }
                  )
                ]
              }
            ),
            s2 && (0, import_jsx_runtime10.jsxs)(
              c3.Generic.Toolbar.Root,
              {
                variant: "action-toolbar",
                className: D2(
                  "bn-action-toolbar",
                  "bn-comment-actions"
                ),
                children: [
                  (0, import_jsx_runtime10.jsx)(
                    c3.Generic.Toolbar.Button,
                    {
                      mainTooltip: r4.comments.save_button_text,
                      variant: "compact",
                      onClick: g,
                      isDisabled: z2,
                      children: r4.comments.save_button_text
                    }
                  ),
                  (0, import_jsx_runtime10.jsx)(
                    c3.Generic.Toolbar.Button,
                    {
                      className: "bn-button",
                      mainTooltip: r4.comments.cancel_button_text,
                      variant: "compact",
                      onClick: f6,
                      children: r4.comments.cancel_button_text
                    }
                  )
                ]
              }
            )
          ] }) : void 0
        }
      )
    }
  );
};
var ol = ({
  thread: e2,
  maxCommentsBeforeCollapse: t2
}) => {
  const n = w2(), o2 = M6(), r4 = Je(e2.resolvedBy ? [e2.resolvedBy] : []), i3 = e2.comments.map((c3, s2) => (0, import_jsx_runtime10.jsx)(
    nl,
    {
      thread: e2,
      comment: c3,
      showResolveButton: s2 === 0
    },
    c3.id + JSON.stringify(c3.body || "{}")
  ));
  if (e2.resolved && e2.resolvedUpdatedAt && e2.resolvedBy) {
    if (!r4.get(e2.resolvedBy))
      throw new Error(
        `User ${e2.resolvedBy} resolved thread ${e2.id}, but their data could not be found.`
      );
    const s2 = e2.comments.findLastIndex(
      (a3) => e2.resolvedUpdatedAt.getTime() > a3.createdAt.getTime()
    ) + 1;
    i3.splice(
      s2,
      0,
      (0, import_jsx_runtime10.jsx)(
        n.Comments.Comment,
        {
          className: "bn-thread-comment",
          authorInfo: e2.resolvedBy && r4.get(e2.resolvedBy) || "loading",
          timeString: e2.resolvedUpdatedAt.toLocaleDateString(void 0, {
            month: "short",
            day: "numeric"
          }),
          edited: false,
          showActions: false,
          children: (0, import_jsx_runtime10.jsx)("div", { className: "bn-resolved-text", children: o2.comments.sidebar.marked_as_resolved })
        },
        "resolved-comment"
      )
    );
  }
  return t2 && i3.length > t2 && i3.splice(
    1,
    i3.length - 2,
    (0, import_jsx_runtime10.jsx)(
      n.Comments.ExpandSectionsPrompt,
      {
        className: "bn-thread-expand-prompt",
        children: o2.comments.sidebar.more_replies(e2.comments.length - 2)
      },
      "expand-prompt"
    )
  ), i3;
};
function rl() {
  const e2 = T3(ne), t2 = w2(), n = M6(), o2 = Xe({
    trailingBlock: false,
    dictionary: {
      ...n,
      placeholders: {
        emptyDocument: n.placeholders.new_comment
      }
    },
    schema: e2.commentEditorSchema || Qe
  });
  return (0, import_jsx_runtime10.jsx)(t2.Comments.Card, { className: "bn-thread", children: (0, import_jsx_runtime10.jsx)(
    Ye,
    {
      autoFocus: true,
      editable: true,
      editor: o2,
      actions: ({ isEmpty: r4 }) => (0, import_jsx_runtime10.jsx)(
        t2.Generic.Toolbar.Root,
        {
          className: D2(
            "bn-action-toolbar",
            "bn-comment-actions"
          ),
          variant: "action-toolbar",
          children: (0, import_jsx_runtime10.jsx)(
            t2.Generic.Toolbar.Button,
            {
              className: "bn-button",
              mainTooltip: "Save",
              variant: "compact",
              isDisabled: r4,
              onClick: async () => {
                await e2.createThread({
                  initialComment: {
                    body: o2.document
                  }
                }), e2.stopPendingComment();
              },
              children: "Save"
            }
          )
        }
      )
    }
  ) });
}
function il(e2) {
  const t2 = v7(), n = T3(ne), o2 = E3(ne, {
    editor: t2,
    selector: (s2) => s2.pendingComment
  }), r4 = R4({
    editor: t2,
    selector: ({ editor: s2 }) => o2 ? {
      from: s2.prosemirrorState.selection.from,
      to: s2.prosemirrorState.selection.to
    } : void 0
  }), i3 = (0, import_react12.useMemo)(
    () => ({
      useFloatingOptions: {
        open: !!o2,
        // Needed as hooks like `useDismiss` call `onOpenChange` to change the
        // open state.
        onOpenChange: (s2) => {
          s2 || (n.stopPendingComment(), t2.focus());
        },
        placement: "bottom",
        middleware: [offset3(10), shift4(), flip3()]
      },
      elementProps: {
        style: {
          zIndex: 60
        }
      },
      ...e2.floatingUIOptions
    }),
    [n, t2, o2, e2.floatingUIOptions]
  ), c3 = e2.floatingComposer || rl;
  return (0, import_jsx_runtime10.jsx)(Ue, { position: r4, ...i3, children: (0, import_jsx_runtime10.jsx)(c3, {}) });
}
var ll = Object.freeze(Object.defineProperty({
  __proto__: null,
  default: il
}, Symbol.toStringTag, { value: "Module" }));
var tn3 = ({
  thread: e2,
  selected: t2,
  referenceText: n,
  maxCommentsBeforeCollapse: o2,
  onFocus: r4,
  onBlur: i3,
  tabIndex: c3
}) => {
  const s2 = w2(), a3 = M6(), u2 = T3(ne), d = Xe({
    trailingBlock: false,
    dictionary: {
      ...a3,
      placeholders: {
        emptyDocument: a3.placeholders.comment_reply
      }
    },
    schema: u2.commentEditorSchema || Qe
  }), m2 = (0, import_react12.useCallback)(async () => {
    await u2.threadStore.addComment({
      comment: {
        body: d.document
      },
      threadId: e2.id
    }), d.removeBlocks(d.document);
  }, [u2, d, e2.id]);
  return (0, import_jsx_runtime10.jsxs)(
    s2.Comments.Card,
    {
      className: "bn-thread",
      headerText: n,
      onFocus: r4,
      onBlur: i3,
      selected: t2,
      tabIndex: c3,
      children: [
        (0, import_jsx_runtime10.jsx)(s2.Comments.CardSection, { className: "bn-thread-comments", children: (0, import_jsx_runtime10.jsx)(
          ol,
          {
            thread: e2,
            maxCommentsBeforeCollapse: t2 ? void 0 : o2 || 5
          }
        ) }),
        t2 && (0, import_jsx_runtime10.jsx)(s2.Comments.CardSection, { className: "bn-thread-composer", children: (0, import_jsx_runtime10.jsx)(
          Ye,
          {
            autoFocus: false,
            editable: true,
            editor: d,
            actions: ({ isEmpty: h7 }) => h7 ? null : (0, import_jsx_runtime10.jsx)(
              s2.Generic.Toolbar.Root,
              {
                variant: "action-toolbar",
                className: D2(
                  "bn-action-toolbar",
                  "bn-comment-actions"
                ),
                children: (0, import_jsx_runtime10.jsx)(
                  s2.Generic.Toolbar.Button,
                  {
                    mainTooltip: a3.comments.save_button_text,
                    variant: "compact",
                    isDisabled: h7,
                    onClick: m2,
                    children: a3.comments.save_button_text
                  }
                )
              }
            )
          }
        ) })
      ]
    }
  );
};
function nn3() {
  const t2 = T3(ne).threadStore, n = (0, import_react12.useRef)(void 0);
  n.current || (n.current = t2.getThreads());
  const o2 = (0, import_react12.useCallback)(
    (r4) => t2.subscribe((i3) => {
      n.current = i3, r4();
    }),
    [t2]
  );
  return (0, import_react12.useSyncExternalStore)(o2, () => n.current);
}
function cl(e2) {
  const t2 = v7(), n = T3(ne), o2 = E3(ne, {
    editor: t2,
    selector: (a3) => a3.selectedThreadId ? {
      id: a3.selectedThreadId,
      position: a3.threadPositions.get(a3.selectedThreadId)
    } : void 0
  }), r4 = nn3(), i3 = (0, import_react12.useMemo)(
    () => o2 ? r4.get(o2.id) : void 0,
    [o2, r4]
  ), c3 = (0, import_react12.useMemo)(
    () => ({
      useFloatingOptions: {
        open: !!o2,
        // Needed as hooks like `useDismiss` call `onOpenChange` to change the
        // open state.
        onOpenChange: (a3, u2, d) => {
          d === "escape-key" && t2.focus(), a3 || n.selectThread(void 0);
        },
        placement: "bottom",
        middleware: [offset3(10), shift4(), flip3()]
      },
      elementProps: {
        style: {
          zIndex: 30
        }
      },
      ...e2.floatingUIOptions
    }),
    [n, t2, e2.floatingUIOptions, o2]
  ), s2 = e2.floatingThread || tn3;
  return (0, import_jsx_runtime10.jsx)(Ue, { position: o2 == null ? void 0 : o2.position, ...c3, children: i3 && (0, import_jsx_runtime10.jsx)(s2, { thread: i3, selected: true }) });
}
var al = Object.freeze(Object.defineProperty({
  __proto__: null,
  default: cl
}, Symbol.toStringTag, { value: "Module" }));
var sl = import_react12.default.memo(
  ({
    thread: e2,
    selectedThreadId: t2,
    maxCommentsBeforeCollapse: n,
    referenceText: o2
  }) => {
    const r4 = T3(ne), i3 = (0, import_react12.useCallback)(
      (s2) => {
        s2.target.closest(".bn-action-toolbar") || r4.selectThread(e2.id);
      },
      [r4, e2.id]
    ), c3 = (0, import_react12.useCallback)(
      (s2) => {
        if (!s2.relatedTarget || s2.relatedTarget.closest(".bn-action-toolbar"))
          return;
        const a3 = s2.target instanceof Node ? s2.target : null, u2 = s2.relatedTarget instanceof Node ? s2.relatedTarget.closest(".bn-thread") : null;
        (!a3 || !u2 || !u2.contains(a3)) && r4.selectThread(void 0);
      },
      [r4]
    );
    return (0, import_jsx_runtime10.jsx)(
      tn3,
      {
        thread: e2,
        selected: e2.id === t2,
        referenceText: o2,
        maxCommentsBeforeCollapse: n,
        onFocus: i3,
        onBlur: c3,
        tabIndex: 0
      }
    );
  }
);
function dl2(e2, t2, n) {
  if (t2 === "recent-activity")
    return e2.sort(
      (o2, r4) => r4.comments[r4.comments.length - 1].createdAt.getTime() - o2.comments[o2.comments.length - 1].createdAt.getTime()
    );
  if (t2 === "oldest")
    return e2.sort(
      (o2, r4) => o2.createdAt.getTime() - r4.createdAt.getTime()
    );
  if (t2 === "position")
    return e2.sort((o2, r4) => {
      var s2, a3;
      const i3 = ((s2 = n == null ? void 0 : n.get(o2.id)) == null ? void 0 : s2.from) || Number.MAX_VALUE, c3 = ((a3 = n == null ? void 0 : n.get(r4.id)) == null ? void 0 : a3.from) || Number.MAX_VALUE;
      return i3 - c3;
    });
  throw new O(t2);
}
function Ct4(e2, t2) {
  return e2.transact((n) => {
    if (!t2)
      return "Original content deleted";
    if (n.doc.nodeSize < t2.to)
      return "";
    const o2 = n.doc.textBetween(
      t2.from,
      t2.to
    );
    return o2.length > 15 ? `${o2.slice(0, 15)}…` : o2;
  });
}
function Nl2(e2) {
  const t2 = v7(), { selectedThreadId: n, threadPositions: o2 } = E3(ne), r4 = nn3(), i3 = (0, import_react12.useMemo)(() => {
    const c3 = Array.from(r4.values()), s2 = dl2(
      c3,
      e2.sort || "position",
      o2
    ), a3 = [];
    for (const u2 of s2)
      u2.resolved ? (e2.filter === "resolved" || e2.filter === "all") && a3.push({
        thread: u2,
        referenceText: Ct4(
          t2,
          o2.get(u2.id)
        )
      }) : (e2.filter === "open" || e2.filter === "all") && a3.push({
        thread: u2,
        referenceText: Ct4(
          t2,
          o2.get(u2.id)
        )
      });
    return a3;
  }, [r4, e2.sort, e2.filter, o2, t2]);
  return (0, import_jsx_runtime10.jsx)("div", { className: "bn-threads-sidebar", children: i3.map((c3) => (0, import_jsx_runtime10.jsx)(
    sl,
    {
      thread: c3.thread,
      selectedThreadId: n,
      editor: t2,
      referenceText: c3.referenceText,
      maxCommentsBeforeCollapse: e2.maxCommentsBeforeCollapse
    },
    c3.thread.id
  )) });
}
function Al(e2) {
  const t2 = q3();
  if (e2 || (e2 = t2 == null ? void 0 : t2.editor), !e2)
    throw new Error(
      "'editor' is required, either from BlockNoteContext or as a function argument"
    );
  return R4({
    editor: e2,
    selector: ({ editor: o2 }) => o2.getActiveStyles()
  });
}
function Zl(e2, t2) {
  return R4({
    editor: t2,
    selector: ({ editor: n }) => e2 ? n.getSelectionBoundingBox() : void 0
  });
}
function ul(e2) {
  return e2.currentTarget instanceof HTMLElement && e2.relatedTarget instanceof HTMLElement ? e2.currentTarget.contains(e2.relatedTarget) : false;
}
function Dl({
  onBlur: e2,
  onFocus: t2
} = {}) {
  const n = (0, import_react12.useRef)(null), [o2, r4] = (0, import_react12.useState)(false), i3 = (0, import_react12.useRef)(false), c3 = (u2) => {
    r4(u2), i3.current = u2;
  }, s2 = (u2) => {
    i3.current || (c3(true), t2 == null || t2(u2));
  }, a3 = (u2) => {
    i3.current && !ul(u2) && (c3(false), e2 == null || e2(u2));
  };
  return (0, import_react12.useEffect)(() => {
    const u2 = n.current;
    if (u2)
      return u2.addEventListener("focusin", s2), u2.addEventListener("focusout", a3), () => {
        u2 == null || u2.removeEventListener("focusin", s2), u2 == null || u2.removeEventListener("focusout", a3);
      };
  }, [s2, a3]), { ref: n, focused: o2 };
}
function Fl(e2) {
  return R4({
    editor: e2,
    selector: ({ editor: t2 }) => {
      var n;
      return ((n = t2.getSelection()) == null ? void 0 : n.blocks) || [t2.getTextCursorPosition().block];
    }
  });
}
function Oe4(e2) {
  return (
    // Creates inline content section element
    (0, import_jsx_runtime10.jsx)(
      NodeViewWrapper,
      {
        as: "span",
        className: "bn-inline-content-section",
        "data-inline-content-type": e2.inlineContentType,
        ...Object.fromEntries(
          Object.entries(e2.inlineContentProps).filter(([t2, n]) => {
            const o2 = e2.propSchema[t2];
            return n !== o2.default;
          }).map(([t2, n]) => [W(t2), n])
        ),
        children: e2.children
      }
    )
  );
}
function Gl(e2, t2) {
  var o2;
  const n = Node3.create({
    name: e2.type,
    inline: true,
    group: "inline",
    selectable: e2.content === "styled",
    atom: e2.content === "none",
    draggable: (o2 = t2.meta) == null ? void 0 : o2.draggable,
    content: e2.content === "styled" ? "inline*" : "",
    addAttributes() {
      return Ct2(e2.propSchema);
    },
    addKeyboardShortcuts() {
      return bo(e2);
    },
    parseHTML() {
      return Kt2(
        e2,
        t2.parse
      );
    },
    renderHTML({ node: r4 }) {
      const i3 = this.options.editor, c3 = wt(
        r4,
        i3.schema.inlineContentSchema,
        i3.schema.styleSchema
      ), s2 = t2.toExternalHTML || t2.render, a3 = Y4(
        (u2) => (0, import_jsx_runtime10.jsx)(
          s2,
          {
            contentRef: (d) => {
              u2(d), d && (d.dataset.editable = "");
            },
            inlineContent: c3,
            updateInlineContent: () => {
            },
            editor: i3
          }
        ),
        i3
      );
      return go(
        a3,
        e2.type,
        r4.attrs,
        e2.propSchema
      );
    },
    addNodeView() {
      const r4 = this.options.editor;
      return (i3) => ReactNodeViewRenderer(
        (c3) => {
          const s2 = useReactNodeView().nodeViewContentRef;
          if (!s2)
            throw new Error("nodeViewContentRef is not set");
          const a3 = t2.render;
          return (0, import_jsx_runtime10.jsx)(
            Oe4,
            {
              inlineContentProps: c3.node.attrs,
              inlineContentType: e2.type,
              propSchema: e2.propSchema,
              children: (0, import_jsx_runtime10.jsx)(
                a3,
                {
                  contentRef: (u2) => {
                    s2(u2), u2 && (u2.dataset.editable = "");
                  },
                  editor: r4,
                  inlineContent: wt(
                    c3.node,
                    r4.schema.inlineContentSchema,
                    r4.schema.styleSchema
                  ),
                  updateInlineContent: (u2) => {
                    const d = T(
                      [u2],
                      r4.pmSchema
                    ), m2 = c3.getPos();
                    m2 !== void 0 && r4.transact(
                      (h7) => h7.replaceWith(m2, m2 + c3.node.nodeSize, d)
                    );
                  }
                }
              )
            }
          );
        },
        {
          className: "bn-ic-react-node-view-renderer",
          as: "span"
          // contentDOMElementTag: "span", (requires tt upgrade)
        }
      )(i3);
    }
  });
  return xt(
    e2,
    {
      ...t2,
      node: n,
      render(r4, i3, c3) {
        const s2 = t2.render;
        return Y4((u2) => (0, import_jsx_runtime10.jsx)(
          Oe4,
          {
            inlineContentProps: r4.props,
            inlineContentType: e2.type,
            propSchema: e2.propSchema,
            children: (0, import_jsx_runtime10.jsx)(
              s2,
              {
                contentRef: (d) => {
                  u2(d), d && (d.dataset.editable = "");
                },
                editor: c3,
                inlineContent: r4,
                updateInlineContent: i3
              }
            )
          }
        ), c3);
      },
      toExternalHTML(r4, i3) {
        const c3 = t2.toExternalHTML || t2.render;
        return Y4((a3) => (0, import_jsx_runtime10.jsx)(
          Oe4,
          {
            inlineContentProps: r4.props,
            inlineContentType: e2.type,
            propSchema: e2.propSchema,
            children: (0, import_jsx_runtime10.jsx)(
              c3,
              {
                contentRef: (u2) => {
                  a3(u2), u2 && (u2.dataset.editable = "");
                },
                editor: i3,
                inlineContent: r4,
                updateInlineContent: () => {
                }
              }
            )
          }
        ), i3);
      }
    }
  );
}
function zl(e2, t2) {
  const n = Mark2.create({
    name: e2.type,
    addAttributes() {
      return St2(e2.propSchema);
    },
    parseHTML() {
      return Lt(e2);
    },
    renderHTML({ mark: o2 }) {
      const r4 = t2.render, i3 = Y4(
        (c3) => (0, import_jsx_runtime10.jsx)(
          r4,
          {
            editor: this.options.editor,
            value: e2.propSchema === "boolean" ? void 0 : o2.attrs.stringValue,
            contentRef: (s2) => {
              c3(s2), s2 && (s2.dataset.editable = "");
            }
          }
        ),
        this.options.editor
      );
      return V2(
        i3,
        e2.type,
        o2.attrs.stringValue,
        e2.propSchema
      );
    },
    addMarkView() {
      const o2 = this.options.editor;
      return (r4) => {
        const i3 = ReactMarkViewRenderer((c3) => {
          const s2 = (0, import_react12.useContext)(ReactMarkViewContext).markViewContentRef;
          if (!s2)
            throw new Error("markViewContentRef is not set");
          const a3 = t2.render;
          return (0, import_jsx_runtime10.jsx)(
            a3,
            {
              editor: o2,
              contentRef: (u2) => {
                s2(u2), u2 && (u2.dataset.markViewContent = "");
              },
              value: e2.propSchema === "boolean" ? void 0 : c3.mark.attrs.stringValue
            }
          );
        })(r4);
        return i3.didMountContentDomElement = true, i3;
      };
    }
  });
  return Me(e2, {
    ...t2,
    mark: n,
    render(o2, r4) {
      const i3 = t2.render, c3 = Y4(
        (s2) => (0, import_jsx_runtime10.jsx)(
          i3,
          {
            editor: r4,
            value: o2,
            contentRef: (a3) => {
              s2(a3), a3 && (a3.dataset.editable = "");
            }
          }
        ),
        r4
      );
      return V2(
        c3,
        e2.type,
        o2,
        e2.propSchema
      );
    },
    toExternalHTML(o2, r4) {
      const i3 = t2.render, c3 = Y4(
        (s2) => (0, import_jsx_runtime10.jsx)(
          i3,
          {
            editor: r4,
            value: o2,
            contentRef: (a3) => {
              s2(a3), a3 && (a3.dataset.editable = "");
            }
          }
        ),
        r4
      );
      return V2(
        c3,
        e2.type,
        o2,
        e2.propSchema
      );
    }
  });
}
function Ul(e2, t2) {
  const n = e2.getBoundingClientRect(), o2 = t2.getBoundingClientRect(), r4 = n.top < o2.top, i3 = n.bottom > o2.bottom;
  return r4 && i3 ? "both" : r4 ? "top" : i3 ? "bottom" : "none";
}
function jl(e2) {
  return (t2) => {
    e2.forEach((n) => {
      typeof n == "function" ? n(t2) : n != null && (n.current = t2);
    });
  };
}

export {
  At,
  D2 as D,
  autoUpdate,
  useFloating,
  offset3 as offset,
  shift4 as shift,
  limitShift3 as limitShift,
  flip3 as flip,
  size4 as size,
  hide3 as hide,
  arrow4 as arrow,
  require_shim,
  _t5 as _t,
  q3 as q,
  lo2 as lo,
  w2 as w,
  v7 as v,
  M6 as M,
  co2 as co,
  ao2 as ao,
  Et3 as Et,
  so2 as so,
  U4 as U,
  Bt3 as Bt,
  T3 as T,
  E3 as E,
  uo3 as uo,
  R4 as R,
  Ue,
  de3 as de,
  ar,
  Wt2 as Wt,
  dr,
  ur,
  mr,
  fr,
  hr2 as hr,
  gr,
  br3 as br,
  pr,
  Cr,
  vr,
  wr,
  kr,
  Hr,
  xr,
  Sr,
  Be3 as Be,
  Vr,
  qt3 as qt,
  _r,
  Er,
  Br,
  Lr,
  Rr,
  Or,
  Pr,
  Ar,
  Zr,
  Dr,
  Fr,
  Gr,
  zr,
  Ur,
  jr,
  $r,
  Xt3 as Xt,
  Yt3 as Yt,
  qr,
  Kr,
  Xr,
  Jr,
  ei,
  ti,
  oi,
  ri,
  li3 as li,
  ht2 as ht,
  ci,
  ui,
  mi,
  fi,
  hi,
  gi,
  bi,
  pi,
  wi,
  ki,
  Hi,
  xi,
  yl,
  Ei,
  Le3 as Le,
  ye2 as ye,
  We,
  qe,
  Li,
  Ri,
  Qt3 as Qt,
  Oi,
  Ii,
  Ke,
  Se2 as Se,
  Pi,
  Ni,
  Ai,
  Sl,
  Ml,
  en3 as en,
  Zi,
  Di,
  Fi,
  Vl,
  Tl,
  Ui,
  ji,
  $i,
  _l,
  El,
  Bl,
  Ll,
  Rl,
  Ol,
  Xe,
  Qi,
  Je,
  nl,
  ol,
  rl,
  il,
  tn3 as tn,
  nn3 as nn,
  cl,
  Ct4 as Ct,
  Nl2 as Nl,
  Al,
  Zl,
  Dl,
  Fl,
  Oe4 as Oe,
  Gl,
  zl,
  Ul,
  jl
};
/*! Bundled license information:

use-sync-external-store/cjs/use-sync-external-store-shim.development.js:
  (**
   * @license React
   * use-sync-external-store-shim.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js:
@blocknote/react/dist/blocknote-react.js:
  (**
   * @license React
   * use-sync-external-store-shim/with-selector.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

tabbable/dist/index.esm.js:
  (*!
  * tabbable 6.3.0
  * @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE
  *)

@blocknote/react/dist/blocknote-react.js:
  (**
   * @license React
   * use-sync-external-store-shim.production.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

@blocknote/react/dist/blocknote-react.js:
  (**
   * @license React
   * use-sync-external-store-shim.development.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)
  (**
   * @license React
   * use-sync-external-store-shim/with-selector.production.js
   *
   * Copyright (c) Meta Platforms, Inc. and affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)
*/
//# sourceMappingURL=chunk-PT7F464S.js.map
